Change values in a reference


If you create a copy of an array then the two arrays are separated. Change to any of the arrays is not reflected in the other array.


examples/references/copy_array.pl
#!/usr/bin/env perl
use strict;
use warnings;

my @names = qw(Foo Bar);
my @copy_names = @names;
$copy_names[0] = 'Baz';

print "$names[0]\n";       # Foo
print "$copy_names[0]\n";  # Baz

When you create a reference to an array, then the referenced array has the same memory location, hence change in either one of them is a change in both of them.


examples/references/change_reference.pl
#!/usr/bin/env perl
use strict;
use warnings;

my @names = qw(Foo Bar);
my $names_ref = \@names;

$names_ref->[0] = 'Baz';
print "$names[0]\n";        # Baz
print "$names_ref->[0]\n";  # Baz

That means you can pass to a function an array reference, then from within the function it is easy to change the content of the original array.