remiah has asked for the wisdom of the Perl Monks concerning the following question:
Hello monks.
I tried to filter array of hash. I tried three way: with only map, with grep&map, with for loop.
grep&map, for loop works fine but I see strange 'undef' in only map version.
output of this.use strict; use warnings; use Data::Dumper; my $data1=[ {key=>'a1',value=>'vala1'}, {key=>'a2',value=>'vala2'}, {key=>'a3',value=>'vala3'}, {key=>'b1',value=>'valb1'}, {key=>'b2',value=>'valb2'}, {key=>'c2',value=>'valc2'}, ]; my %ret; #one map %ret = map{ $_->{key} => $_->{value} if($_->{key} =~/^a\d+/) } @$data1 +; print "map ver\n"; print Dumper \%ret; #grep and map %ret = map{ $_->{key} => $_->{value} } grep{ $_->{key} =~ /^a\d+/ } @$ +data1; print "grep,map ver\n"; print Dumper \%ret; #foreach %ret=(); foreach my $r (@$data1){ $ret{$r->{key}} = $r->{value} if ( $r->{key} =~ /^a\d+/ ); } print "foreach ver\n"; print Dumper \%ret;
"only map" version causes "Odd number of elements" warning. And I want to ask some advice to understand this warning. What is wrong for only map version?Odd number of elements in hash assignment at test.pl line 15. map ver $VAR1 = { '' => undef, <====THIS ONE 'a2' => 'vala2', 'a1' => 'vala1', 'a3' => 'vala3' }; grep,map ver $VAR1 = { 'a2' => 'vala2', 'a1' => 'vala1', 'a3' => 'vala3' }; foreach ver $VAR1 = { 'a2' => 'vala2', 'a1' => 'vala1', 'a3' => 'vala3' };
I thought I once saw similar case at PerlMonk, but I couldn't find one with Super Search.
I am so sorry if this is FAQ.
regards.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: map with empty item
by Eliya (Vicar) on Mar 15, 2012 at 05:08 UTC | |
by AnomalousMonk (Archbishop) on Mar 15, 2012 at 07:27 UTC | |
by remiah (Hermit) on Mar 15, 2012 at 05:49 UTC | |
|
Re: map with empty item
by jwkrahn (Abbot) on Mar 15, 2012 at 05:12 UTC | |
by remiah (Hermit) on Mar 15, 2012 at 05:55 UTC |