Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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?

Regards,

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
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (16)
As of 2014-07-25 20:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (175 votes), past polls