in reply to To return and/or not?

In situations like this, B::Deparse (a core module) often helps:
$ perl -MO=Deparse foo.pl sub c1 { my($a, $b) = @_; not $b if $a; } sub c2 { my($a, $b) = @_; not $b if return $a; } foo.pl syntax OK

Replies are listed 'Best First'.
Re^2: To return and/or not?
by Anonymous Monk on Oct 08, 2011 at 09:32 UTC
    I see. So basically the operators "and, or, xor" (and no others?) all have lower precedence than the return statement. Seems a strange decision.

      It seems to be the general sentiment that if a certain decision bites you, you consider it strange/weird/harmful/whatever, and forget all those idioms that are enabled by it.

      Yet all language design decisions are tradeoffs, and even generally good decisions bite you sometimes. Go figure.

      return is a normal listop, with normal listop precedence. The looser precedence of and/or/not is exactly the reason for having them. There wouldn't be any reason for them to exist if they had the same precedence as &&/||/!.

      The only thing perl could do better here is to warn about unreachable code in sub c2; but I think that has been tried before for if 0 { ... } code, and has been discarded at not helpful.

      Seems a strange decision.
      Not really. It make the famous
      open my $IN, '<', $filename or die "Cannot open $filename: $!\n";
      possible.
        How would lowering the precedence of 'return' stop that from working?

      So basically the operators...

      Yeah, perldoc perlop indeed says that not/and/or/xor have the lowest precedence

      left        terms and list operators (leftward)
      left        ->
      nonassoc    ++ --
      right       **
      right       ! ~ \ and unary + and -
      left        =~ !~
      left        * / % x
      left        + - .
      left        << >>
      nonassoc    named unary operators
      nonassoc    < > <= >= lt gt le ge
      nonassoc    == != <=> eq ne cmp ~~
      left        &
      left        | ^
      left        &&
      left        || //
      nonassoc    ..  ...
      right       ?:
      right       = += -= *= etc.
      left        , =>
      nonassoc    list operators (rightward)
      right       not
      left        and
      left        or xor

      Seems a strange decision.

      How many other programming languages do you know? That have the keywords not/and/or/xor as operators?

        What other programming languages?

        OK, I think I get it - its not that return is strange, its that not, and, or , xor are lower precedence than everything else (eg other operators, statements like return, and functions like open). I expected return to be even lower precedence.