[tpm] Is there a three-way version of...

John Macdonald john at perlwolf.com
Fri May 29 13:43:56 PDT 2009

On Fri, May 29, 2009 at 04:20:48PM -0400, Mike Stok wrote:
> As of perl 5.10 (I think) it is the "defined or" operator which only  
> returns the right hand side if the left hand side is undef, from perlop:
>        C−style Logical Defined‐Or
>        Although it has no direct equivalent in C, Perl’s "//" operator is
>        related to its C−style or.  In fact, it’s exactly the same as 
> "||",
>        except that it tests the left hand side’s definedness instead of 
> its
>        truth.  Thus, "$a // $b" is similar to "defined($a) || $b" (except 
> that
>        it returns the value of $a rather than the value of  
> "defined($a)") and
>        is exactly equivalent to "defined($a) ? $a : $b".  This is very 
> useful
>        for providing default values for variables.  If you actually want 
> to
>        test if at least one of $a and $b is defined, use "defined($a // 
> $b)".
>        The "||", "//" and "&&" operators return the last value evaluated
>        (unlike C’s "||" and "&&", which return 0 or 1).

This is especially useful for setting a value that can come from
multiple optional locations, and using the first one that was
actually provided:

    $foo = $opt{foo} || $ENV{PROG_FOO} || $rc_opts{foo} || 'default';

and, as Mike said, this will still take the first one found even
if the explicitly provided value is 0 or ''.  e.g.:

    prog --foo=0

The || operator would skip this setting (because it's false) and
go on to getting the setting of foo from the alternate sources.

More information about the toronto-pm mailing list