in reply to Re^8: Pre vs Post Incrementing variables
in thread Pre vs Post Incrementing variables
By the same logic in f($n) f should be passed the result (value) of $n, disallowing f from modifying $n.
Not so.
If I pass variables to a function, then I expect to get reference to those variables:
$n = 1; $m = 2; print \$n, \$m;; SCALAR(0x3d3cf08) SCALAR(0x3e12508) sub { print \$_[0], \$_[1] }->( $n, $m );; SCALAR(0x3d3cf08) SCALAR(0x3e12508)
But, if I pass sub-expressions to a function, I expect to get references to (temporary) variables containing the results of those sub-expressions. And in most cases that's exactly what I get:
sub { print \$_[0], \$_[1] }->( $n+1, $m+1 );; SCALAR(0x3cc86d0) SCALAR(0x3d3f320)
I can even mutate those references to results without error:
[0] Perl> sub { print \$_[0], \$_[1]; +$_++ for @_ }->( $n+1, $m+1 );; SCALAR(0x3cc86d0) SCALAR(0x3d3f320) 2 3
but, and here is the significant point, those mutations do not modify the variable involved in the sub-expressions from which those results were derived:
print $n, $m;; 1 2
It is only in the case of pre-increment expressions (and a few other similar anomalies), that the function receives a reference to the target of the sub-expression, rather than a reference to the result of it.
And the clincher that this is a bug, rather than an implementation specific optimisation allowable within the rules of the language definition, is that there is no good use for it.
The justification for many of the anomalies that exist in Perl, is that there are one or more very common cases where the anomalous behaviour is useful, Because it allows the capture, within a concise idiom, a piece of behaviour that is sufficiently commonplace to warrent it. This has no such justification.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^10: Pre vs Post Incrementing variables
by shmem (Chancellor) on Sep 13, 2010 at 14:30 UTC | |
|
Re^10: Pre vs Post Incrementing variables
by JavaFan (Canon) on Sep 13, 2010 at 09:41 UTC | |
by BrowserUk (Patriarch) on Sep 13, 2010 at 14:16 UTC |