LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   perl code to split multiple lines of data into 2columns (https://www.linuxquestions.org/questions/linux-newbie-8/perl-code-to-split-multiple-lines-of-data-into-2columns-4175414105/)

lakssreedhar 06-30-2012 01:16 AM

perl code to split multiple lines of data into 2columns
 
Hi
I have a data somewhat in the below format
{MCL}who is this.{/MCL}
{RP}what a shame.{/RP}
I would like to write a code to split the file as follows
who MCL
is o
this o
. MCL
and similar for all lines.The code i developed using split function just splits the above in a single column.awaiting reply and thanks in advance

Snark1994 06-30-2012 05:20 AM

Give us your code and we'll see how to improve it :)

lakssreedhar 07-02-2012 01:56 AM

I have done something llike this.But the output is not in the expected format.
#!/usr/bin/perl

while(<>)
{

#replace multiple .'s by a single .
$_ =~ s/\.\.+/ /ig;

#split multiple sentences into an array.
next if($_ eq undef);
@arr=split(/\t/,$_);
print"$arr[0]\t$arr[1]\n";
}

pan64 07-02-2012 03:21 AM

just please give us a sample input and output (a bit more, if possible) and also please use [code][/code] to keep formatting of your code.

try the following:
1. use #!/usr/bin/perl -w at the beginning ( so add -w )
2. add this as second line: use strict;
these will ensure you will write better code
3. the line: next if($_ eq undef); is meaningless, $_ always has value (because otherwise the while loop will be terminated)
4. you ought to need check if @arr has 2 elements

chrism01 07-02-2012 06:50 PM

In addition to the excellent advice above
Code:

#replace multiple .'s by a single .
None of your input has multiple successive '.'s

Code:

#split multiple sentences into an array.
By default, Perl is line oriented, so I think you mean words not sentences here. Also, your code implies tabs between the 'words'; is that right?

Also, please use code tags for posting code https://www.linuxquestions.org/quest...do=bbcode#code


All times are GMT -5. The time now is 07:46 PM.