Please have a look at bellow code. File contain test.csv
aa,OPEN,TEMP1
bb,CLOSE,TEMP2
cc,OPEN,TEMP3
dd,TERMINATED,TEMP4
Code:
use Data::Dumper;
sub main {
my $file = 'test.csv';
my @lines1;
my @values;
unless (open (INPUT, $file)) {
print " files does not exist";
}
while (my $line = <INPUT>) {
@values = split /\s*,\s*/, $line;
push @lines1, \@values;
}
foreach my $rr(@lines1) {
print Dumper ($rr)."\n";
}
close INPUT;
}
main();
CODE RESULT:
$VAR1 = [
'dd',
'TERMINATED',
'TEMP4
'
];
$VAR1 = [
'dd',
'TERMINATED',
'TEMP4
'
];
$VAR1 = [
'dd',
'TERMINATED',
'TEMP4
'
];
$VAR1 = [
'dd',
'TERMINATED',
'TEMP4
'
];
Now when I run the code all I get is last line printed 4 times.
but I declare array @values inside while loop everything works fine.
Can someone please explain me this strange behaviour.?
Thanks
my @values = split /\s*,\s*/, $line;as@valuesdoesn't need to be visible outsidewhileloop, and as a side effect you get rid of unwanted behavior.@valuesarray =>print \@values, "\n";