in reply to Mixing OR with conditional operator

It's a precedence problem.

B::Deparse with the -p option can show you how Perl understands expressions. Unfortunately, the expression contains only constants, so it's evaluated at compile time, so the result isn't helpful:

$ perl -MO=Deparse,-p 1.pl use strict; my($test); ($test = (undef)); print("test = $test\n"); 1.pl syntax OK

You need to introduce variables to postpone the evaluation to runtime to get a more enlightening answer:

#! /usr/bin/perl use warnings; use strict; my $test; my $undef; my $true = 1; my $zero = 0; $test = $true || ($undef && $undef != $zero) ? $undef : $zero; print "test = $test\n";

And, voilą:

use strict; my($test); my($undef); (my $true = 1); (my $zero = 0); ($test = (($true || ($undef && ($undef != $zero))) ? $undef : $zero)); print("test = $test\n"); 1.pl syntax OK

Nicely indented:

$test = ( ( $true || ( $undef && ( $undef != $zero ) ) ) ? $undef : $zero )

$true || ... returns 1, so the "then" part of the ternary is returned, i.e. $undef.

Maybe you wanted

$test = $true || ($undef && $undef != $zero ? $undef : $zero);

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Mixing OR with conditional operator
by jockel (Beadle) on Nov 19, 2017 at 10:44 UTC

    Choroba,

    I have variables in my real code, I just thought I would simplify it as much as possible.

    Actually I first wrote an example just like your last example. But I didn't think my 'simplification' would actually change the whole behavior!

    OT: The current "Voting Booth"-question "In order to be able to say "I know Perl", you must have:", with the leading answer "One can never truly know perl", are totally correct ;-)

    Edit: And yes, your last one liner code-example, fixes the issue and I will adopt that syntax!

    Thank you!

    -----BEGIN PERL GEEK CODE BLOCK----- Version: 0.01 P++>*$c--->---P6 > R >++++$M+>+++$O+++>+++$MA->+++$E > PU->++BD->-C+>+$D+>+$S->+++X >+WP >+++MO!PP n?CO--PO!>!(!)o?G!A--OLC--OLCC--OLJ--Ee !Ev-Eon-uL++>*uB!uS!uH-uo!w->!m+ ------END PERL GEEK CODE BLOCK------
      > One can never truly know perl

      This problem is not Perl specific, you need to respect precedence in all languages.*

      Just try to do the same expression in JS or C ...

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

      update

      *) correction, most not all. You might enjoy Lisp or Assembler.