Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

grep an array of hashrefs

264 views
Skip to first unread message

monkeys paw

unread,
Mar 10, 2010, 12:59:51 PM3/10/10
to
Here is the code i have to find if a hash element
is present in an array of hashrefs:

my @return_set = (
{
'topic' => '40604',
'id_type' => 'bill',
'topic_list' => '',
'id' => 'CA2009000A34'
},
{
'topic' => '40604',
'id_type' => 'bill',
'topic_list' => '',
'id' => 'CA2009000A126'
},
{
'topic' => '40604',
'id_type' => 'bill',
'topic_list' => '',
'id' => 'CA2009000A293'
},

);

my @tmp_array;
for (@return_set) {
push @tmp_array, $_->{id};
}

my $key = 'CA2009000A293';
if (grep /$key/, @tmp_array) {
print 'yestru';
}

How can i use grep on the original array (@return_set), instead of
building a flat array.

John Bokma

unread,
Mar 10, 2010, 1:22:52 PM3/10/10
to
monkeys paw <mon...@joemoney.net> writes:

perldoc -f grep

grep { $_->{ id } eq $key } @return_set;

but if you just want to test if the key is present, you might want to

use List::MoreUtils 'any';

if ( any { $_->{ id } eq $key } @return_set ) {

print 'yestru';
}

--
John Bokma j3b

Hacking & Hiking in Mexico - http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development

J�rgen Exner

unread,
Mar 10, 2010, 1:45:49 PM3/10/10
to
monkeys paw <mon...@joemoney.net> wrote:
>Here is the code i have to find if a hash element
>is present in an array of hashrefs:

>How can i use grep on the original array (@return_set), instead of
>building a flat array.

The first argument to grep() is not a restricted to an RE but can be any
expression. So just dig down in that expression (untested):

grep ( $_->{id} eq 'CA2009000A293', @return_set);

jue

0 new messages