I am inching my way through INTERMEDIATE PERL and tried using hashes to
solve Chapter 4, Problem 2.  I never used hashes before but my attempted
solution convinced me of their value as contrasted to the solution with
arrays.

The Problem:  My solution works but with an error I can't eliminate.

The difficulty is in the next to last line, the 'unless ...' statement
which causes warning:
 
Use of uninitialized value in string eq at chap4-take6.pl line 49.

Here is the complete program:


#!/usr/bin/perl -w
#
use strict;

my %required_list = ( 
        life_jacket => 'preserver',
        lotion => 'sunscreen',
        water => 'water_bottle',
        coat => 'jacket',
);

my %captain = (
        name => 'skipper',
        life_jacket => 'preserver',
        lotion => 'sunscreen',
        water => 'water_bottle',
        shirt => 'blue_shirt',
        coat => 'jacket',
        hat => 'cap',
);

my %mate = (
        name => 'gilligan',
        shirt => 'red_shirt',
        hat => 'cap',
        socks => 'lucky_socks',
        water => 'water_bottle',
);

my %passenger = (
        name => 'professor',
        lotion => 'sunscreen',
        water => 'water_bottle',
        calculator => 'slide_rule',
        power_supply => 'batteries',
       entertainment => 'radio',
);

my @crew = (\%captain, \%mate, \%passenger);


check_required_items (@crew);

sub check_required_items {
        foreach my $person (@crew) {
                my $who = ${$person} {'name'};
                my @keys = keys %required_list;  
                foreach (@keys) {
                        unless ($required_list {"$_"} eq ${$person} {"$_"}) {
                                print "$who is missing $_\n";
                        }       
                }
        }
}

I would be very greatful for a solution to this problem as I think it
very neat that the hashes for the individuals can contain different
numbers of entries in arbitrary order.  I would like to be able to use
the approach with confidence in the future.  

For completeness here is the output of the program with STDERR
redirected to STDOUT:


Use of uninitialized value in string eq at chap4-take6.pl line 49.
Use of uninitialized value in string eq at chap4-take6.pl line 49.
Use of uninitialized value in string eq at chap4-take6.pl line 49.
Use of uninitialized value in string eq at chap4-take6.pl line 49.
Use of uninitialized value in string eq at chap4-take6.pl line 49.
gilligan is missing coat
gilligan is missing lotion
gilligan is missing life_jacket
professor is missing coat
professor is missing life_jacket

When the program is run without redirection the warnings and print
statements alternate.  There is no output for the skipper as his hash
has all the required items.

Thanks for any guidance,

Tom

-- 
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to