Assign the address of one array to another in Perl?

In the following C # code:

int[] X = new int[2]; X[0] = 1; X[1] = 2; int[] Y = X; X[1] = 3; 

After that, Y [1] will also be 3, since the operation Y = X does not make a clone, but rather assigns a link or pointer that X points to Y.

If the same operation is performed in Perl 5:

 my @X = (1, 2); my @Y = @X; $X[1] = 3; 

Unlike C #, Y [1] is not 3, but 2, which indicates that Perl makes a copy of the array after the operation @Y = @X.

So my question is: is there a way to assign or initialize a Perl 5 array with reference to another Perl array so that they both point to the same data? I already know about references and tried to dereference the array reference, but that also makes a copy. I also know that using an array reference will solve most of what I'm trying to do, so I don't need answers showing how to work with links.

0
source share
4 answers

You are using the link in a C # program, but not in a Perl program. It works the same if you use the link in Perl.

 my $X = [ 1, 2 ]; my $Y = $X; $X->[1] = 3; print "@$Y\n"; # 1 3 

or

 my @X = ( 1, 2 ); my $Y = \@X; $X[1] = 3; print "@$Y\n"; # 1 3 

You can also create an alias.

 use Data::Alias qw( alias ); my @X = ( 1, 2 ); alias my @Y = @X; $X[1] = 3; print "@Y\n"; # 1 3 
+4
source

A way to create a reference to a specific named variable is to use a backslash:

 my @x = (1,2); my $y = \@x; # create reference by escaping the sigil $y->[1] = 3; # $x[1] is now 3 for ( @$y ) { print } # how to reference the list of elements 

You can also create a link using an anonymous array:

 my $x = [1,2]; # square brackets create array reference my $y = $x; # points to the same memory address 

The link is a scalar value, so in your case it will be $y . If you put the array reference in an array, you will get a two-dimensional array, which is convenient for future use. For instance:.

 my @two = (\@x, \@y); # $two[0][0] is now $x[0] my @three = ( [1,2], [3,4], [4,5] ); # using anonymous arrays 
+2
source

Try to do this:

 my @X = (1, 2); my $ref = \@X; # $ref in now a reference to @X array (the magic is `\`) $ref->[0] = "foobar"; # assigning "foobar" to the first key of the array print join "\n", @X; # we print the whole @X array and we see that it was changed 
+1
source

In Perl, an array is not a pointer.

You can get an array reference with the \ operator:

 my @array = ( 1, 2 ); my $array_ref = \@array; 

$array_ref will then point to the original array (as in C)

 ${$array_ref}[0] = 3 

will change the first cell of the original array (ie $array[0] will be 3)

+1
source

All Articles