develooper Front page | perl.beginners | Postings from April 2012

Re: Using the ternary operator to concat a string not working like Ithink?

Thread Previous | Thread Next
From:
Uri Guttman
Date:
April 4, 2012 00:04
Subject:
Re: Using the ternary operator to concat a string not working like Ithink?
Message ID:
4F7BF28A.8000308@stemsystems.com
On 04/03/2012 06:55 PM, timothy adigun wrote:
> Hi Stan,
> Please check my comments below:
> On Tue, Apr 3, 2012 at 10:39 PM, Stan N/A<stan100@gmail.com>  wrote:
>
>> I've run into a weird issue where the ternary operator isn't doing
>> what I believe it normally would and need some help understanding the
>> issue. I'm sure I'm missing some critical point, but perhaps this is
>> an issue with perl. Here's a short 14 line script exemplifying the
>>
> issue:
>>
>> -----code-----
>> #!/usr/bin/perl
>> use strict;
>> use warnings;
>>
>> my %test = (
>>     one =>  "first",
>>     two =>  "second"
>> );
>>
>> $test{one} eq "first" ?
>>     $test{one} .= " is the worst\n" :
>>     $test{two} .= " is the best\n";
>>
>
>      $test{one} eq "first" ?
>      $test{one} .= " is the worst\n" :
>      ( $test{two} .= " is the best\n");
>

that is the wrong way to fix this even if it works.

the ternary operator is meant to return a single value from a choice of 
two expressions. it is not meant for side effects like assignment or sub 
calls that do things. use if/else for that. the correct answer here is 
to use if/else as the assignments go to different places.

if( $test{one} eq 'first' ) {
	$test{one} .= " is the worst\n" ;
else {
	$test{two} .= " is the best\n";
}

that code is not a good use of ?: at all so use if/else.

uri

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About