Prev: recursive perl
Next: FAQ 5.22 I still don't get locking. I just want to increment the number in the file. How can I do this?
From: monkeys paw on 10 Mar 2010 12:59 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 10 Mar 2010 13:22 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 10 Mar 2010 13:45
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 |