The code:
push @data, (split//, $line);
pushes all items on the current line into @data
and
push @data, [split //, $line];
Pushes a reference to an anonymous array containing those items into @data
If you're only ever processing one value of '$line' its probably more effective to use the former*1 , however, if you are processing a file that contains multiple lines and you want to differentiate between the lines the content is on, the latter is more effective.
Consider:
my @data;
while( my $line = <$fh> ){
push @data , ( split //, $line );
}
use Data::Dumper;
$Data::Dumper::Indent = 0;
$Data::Dumper::Terse = 1;
print Dumper( \@data );
This will yield all of the bytes read in as separate characters, a single
array containing them all, i.e.:
[ "a", "b" , "c" , "\n", "d", "e", "f" ]
When this instead will do something entirely different:
my @data;
while( my $line = <$fh> ){
push @data , [ split //, $line ];
}
use Data::Dumper;
$Data::Dumper::Indent = 0;
$Data::Dumper::Terse = 1;
print Dumper( \@data );
And will instead group lines like so:
[ [ "a", "b", "c" , "\n" ], [ "d" , "e", "f" , "\n" ] ]
So you can later programmatically traverse it easier.
Note:
push @data, ( split //, $line );
and
push @data, split //, $line;
Are equivalent.
Also,
my @other = ( 1,2,3 );
push @data, @other ;
and
push @data, 1,2,3;
are equivalent.
From perldoc -f push
push ARRAY,LIST
Treats ARRAY as a stack, and pushes the values of LIST onto the end of ARRAY. The length of ARRAY increases by the length of LIST. Has the same effect as
for $value (LIST) {
$ARRAY[++$#ARRAY] = $value;
}
but is more efficient. Returns the number of elements in the array following the completed "push".
*1: actually, tbf, anyone with half a brain would probably want @data = split //, $line