$ perl -wle '$n = 1 ; print $n / ++$n'
1
$ perl -wle '$n = 1 ; print $n / $n++'
2
In the first case, I expected to get 0.5 because
the preincrement would increment $n so the numerator
became 2, thus giving 1/2 = 0.5.
In the second case, I expected to get 1 because
the postincrement would increment $n *after* the
division was performed, thus giving 1/1 = 1.
I'd be thankful if anyone would explain...
Peter
> The following results confuse me. I expected
> to get 0.5 and 1:
>
> $ perl -wle '$n = 1 ; print $n / ++$n'
> 1
The sequence of evals is:
$n = 1;
print $n / ++$n; # $n == 2
print $n / 2; # $n == 2
print 2 / 2; # 1
> $ perl -wle '$n = 1 ; print $n / $n++'
> 2
The sequence of evals is:
$n = 1;
print $n / $n++; # $n == 1
print $n / 1; # $n == 2
print 2 / 1; # 2
HTH
--
KP
> Subject: When does (pre|post)increment happen?
The increment happens at the time the (pre|post)increment
subexpression is evaluated. It is _not_ pre- or post- the whole
expression that contains it.
For numeric $n you can model ++$n as:
do { $n += 1; $n }
And $n++ as:
do { my $o = $n; $n += 1; $o }
> $ perl -wle '$n = 1 ; print $n / ++$n'
> 1
>
> $ perl -wle '$n = 1 ; print $n / $n++'
> 2
> I'd be thankful if anyone would explain...
The first thing to note is that you should not rely on the evaluation
order staying the same in all future versions of Perl.
That said, you can usually explain the current behaviour as
depth-first left-to-right traversal of the parse-tree but with any
lvalue expressions (such as '$n') that are used in an rvalue context
(such as the the operand of a division) being converted as late as
possible.
It is also important to note that many Perl expressions (such as ++$n)
are implemented as returning lvalues even though a (mis-)feature of
the compiler prevents them being used on the LHS of an asignment
operator.
So in...
$n / ++$n
First the LHS operand of / is evaluated to the lvalue $n.
Next the RHS operand of / is evaluated to the lvalue $n, incrementing
$n to 2 at the same time.
Next the lvalues ($n,$n) are converted to rvalues (2,2).
Then 2/2 is evaluated to 1.
And in...
$n / $n++
First the LHS operand of / is evaluated to the lvalue $n.
Next the RHS operand of / is evaluated to the the rvalue 1,
incrementing $n to 2 at the same time.
Next the lvalue $n is converted to rvalue 2.
Then 2/1 is evaluated to 2.
--
\\ ( )
. _\\__[oo
.__/ \\ /\@
. l___\\
# ll l\\
###LL LL\\
> pjac...@online.no (Peter J. Acklam) writes:
>
> > Subject: When does (pre|post)increment happen?
>
> The increment happens at the time the (pre|post)increment
> subexpression is evaluated. It is _not_ pre- or post- the
> whole expression that contains it. [...]
Thank you very much for the explanation! I got it! :-)
Peter
--
#!/local/bin/perl5 -wp -*- mode: cperl; coding: iso-8859-1; -*-
# matlab comment stripper (strips comments from Matlab m-files)
s/^((?:(?:[])}\w.]'+|[^'%])+|'[^'\n]*(?:''[^'\n]*)*')*).*/$1/x;