Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reverse() not change my array?

Tags:

push

reverse

perl

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"?

like image 827
S. Tanghe Avatar asked Jun 04 '14 09:06

S. Tanghe


People also ask

Does Reverse () modify the original array?

reverse() . The reverse method will not modify the original array when used on the copy.

Does reverse mutate an array?

The reverse() method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.


2 Answers

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, and splice.


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.

like image 102
Zaid Avatar answered Sep 28 '22 12:09

Zaid


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'];
like image 38
John C Avatar answered Sep 28 '22 13:09

John C