3

What is the difference between

myArr1 => \@existingarray

and

myArr2 => [
              @existingarray
          ]

I am assigning the @existingarray to a element in a hash map.

I mean what exactly internally happens. Is it that for the first one, it points to the same array and for the second array it creates a new array with the elements in the @existingarray

Thanks in advance

1
  • 1
    They both give syntax errors :-) Commented Sep 20, 2012 at 9:34

3 Answers 3

8

Yes, the first one takes a reference, the second one does a copy and then takes a reference.

[ ... ] is the anonymous array constructor, and turns the list inside into an arrayref.

So with @a = 1, 2, 3,

[ @a ]

is the same as

[ 1, 2, 3 ]

(the array is flattened to a list) or

do {
  my @b = @a;
  \@b;
}

In effect, the elements get copied.

Also,

my ($ref1, $ref2) = (\@a, [@a]);
print "$ref1 and $ref2 are " . ($ref1 eq $ref2 ? "equal" : "not equal") . "\n";

would confirm that they are not the same. And if we do

$ref1->[0] = 'a';
$ref2->[0] = 'b';

then $a[0] would equal a and not b.

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

Comments

3

You can use

perl -e 'my @a=(1); my $ra=\@a; my $rca=[@a]; $ra->[0]=2; print @a, @{$ra}, @{$rca};'
221

to see that your assumption that [@existingarray] creates a reference to a copy of @existingarray is correct (and that myArray* isn't Perl).

WRT amon's revising my perl -e "..." (fails under bash) to perl -e '...' (fails under cmd.exe): Use the quotes that work for your shell.

Comments

2

The square brackets make a reference to a new array with a copy of what's in @existingarray at the time of the assignment.

Comments

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.