[an error occurred while processing this directive]
[an error occurred while processing this directive]

Precedence in PERL

Perl operators have the following associativity and precedence:

   nonassoc   print printf exec system sort reverse
              chmod chown kill unlink utime die return
   left       ,
   right      = += -= *= etc.
   right      ?:
   nonassoc   ..
   left       ||
   left       &&
   left       | ^
   left       &
   nonassoc   == != <=> eq ne cmp
   nonassoc   &lt; &gt; &lt;= &gt;= lt gt le ge
   nonassoc   chdir exit eval reset sleep rand umask
   nonassoc   -r -w -x etc.
   left       << >>
   left       + - .
   left       * / % x
   left       =~ !~ 
   right      ! ~ and unary minus
   right      **
   nonassoc   ++ --
   left
As mentioned earlier, if any list operator (print, etc.) or any unary operator (chdir, etc.) is followed by a left parenthesis as the next token on the same line, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. Examples:
   chdir $foo || die;    # (chdir $foo) || die
   chdir($foo) || die;   # (chdir $foo) || die
   chdir ($foo) || die;  # (chdir $foo) || die
   chdir +($foo) || die; # (chdir $foo) || die
but, because * is higher precedence than ||:
   chdir $foo * 20;      # chdir ($foo * 20)
   chdir($foo) * 20;     # (chdir $foo) * 20
   chdir ($foo) * 20;    # (chdir $foo) * 20
   chdir +($foo) * 20;   # chdir ($foo * 20)

   rand 10 * 20;         # rand (10 * 20)
   rand(10) * 20;        # (rand 10) * 20
   rand (10) * 20;       # (rand 10) * 20
   rand +(10) * 20;      # rand (10 * 20)
In the absence of parentheses, the precedence of list operators such as print, sort or chmod is either very high or very low depending on whether you look at the left side of operator or the right side of it. For example, in
   @ary = (1, 3, sort 4, 2);
   print @ary;   # prints 1324
the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all the arguments that follow them, and then act like a simple term with regard to the preceding expression. Note that you have to be careful with parens:
   # These evaluate exit before doing the print:
   print($foo, exit);   # Obviously not what you want.
   print $foo, exit;    # Nor is this.

   # These do the print before evaluating exit:
   (print $foo), exit;  # This is what you want.
   print($foo), exit;   # Or this.
   print ($foo), exit;  # Or even this.
Also note that
   print ($foo & 255) + 1, "\n";
probably doesn't do what you expect at first glance.

Click here to go back to the Perl index

[an error occurred while processing this directive]