Passing references to subroutines
Passing a reference avoids copying big data and lets a subroutine change the original.
In this page:
Passing references to subroutines
When you pass arrays or hashes directly, Perl flattens them into one list in @_, so two arrays would be merged and you lose the boundary. Passing references keeps each structure intact and cheap to pass. The subroutine can read through the reference and, since it is not a copy, changes made through it are visible to the caller.
Note:
Use ref($arg) eq ARRAY to check that the caller really passed an array reference.
Example: Passing references to subroutines
use strict;
use warnings;
sub flat_count { return scalar @_; }
sub ref_counts { my ($p, $q) = @_; return scalar(@$p) . " and " . scalar(@$q); }
sub add_item { my ($list, $item) = @_; push @$list, $item; return; }
my @first = (1, 2, 3);
my @second = (4, 5);
print "flattened count: ", flat_count(@first, @second), "\n";
print "with references: ", ref_counts(\@first, \@second), "\n";
add_item(\@first, 99);
print "first is now: @first\n";
my @copy = @first;
push @copy, 100;
print "copy: @copy\n";
print "original: @first\n";
# Output:
# flattened count: 5
# with references: 3 and 2
# first is now: 1 2 3 99
# copy: 1 2 3 99 100
# original: 1 2 3 99
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Passing two arrays directly and expecting them to stay separate
- Modifying data through a reference by accident
- Copying a reference and thinking you copied the data
Chapter Summary
- Arrays passed directly are flattened
- Pass \@array to keep it intact
- Changes through a reference affect the caller
- Use ref to validate arguments
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: