Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Grep with AoA [Solved]

by davies (Parson)
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.

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2018-06-24 01:25 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.