In the following C# code:
int[] X = new int[2];
X[0] = 1;
X[1] = 2;
int[] Y = X;
X[1] = 3;
After this executes, Y[1] will also be 3 since the o
In Perl an array is not a pointer.
You can get the reference of an array 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 (i.e., $array[0]
will be 3)
You're using a reference in the C# program, but not in the Perl program. It works the same if you use a reference 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 could 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
The way to create a reference to a specific named variable is by using backslash like so:
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 may also create a reference by using an anonymous array:
my $x = [1,2]; # square brackets create array reference
my $y = $x; # points to the same memory address
The reference is a scalar value, so it would be $y
in your case. If you put an array reference into an array, you get a two-dimensional array, which is handy to know for future reference. E.g.:
my @two = (\@x, \@y); # $two[0][0] is now $x[0]
my @three = ( [1,2], [3,4], [4,5] ); # using anonymous arrays
Try doing 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