in reply to nonempty false list

A hash slice in a scalar context returns the last element. @x{1, 2} equals (2, undef) and so undef is used as the boolean.

The second one constructs a new array, and therefore the array count is returned in a scalar context, 2.

%x = (1 => 2); print '@x{1, 2} in scalar equals: \'' . (scalar @x{1, 2}) . "'\n"; # Returns '' print '@{[@x{1, 2}]} in scalar equals: \'' . (scalar @{[@x{1, 2}]})) . + "'\n"; # Returns 2

Replies are listed 'Best First'.
Re^2: nonempty false list
by Anonymous Monk on Mar 10, 2011 at 18:47 UTC
    Hmm thanks to everyone, I definitely see the distinction. What I am TRYING to do is this: I have a hash, and I want to test whether any of three separate keys produce a 'true' value. So, it looks something like this (I boiled it down for the first example)
    if(@opts{qw|a b c|}) { }
    Which seemed pretty elegant, but as previously discussed does not work, because its a hash slice. THIS, however, seems horribly inelegant:
    if(@{[@opts{qw|a b c|}]}) { }
    But perl must have something better than this:
    if($opts{a} || $opts{b} || $opts{c}) { }
      Testing each value of a list sounds like a job for grep. When I need to determine if any elements of a list are true, I will usually use something that looks like:

      if( grep $_, @opts{qw|a b c|}) { }

      A cleaner version of this would be

      if( grep $opts{$_}, qw|a b c|) { }

      You can use a couple negations to check if all values are true:

      if( !grep !$opts{$_}, qw|a b c|) { }

      Note that your second suggestion will always return true, since you will always have a 3-element array in scalar context.

      Just use grep
      if (grep {$opt{$_}} qw(a b c)}) {
      And you can even capture the keys for which true is returned
      if (my @keys = grep {$opt{$_}} qw(a b c)}) { print "@keys match\n";