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:
Peter Scott
Date:
April 7, 2012 03:54
Subject:
Re: Using the ternary operator to concat a string not working like Ithink?
Message ID:
20120407105402.6863.qmail@lists-nntp.develooper.com
On Wed, 04 Apr 2012 03:04:42 -0400, Uri Guttman wrote:
> On 04/03/2012 06:55 PM, timothy adigun wrote:
> 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.

Right.  And if you want the single statement succinctness, use and/or:

% perl -le '%test = qw(one first two second); $test{one} eq "first" and 
$test{one} .= " is the worst" or $test{two} .= " is the best"; print for 
values %test'
first is the worst
second

% perl -le '%test = qw(one third two second); $test{one} eq "first" and 
$test{one} .= " is the worst" or $test{two} .= " is the best"; print for 
values %test'
third
second is the best


-- 
Peter Scott
http://www.perlmedic.com/     http://www.perldebugged.com/
http://www.informit.com/store/product.aspx?isbn=0137001274
http://www.oreillyschool.com/certificates/perl-programming.php

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