I came across this syntax while reading a script. I am not sure what is the use of square brackets.
push @data, [ split //, $line ]; #printing this array gives crap values
Or to put into other words what is the difference between the above and the following?
push @data, (split//, $line); #printing this gives actual values
Any suggestions?
The code:
pushes all items on the current line into
@dataand
Pushes a reference to an anonymous array containing those items into
@dataIf 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:
This will yield all of the bytes read in as separate characters, a single
array containing them all, i.e.:
When this instead will do something entirely different:
And will instead group lines like so:
So you can later programmatically traverse it easier.
Note:
and
Are equivalent.
Also,
and
are equivalent.
From
perldoc -f pushpush 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