Perl Cd Bookshelf [Electronic resources]

نسخه متنی -صفحه : 875/ 706
نمايش فراداده

A.2. Answers for Chapter 3<a class="libraryIndexlink" href="index.aspx?pid=31159&BookID=23871&PageIndex=457&Language=3#lrnperlorm-CHP-3-SECT-9.1">Section 3.9.1</a>)

A.2. Answers for Chapter 3

Section 3.9.1)

They''re all referring to the same thing, except for the second one, ${$ginger[2]}[1]. That one is the same as $ginger[2][1], whose base is the array @ginger, rather than the scalar $ginger.

Section 3.9.2)

First, construct the hash structure:

my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
my @professor = qw(sunscreen water_bottle slide_rule batteries radio);
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
my %all = (
"Gilligan" => \@gilligan,
"Skipper" => \@skipper,
"Professor" => \@professor,
);

Then pass it to the first subroutine:

check_items_for_all(\%all);

In the subroutine, the first parameter is a hashref, so dereference it to get the keys and the corresponding values:

sub check_items_for_all {
my $all = shift;
for my $person (sort keys %$all) {
check_required_items($person, $all->{$person});
}
}

From there, call the original subroutine:

sub check_required_items {
my $who = shift;
my $items = shift;
my @required = qw(preserver sunscreen water_bottle jacket);
my @missing = ( );
for my $item (@required) {
unless (grep $item eq $_, @$items) { # not found in list?
print "$who is missing $item.\n";
push @missing, $item;
}
}
if (@missing) {
print "Adding @missing to @$items for $who.\n";
push @$items, @missing;
}
}