From: monkeys paw on
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.
From: John Bokma on
monkeys paw <monkey(a)joemoney.net> writes:

> 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.

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
From: J�rgen Exner on
monkeys paw <monkey(a)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