On 2012-04-03 17:39, Stan N/A 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:

$test{one} eq "first" ?
     $test{one} .= " is the worst\n" :
     $test{two} .= " is the best\n";

print $_ for values %test;
----code----

I believe the output should result with:

first is the worst
second

I think your understanding of the ternary operator is backwards. It is not meant to be used like this:

if condition
    ? do this
    : else do this

instead, it works like this:

my value, ( if this condition is true  )
    ? is set to this
    : else it is set to this

Here is an actual code example:

my $x = 1;
my $y = ( $x == 1 )
    : 5
    : 10;

# $y would be set to 5

Your code isn't really that good of a candidate for the ternary operator. It would be much better suited to a full blown if/else block. This is because you should not be making modifications to the variables (aka causing side-effects) within the ternary operator.

To use the ternary operator to get your previously expected output, it would have to be rewritten like the following. Note however that you lose the ability to do anything with $test{two}:

#!/usr/bin/perl
use strict;
use warnings;

my %test = (
    one => "first",
    two => "second"
);

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

print "$_" for values %test;

Steve

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to