home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Learning Perl Objects, References & ModulesLearning Perl Objects, References & ModulesSearch this book

A.2. Answers for Chapter 3

A.2.1. Exercise 1 (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.

A.2.2. Exercise 2 (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;
  }
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.