Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

#!/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.

#!/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.