Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing array using array name and reference to array

Tags:

perl

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?

like image 334
Rohit Jain Avatar asked Dec 03 '25 12:12

Rohit Jain


1 Answers

reverse @digits, reverse @$digits, "\n"

means

reverse(@digits, reverse(@$digits, "\n"))

You want

reverse(@digits), reverse(@$digits), "\n"

or simply

reverse(@$digits, @digits), "\n"
like image 121
ikegami Avatar answered Dec 06 '25 05:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!