I have declared an array, and a reference to that array like this: -
my @array = (1, 2, 3, 4);
my $aref = \@array;
Now, I'm trying to reverse the array, using the array name and the reference name.
print reverse @array, "\n";
print reverse @{$aref}, "\n";
This is working fine, and printing the reversed array in both the cases: -
4321
4321
However, if I try to print the reverse in the same line, its giving me a strange result: -
print reverse @array, reverse @{$aref}, "\n";
Now, I got this output: -
1234
4321
and if I add a newline in between: -
print reverse @array, "\n", reverse @{$aref}, "\n";
I got this output: -
1234
4321
So, there are two problems as you can see: -
- 1st, The array is not getting reversed for using the name
- 2nd, there is an extra newline getting printed between the two reversed array.
I can't understand this behaviour, why this could be happening. Also I went through the documentation of the function reverse to check whether there is mentioned any where about this behaviour, but I didn't dine any. Can anyone explain what's happening here?
1 Answer 1
reverse @digits, reverse @$digits, "\n"
means
reverse(@digits, reverse(@$digits, "\n"))
You want
reverse(@digits), reverse(@$digits), "\n"
or simply
reverse(@$digits, @digits), "\n"
2 Comments
parenthesis can be removed where it does not change the meaning. :( Thank you so much. :)
perl -MO=Deparse ...helps you see what Perl is seeing more easily