Reference Parameters
In Perl you cannot directly pass arrays or associative arrays to functions.
If you try to do so, then Perl will concatenate the contents to produce a
single array of arguments. For example:
sub print_arrays {
my (@a, @b) = @_; # @a = ('dog', 'cat', 'bird', 10, 20, 30)
# @b = undef
}
@x = ('dog', 'cat', 'bird');
@y = (10, 20, 30);
print_arrays(@x, @y);
You will need to pass a reference to an array if you want to access it
in a subroutine. A reference is much like a pointer in C except that the
"address-of" operator is \. A reference is a scalar value and
so the variable that holds it is prefixed with a $. You can de-reference
the scalar value using the appropriate type operator--$, @, or %.
Here's an example of a reference to a scalar variable:
$a = 10;
$b = \$a;
$$b = 20; # $a = 20
Getting an array reference is similar:
sub print_arrays {
my ($a, $b) = @_; # array references are scalar values
print "a = ";
print join(", ", @$a); # dereference the reference to @x
print "\nb = ";
print join(", ", @$b); # dereference the reference to @y
print "\n";
}
@x = ('dog', 'cat', 'bird');
@y = (10, 20, 30);
print_arrays(\@x, \@y);
output:
a = dog, cat, bird
b = 10, 20, 30
Using References to Build Complex Data Structures
As noted earlier in the course, you can use a hash table to simulate
a record. Now suppose you have an application that requires you to create
a number of records and store them in an array. To do so you are going to
have to create references to "anonymous" hash tables. You have seen how to create
a named hash table:
%new_rec = ("name", "brad", "age", 23);
You can also create anonymous hash tables using {} notation and assign the
result to a reference variable. For example:
$new_rec = { "name" => "brad", "age" => 23 };
Note the use of the => operator to associate values with keys.
Here is how we can use anonymous hash tables to read records with a name
and an age from a file and store them in an array:
@emp_records = ();
while ($employee = <>) {
@data = split / +/, $employee;
$new_rec = { "name" => $data[0], "age" => $data[1] };
push(@emp_records, $new_rec);
}
At the end of this code fragment we have an array of references to hash
tables, which are simulating our employee records. We can now use the following
code fragment to sort the records by employee name:
@sorted_emp_records = sort { $$a{"name"} cmp $$b{"name"}} @emp_records;
for $rec (@sorted_emp_records) {
printf %-10s %3d\n", $$rec{"name"}, $$rec{"age"};
}
input:
brad 43
nels 41
james 73
katrina 70
output:
brad 43
james 73
katrina 70
nels 41
We can also create anonymous arrays via the [] operator:
$new_array = [10, 20, 30];
To recap:
- Create a named array or hash table using ()'s.
- Create anonymous arrays that return a reference using []'s.
- Create anonymous hash tables that return a reference using {}'s