in reply to Checking for defined-ness for a list

Use this: if (map { (defined $hash->{$_})? 1 : () } qw(A B C)) map in scalar context returns the number of list elements generated.

Update: This is (probably) an inferior solution. I think it has to build the array in memory. I would use tilly's solution. But maybe map is implemented well and doesn't build the list when called in scalar context. Maybe someone with more knowledge than me could comment on that?

Update 2: Another thought ... when testing for the definedness of lots of keys an explicit loop with exit might be quicker because you don't have to test all elements. It's enough when the first key is not defined. grep and map always go through the whole list.

-- Hofmator

Replies are listed 'Best First'.
Re: Re: Checking for defined-ness for a list
by dragonchild (Archbishop) on Jul 25, 2001 at 21:26 UTC
    Hofmator - How would you implement Update2 in a if-check? I like merlyn's solution, but I'm curious how to do it faster ...

      Well, I thought of something obvious along the lines of:

      my $undefined; while my $key (qw/A B C/) { $undefined = 1, last unless defined $hashref->{$key}; } if ($undefined) { # at least one key undefined } else { # all keys defined }
      I'd say this is faster than the grep/map approach when the list of keys to test is long. It also depends on the probability of a key being undefined. Try and Benchmark some real-life examples and you get a definitive answer concerning the speed.

      -- Hofmator