in reply to Explanation of mapping and undef

It's creating an anonymous array, just like
%hash = map {$_ => undef } qw(city state country);
which produces a list like
( 'city' => undef, 'state' => undef, 'country' => undef )
which is then turned into a hash. In fact, any other value than undef would do just as well, as it isn't actually used.

But, it does so for every loop, just to test if $field is one of qw(city state country). That's a very inefficient way of doing it.

A better way would be to create the hash outside of the loop:

my %skip = map {$_ => undef } qw(city state country); foreach my $field (param) { next if exists $skip{$field}; foreach my $value (param($field)) { #process non blank thedata variable ... } }

Or, IMO perfectly acceptable for small skip lists and/or few parameters:

foreach my $field (param) { next if grep { $field eq $_ } qw(city state country); foreach my $value (param($field)) { #process non blank thedata variable ... } }

Note that I moved the test outside of the inner loop, as the result won't change for whatever values you get.

Replies are listed 'Best First'.
Re^2: Explanation of mapping and undef
by dragonchild (Archbishop) on Jun 08, 2004 at 11:56 UTC
    While it's true that any value would be ok, undef is generally preferred because there is one undef scalar that all undef values point to. This results in a small savings in memory, as well as being more descriptive.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested