Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Grep with AoA [Solved]

by davies (Vicar)
on Aug 27, 2012 at 09:28 UTC ( #989950=perlquestion: print w/ replies, xml ) Need Help??
davies has asked for the wisdom of the Perl Monks concerning the following question:

The following code does what I want:

use strict; use warnings; use diagnostics; my @list = (["qwe", 1], ["qwer", 2], ["tyui", 3], ["asdf", 4], ["ghjk" +, 5], ["zxcv", 6] ); my @list2 = map $$_[0], @list; for my $item ("qwe", "qwer", "tyu", "yui", "tyui") { print grep(/^$item$/, @list2) . " " . $item . "\n"; }

I would prefer to avoid creating @list2 every time (or an anonymous array/list via some other use of map), but I'm stuck. My instincts tell me that it should be possible, but trial results in nothing but error and Google gives me nothing I find helpful. Is there a way of using grep directly on an AoA?


John Davies

Update: Thank you both for working solutions that through their slight differences have taught me more than I was expecting.

Comment on Grep with AoA [Solved]
Download Code
Replies are listed 'Best First'.
Re: Grep with AoA
by grizzley (Chaplain) on Aug 27, 2012 at 09:43 UTC
    Use just grep($$_[0]=~/^$item$/, @list)
Re: Grep with AoA
by moritz (Cardinal) on Aug 27, 2012 at 09:43 UTC
    use strict; use warnings; use diagnostics; my @list = (["qwe", 1], ["qwer", 2], ["tyui", 3], ["asdf", 4], ["ghjk" +, 5], ["zxcv", 6] ); for my $item ("qwe", "qwer", "tyu", "yui", "tyui") { print grep($_->[0] ~~ /^$item$/, @list) . " " . $item . "\n"; }

    Though of course if you check for equality, you can also write grep($_->[0] eq $item, @list)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://989950]
Approved by moritz
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2015-10-10 00:16 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (254 votes), past polls