landau351 has asked for the wisdom of the Perl Monks concerning the following question:

The snippet below always fails when i test using the ?: operators but not when a full if() test is performed.
Why ??

-cheers landau351
# # /usr/local/lib/perl5/5.6.1/sun4-solaris # $msgFile = "./data/err-PHY-opt.dat"; ($msgFile =~ /\-opt.dat$/) ? $optsFile = 1 : $optsFile = 0; print "optsFile = " . $optsFile . "\n"; if ($msgFile =~ /\-opt.dat$/) { $optsFile = 1; } else { $optsFile = 0; } print "optsFile = " . $optsFile . "\n";

janitored by ybiC: Balanced <code> tags around codeblock, as per Monastery convention

Replies are listed 'Best First'.
Re: ?: conditional operators appear to fail
by Zaxo (Archbishop) on Aug 24, 2004 at 04:18 UTC

    We've seen a similar question earlier today. Write it like this: $optsFile = ($msgFile =~ /\-opt.dat$/) ? 1 : 0; Trinary op returns a value, as if () {} else {} does not. It is the embedded assignments that goof things up for you.

    After Compline,
    Zaxo

      thanx, i only just found the comments about the perlop precidence issue, i shall re-write. my code

      thanks again
Re: ?: conditional operators appear to fail
by tachyon (Chancellor) on Aug 24, 2004 at 05:38 UTC

    In addition to Zaxos correct idiom it is useful to note you can use do{} in a ternary op which lets you say do:

    $condition ? do{ $a = $b } : do { $c = $d }; $condition ? do_stuff() : do{ $stuff = NOT_DONE };

    ie mix assignments to different vars, assignment and function call etc. This is mostly useful if you are using it as a shortform idiom for if/elseif..... If you are just assigning different values to a variable based on some condition Zaxos $var = $cond ? $val1 : $val2; is the way to go.

    cheers

    tachyon

Re: ?: conditional operators appear to fail
by bart (Canon) on Aug 24, 2004 at 09:25 UTC
    I don't see why you're not using
    $optsFile = ($msgFile =~ /\-opt.dat$/) ? 1 : 0;
    which is how ?: was intended to be used.
Re: ?: conditional operators appear to fail
by Fletch (Bishop) on Aug 24, 2004 at 15:34 UTC

    Also note that when you get strange behavior like this B::Deparse can help clear up how perl is parsing your code.

    $ perl -MO=Deparse,-p -e '($msgFile =~ /\-opt.dat$/) ? $optsFile = 1 : + $optsFile = 0;' ((($msgFile =~ /\-opt.dat$/) ? ($optsFile = 1) : $optsFile) = 0);
Re: ?: conditional operators appear to fail
by shenme (Priest) on Aug 24, 2004 at 20:59 UTC
    Parenthesizing the truth value used with ?: is a good idea - usually. Got myself into a pickle the other day, though.
    warn ($msg =~ m/\n$/) ? $msg : ($msg . "\n");
    didn't work quite as expected. After a bit'o head scratching about no results and complaints about "void context", I remembered the nastiness pointed out about 'print' and others, and realized the left paren was confusing the parser into thinking "warn()".

    In _this_ case, removing the parens worked better...

    warn $msg =~ m/\n$/ ? $msg : ($msg . "\n");