\@skipper, the result is a
reference to
that array. A reference to the array is like a pointer: it points at the array,
but it is not the array itself.
A reference fits wherever a scalar fits. It can go into an
element of an array or a hash, or into a plain scalar variable, like this:
- my $reference_to_skipper = \@skipper;
Because we can copy a reference, and passing an argument to a
subroutine is really just copying, we can use this code to pass a reference to
the array into the subroutine:
- my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
-
check_required_items("The Skipper", \@skipper);
sub check_required_items {
my $who = shift;
my $items = shift;
my @required = qw(preserver sunscreen water_bottle jacket);
for my $item (@required) {
unless (grep $item eq $_, @{$items}) { # not found in list?
print "$who is missing $item.\n";
}
}
}
in the above case, the dereference array can be written like @$items.
Now $items in the subroutine is a reference to the
array of @skipper.
Dereferencing the Array Reference
That is, wherever we write skipper to name the array, we use the
reference inside curly braces: { $items }. For example, both of these lines refer to the entire array:
@ skipper
@{ $items } #the $items is a reference to array.
whereas both of these refer to the second item of the array:
$ skipper [1]
${ $items }[1]
- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
-
check_required_items('The Skipper', \@skipper);
-
-
sub check_required_items{
-
#my $who = shift;
-
# my $items = shift;
-
my @required = qw(preserver sunscreen water_bottle jacket);
-
-
foreach my $item (@required){
-
unless( grep $item eq $_, @{$_[1]}){
-
print "$_[0] missing $item\n";
-
}
-
}
-
}
阅读(667) | 评论(0) | 转发(0) |