Bhaskar Santosh K Bhaskar Santosh K - 1 month ago 5
Perl Question

How to get the data of each line from a file?

Here, I want to print the data in each line as 3 separate values with "

:
" as separator. The file
BatmanFile.txt
has the following details:

Bruce:Batman:bat@bat.com
Santosh:Bhaskar:santosh@santosh.com


And the output I expected was:

Bruce
Batman
bat@bat.com
Santosh
Bhaskar
santosh@santosh.com


The output after executing the script was:

Bruce
Batman
bat@bat.com
Bruce
Batman
bat@bat.com


Please explain me what I am missing here:

use strict;
use warnings;

my $file = 'BatmanFile.txt';
open my $info, $file or die "Could not open $file: $!";
my @resultarray;
while( my $line = <$info>) {
#print $line;
chomp $line;
my @linearray = split(":", $line);
push(@resultarray, @linearray);
print join("\n",$resultarray[0]),"\n";
print join("\n",$resultarray[1]),"\n";
print join("\n",$resultarray[2]),"\n";
}
close $info;

Answer

When you do:

push(@resultarray, @linearray);

you're pushing @linearray into @resultarray at the end, so index 0 through 2 is still the items from the first time you pushed @linearray.

To overwrite @resultarray with the values from the second iteration, do:

@resultarray = @linearray;

instead.

Alternatively, use unshift to place @linearray at the start of @resultarray, as suggested by Sobrique:

unshift @resultarray, @linearray;
Comments