Приглашаем посетить
Черный Саша (cherny-sasha.lit-info.ru)

Section A.3.  Answers for Chapter 4

Previous
Table of Contents
Next

A.3. Answers for Chapter 4

A.3.1. Exercise 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.

A.3.2. Exercise 2

First, we 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 we pass it to the first subroutine:

check_items_for_all(\%all);

In the subroutine, the first parameter is a hashref, so we 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, we 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;
  }
}


Previous
Table of Contents
Next