First ... Back ... Next ... Last ... (Notes home)

Operators and Precedence in Perl

  • man perlop for review
  • Operators include the regular suspects such as + and *, as well as nearly every other operator found in modern languages like C and Java:
    Perl operators listed from highest to 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
    
  • If in doubt about operator precedence, use parentheses. Whitespace can also help you to see how your intended grouping is working, as can splitting an operation across multiple statements.
  • How will this be evaluated?
    my $x = 10 + 4 * 2**16 / 4;
  • What about this?
    $y == $z or die "They're not equal!";
  • Is this different?
    $y == $z || die "They're not equal!";
  • Is this?
    $y = $z || die "They're not equal!";
  • And this?
    if (not $a and $b or $c) { print "!a |c\n"; }

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby