In trying to cut my code to a minimum, I have come up against a stumbling point in replacing a perfunc:foreach loop with a perlfunc:map statement - This stumbling point revolves around the following code:

#!/usr/bin/perl -Tw use CGI; use XML::Simple; use strict; my $xs = XML::Simple->new; my $xml = eval { $xs->XMLin('../xml/users.xml') }; die $@ if ($@); my $cgi = CGI->new; my @foreach; foreach (@{%{$xml}->{'user'}}) { push (@foreach, $_) if $_->{'username'} eq $cgi->param('username') +; }; my @map = map { $_ if $_->{'username'} eq $cgi->param('username'); } @ +{%{$xml}->{'user'}};

To my mind, the foreach and map segments of code are equivalent - Herein lies the problem I suspect. They are not.

If indeed, these pieces of code are equivalent, one could rightly expect the output arrays of each code segment to be the same for a given input. This is not occurring - Instead, the array output from the map code segment comprises of a large number of null values (one for each non-matching field) and the single result expected (and returned from the foreach code segment).

And so my question is ... What am I doing wrong here? Is there a way to have map return no value (compared with null value) into the output array if a given condition on the input scalar is not met?

 

Ooohhh, Rob no beer function well without!


In reply to foreach/map equivalency by rob_au

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.