Keen Sage
Keen Sage

Reputation: 1959

Array assignment in Perl

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

Upvotes: 3

Views: 2058

Answers (3)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

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.

Upvotes: 3

amon
amon

Reputation: 57650

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.

Upvotes: 8

librarian
librarian

Reputation: 129

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

Upvotes: 2

Related Questions