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

Mike Stok mike at stok.ca
Fri May 29 13:20:48 PDT 2009


On May 29, 2009, at 4:17 PM, Madison Kelly wrote:

> Mike Stok wrote:
>> On May 29, 2009, at 4:01 PM, G. Matthew Rice wrote:
>>> Madison Kelly <linux at alteeve.com> writes:
>>>>> a table-like way is adviced.
>>>>> my $title = $condition1 ? 'result1'
>>>>>             : $condition2 ? 'result2'
>>>>>             : $condition 3 ? 'result3'
>>>>>            # ... more lines here
>>>
>>> Yuch.  Looks like C :)
>>>
>>> Mine looks similar to another one I saw:
>>>
>>>   my $title = {aa => 'bing', bb => 'bang'}->{$key} || 'bong';
>> Or even use // there if your perl is recent enough, in case you  
>> ever might have cases involving false but defined strings.
>>  my $title = { aa => 'bing', bb => 'bang', cc => '0', dd => '' }- 
>> >{$key} // 'bong';
>> Mike
>
> I'm not familiar with the '//' operator. It is ... ?
>
> Madi

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).

Mike

-- 

Mike Stok <mike at stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.






More information about the toronto-pm mailing list