DCPM: Little syntax query

Steve Marvell steve at devon-it.co.uk
Wed Dec 3 15:14:05 CST 2003


Neil Williams wrote:

> I'm confused over ? : conditionals

a ? b : c

if a then b else c

> if($asyncz == 0) {$port = $list[5];}
> else{ $port = $list[3];}
> 
> Why doesn't this work instead?
> $asyncz ? $port = $list[5] : $port = $list[3];

For one, the condition is the wrong way round, 0 being false. The
other is that it's not idiomatic. And see perlop for why you don't put
assignments inside them. You're also suffering from assigned-to
conditional operator of the type:

($a_or_b ? $a : $b) = $c;

Either of these are fine:

$port = $asyncz ? $list[3] : $list[5]
$port = $asyncz == 0 ? $list[5] : $list[3]

$port = $list[$asyncz ? 3 : 5]
$port = $list[$asyncz == 0? 5 : 3]

> Also, is ? : limited to if then else - if there is no else, do I have to use 
> if() {} anyway?
> 
> $ perl -e '$asyncz = 0 ; $asyncz ? $port = 5 : $port = 3; print $port;'
> $ perl -e '$asyncz = 1; $asyncz ? $port = 5 : $port = 3; print $port;''

Try:

perl -le '$asyncz = 0; $port = $asyncz ? 3 : 5; print $port;'
perl -le '$asyncz = 1; $port = $asyncz ? 3 : 5; print $port;'

> My otherwise excellent documentation doesn't give an example.

perlop does.

Steve



More information about the Devoncornwall-pm mailing list