0
use Data::Dump qw(dump);
my @arr = [1];
wrap(\@arr);
dump(@arr);
sub wrap {
    my @a = @_;
    push @a,2;
    unshift @a, 0;
    dump(@a);
}

result:

[1]

(0, [[1]], 2)

There are two issues here:

  1. pass an array by ref to a sub - and expect it to be modified afterward

  2. why push and unshift don't just extend the array - what's that array nesting?

(new to perl)

1 Answer 1

2
my @arr = [1];

This creates an array with one item in it -- and that item is an array reference to an anonymous array (created by using square brackets) containing your 1. You probably should've gone with my @arr = (1);

wrap(\@arr);

That's fine - it passes a reference to your @arr array.

sub wrap {
    my @a = @_;

You don't dereference this, so now your @a array contains an array reference containing an array reference containing 1. Your array would look something like this: @a = ( [ [ 1 ] ] )

    push @a, 2;    # @a = ([[1]], 2);
    unshift @a, 0; # @a = (0, [[1]], 2);

Inside wrap you'd have a scalar array reference in the arguments, so you'd put it in a scalar instead of an array:

    my ($aref) = @_; # or:  my $aref = shift;

and dereference it with a leading @:

    push @$aref, 2;
    unshift @$aref, 0;

See also perldoc perlref.

Sign up to request clarification or add additional context in comments.

2 Comments

I read that [] defines array and () defines list which is immutable - therefore I used []
[] creates an anonymous array and returns a reference to it. (but you don't want a reference here.) () has almost nothing to do with lists, it just adjusts precedence (e.g. my @x=1 is fine and assigns a one element list; my @x=1,2 doesn't work because it is interpreted as (my @x=1),2; my @x=(1,2) is what you commonly see, but the parentheses only serve to make the assignment get the result of the , list-concatenation operator as its right operand instead of having the , operator get the result of the asssignment as its left operand)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.