When I use reverse()
or sort()
, I always need to save the return statement into a variable if I want to use it later.
@array=qw(Nick Susan Chet Dolly Bill);
@array = reverse(@array);
Why is this different from using push()
, pop()
or shift()
where you can just call the function and the array will be changed?
@array=qw(Nick Susan Chet Dolly Bill);
push(@array, "Bruce");
So what exactly is the difference between these "functions"?
reverse() . The reverse method will not modify the original array when used on the copy.
The reverse() method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
perldoc perlfunc
provides a major clue:
Functions for real @ARRAYs
each
,keys
,pop
,push
,shift
,splice
,unshift
,values
Functions for list data
grep
,join
,map
,qw//
,reverse
,sort
,unpack
And perldoc perlfaq4
explains the difference between arrays and lists (emphasis my own):
What is the difference between a list and an array?
(contributed by brian d foy)
A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars. An array can supply its collection for list operations, so list operations also work on arrays
...
Array operations, which change the scalars, rearrange them, or add or subtract some scalars, only work on arrays. These can't work on a list, which is fixed. Array operations include
shift
,unshift
,push
,pop
, andsplice
.
In short, list operations like reverse
are designed for lists, which cannot be modified.
The fact that they can accept arrays is merely a side-effect of list support.
Just use:
@array = reverse(@array)
I probably wouldn't recommend this, but if you really wanted to you could fix it...:
use Data::Dumper;
use strict;
use warnings;
use subs 'reverse';
my @array=qw(Nick Susan Chet Dolly Bill);
sub reverse(\@) {
my $a = shift;
@{$a} = CORE::reverse(@{$a})
}
reverse(@array);
print Dumper \@array;
#$VAR1 = ['Bill','Dolly','Chet','Susan','Nick'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With