in reply to Using grep for many-to-many relationships
#!/usr/local/bin/perl use warnings; use strict; use Data::Dumper; my %pangolin = ( 'ant' => 15 , 'termite' => 34 ); my %komodo = ( 'newt' => 34 , 'crock' => 3 , 'ant' => 60 , 'termite' => 90 ); my @shops = ( { 'ant' => 10 , 'termite' => 14 } , { 'newt' => 25 , 'crock' => 6 , 'termite' => 80 } , { 'crock' => 3 } ); for my $killer ( \%pangolin , \%komodo ) { # Prints player's statistics & accessible shops as indices of @shop +s. my @ok = find_accessible_shops( $killer , \@shops ); print Dumper( $killer , \@ok ); } exit; # Given a player's statistics as hash reference & a array reference o +f hash # references of shops, returns the indices (of the array reference). sub find_accessible_shops { my ( $player , $shops ) = @_; my @accessible; DEALER: for my $dealer ( 0 .. scalar @{ $shops } - 1 ) { my $allow; REQUIRE: for my $victim ( keys %{ $shops->[ $dealer ] } ) { next DEALER unless exists $player->{ $victim }; $allow = ( defined $allow ? $allow : 1 ) && $shops->[ $dealer ]->{ $victim } <= $player->{ $victim } ; } push @accessible , $dealer if $allow; } return @accessible; }
About 18.5 hours later: Above sub now returns a list instead of array reference, which was originally there to mistakenly simplify the print Dumper( ... ) statement.
About 2 days later, in the sub, removed explicit sentinel variable (to inidicate first iteration, set to -1) as $allow can be appropriated for the purpose (see my $allow;). That also takes care of the bug in case the inner loop does not run causing @accessible to fill erroneously (note to self: -1 is a true value).
|
---|