Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: question about what to grep(?)

by Don Coyote (Pilgrim)
on Apr 12, 2013 at 11:46 UTC ( #1028344=note: print w/replies, xml ) Need Help??

in reply to question about what to grep(?)

Checkout Filter

I will expect you mean the values of the keys of the hash are arrays, which is a common structure. For selecting, grep is a good operator. You also want to understand how to access the arrays to carry out the conditional test.

To build an array of the keys of arrays held by the keys of baskets which have 10 items or less:

my %baskets = ( ten => [0..9], bat => [0..8,'bat:-:laser-disruptor'], elf => [0..10], ); my @tenorless = grep { @{ $baskets{$_} } =< 10 } keys %baskets; # print @tenorless # batten

In this example, we access the array by providing the hashvalue through the key and dereferencing it with the array sigil and curly braces. Obtaining the scalar context of number of items.

You can now happily process the baskets in your 10 items or less queue, the baskets with more having been laser blasted to smithereens.

Of the baskets holding the requisite number of items, some contain goods other than groceries, such as hero equipment, which need to be checked out in the kickass department. Now we really need to access the items inside the arrays. To do this we pass in our newly formed list to a further grep. Similar to adding further foreach loops.

All we need to watch for is assigning the special variable $_ in each 'outer' grep we use so we can repel magnetic pulse traps and displace gravity gracefully.

#!usr/bin/perl use warnings; use strict; my @batgoods = map {'bat:-:'.$_}qw(night-visor laser-disruptor zipwire +-refill); my %baskets = ( ten => [0..9], bat => [0..8,'bat:-:laser-disruptor'], elf => [0..10], ); my @tenorless = grep { @{$baskets{$_}} <= 10 } keys %baskets; my @hasbat = grep { my $key = $_; grep { my $batitem = $_; grep {$_ =~ $batitem} @{$baskets{$key}}; } @batgoods; } @tenorless; print @hasbat; # bat exit 0;

grep, foreach for heros and heroines!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1028344]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2017-09-22 05:47 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (257 votes). Check out past polls.