Why doesn't reverse () change my array?

When I use reverse() or sort() , I always need to store the return statement in 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 a function and the array will be changed?

 @array=qw(Nick Susan Chet Dolly Bill); push(@array, "Bruce"); 

So what is the difference between these "functions"?

+7
push perl reverse
source share
2 answers

perldoc perlfunc provides a basic hint:

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 (highlighting my own):

What is the difference between a list and an array?

(contributed by brian d foy)

A list is a fixed set of scalars. An array is a variable that contains a variable set of scalars. An array can provide collection for list operations, so list operations also work with arrays.

...

Array operations that modify scalars, rearrange them, or add or subtract some scalars only work with arrays . They cannot work on a list that is fixed. Array operations include shift , unshift , push , pop and splice .


In short, list operations, such as reverse , are for lists that cannot be changed.

The fact that they can accept arrays is just a side effect of list maintenance.

+14
source share

Just use:

 @array = reverse(@array) 

I probably would not recommend this, but if you really wanted you to be able to 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']; 
+1
source share

All Articles