1

When I run this program:

print(rand*100)

I get values from [0,1) range.

But for this:

print(100*rand)

I get values from [0,100) range.

What is precedence here? and why first expression does not return values from [0,100) range?

Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158

2 Answers2

6

rand has two syntax:

  • rand
  • rand EXPR

If what follows rand can be the start of an expression (EXPR), Perl assumes you are using the latter form.

* can start an EXPR, so rand*... is parsed as rand EXPR. This means that rand*100 is equivalent to rand(*100).

$ perl -MO=Deparse,-p -wle'print(rand*100)'
BEGIN { $^W = 1; }
BEGIN { $/ = "\n"; $\ = "\n"; }
print(rand(*100));
-e syntax OK

$ perl -wle'print(rand*100)'
Argument "*main::100" isn't numeric in rand at -e line 1.
0.57355563536203
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Two things that make this ambiguity even more fun: Spaces between sigils and variable names are allowed, so `rand * 100` still does not avoid this issue; and it happens with `rand / 100` too just resulting in a parse error once the parser realizes there's no closing `/`. – Grinnz Nov 25 '18 at 17:31
2

You can always use B::Deparse to see how Perl is parsing an expression.

$ perl -MO=Deparse -e'print(100*rand)'
print 100 * (rand);
-e syntax OK
$ perl -MO=Deparse -e'print(rand*100)'
print rand *100;
-e syntax OK
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
  • What an honour ... I've actually got your "Data Munging with Perl" on my bookshelf directly above me. Metaphoric in more ways than one ;-) – M__ Nov 25 '18 at 15:36