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.

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;
output of this.
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' };
"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?

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.


In reply to map with empty item by remiah

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.