Array of Arrays in Perl
The following code snippet provides the often-saught Array of Arrays in Perl. This is my take on the Array of Arrays exercise from the book of Intermediate Perl, also known as the Alpaca book.
sub check_required_items {
my $who = shift;
my $items = shift;
my %whose_items = map { $_, 1 } @$items;
my @required = qw(preserver sunscreen water_bottle jacket);
my @missing = ( );
for my $item (@required) {
unless ($whose_items{$item}) {
print "$who is missing $item.\n";
push @missing, $item;
}
}
if(@missing) {
print "Adding @missing to @$items for $who.\n";
push @$items, @missing;
}
}
sub check_items_for_all {
my $all_with_names_ref = shift;
foreach my $person (keys %$all_with_names_ref) {
check_required_items($person,\@{$$all_with_names_ref{$person}});
}
}
my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
my @professor = qw(sunscreen water_bottle slide_rule batteries radio);
my %all = (
Gilligan => \@gilligan,
Skipper => \@skipper,
Professor => \@professor,
);
check_items_for_all(\%all);
Written by Jason McVeigh
Related protips
2 Responses
I made this!
over 1 year ago
·
I ♥ what I do and I hope you do too!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Perl array arrays
Authors
Related Tags
#perl array arrays
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#