#!/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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |