in reply to Re^7: eval order of args to a sub
in thread eval order of args to a sub
+ - . have "left associativity", so the operands are evaluated in that order; after evaluating the operands for an operation each operation takes place in the order which satisfies said associativity.
perl -MO=Concise,-exec -le '$x = 10; for(qw(moo baz bar foo)) { *{$_} = sub { $x + shift }; $x-=3; } $result = foo() - bar() - baz() - moo();print $result' 1 <0> enter 2 <;> nextstate(main 1 -e:1) v 3 <$> const[IV 10] s 4 <#> gvsv[*x] s 5 <2> sassign vKS/2 6 <;> nextstate(main 4 -e:1) v 7 <0> pushmark sM 8 <$> const[PV "moo"] sM 9 <$> const[PV "baz"] sM a <$> const[PV "bar"] sM b <$> const[PV "foo"] sM c <#> gv[*_] s d <{> enteriter(next->p last->s redo->e) lK q <0> iter s r <|> and(other->e) vK/1 e <;> nextstate(main 3 -e:1) v f <0> pushmark sRM g <$> anoncode[CV ] lRM h <1> refgen sK/1 i <#> gvsv[*_] s j <1> rv2gv sKRM*/1 k <2> sassign vKS/2 l <;> nextstate(main 3 -e:1) v m <#> gvsv[*x] s n <$> const[IV 3] s o <2> subtract[t5] vKS/2 p <0> unstack v goto q s <2> leaveloop vK/2 t <;> nextstate(main 5 -e:1) v u <0> pushmark s v <#> gv[*foo] s/EARLYCV w <1> entersub[t9] sKS/TARG,1 x <0> pushmark s y <#> gv[*bar] s/EARLYCV z <1> entersub[t11] sKS/TARG,1 10 <2> subtract[t12] sK/2 11 <0> pushmark s 12 <#> gv[*baz] s/EARLYCV 13 <1> entersub[t14] sKS/TARG,1 14 <2> subtract[t15] sK/2 15 <0> pushmark s 16 <#> gv[*moo] s/EARLYCV 17 <1> entersub[t17] sKS/TARG,1 18 <2> subtract[t18] sK/2 19 <#> gvsv[*result] s 1a <2> sassign vKS/2 1b <;> nextstate(main 5 -e:1) v 1c <0> pushmark s 1d <#> gvsv[*result] s 1e <@> print vK 1f <@> leave[1 ref] vKP/REFC -e syntax OK
The left associativity leads to the following order:
$result = ( ( foo() - bar() ) - baz() ) - moo();
which is also the order of execution of the subexpressions. Right from perlop:
Operator associativity defines what happens if a sequence of the same operators is used one after another: whether the evaluator will evaluate the left operations first or the right. For example, in "8 - 4 - 2", subtraction is left associative so Perl evaluates the expression left to right. "8 - 4" is evaluated first making the expression "4 - 2 == 2" and not "8 - 2 == 6".
which IMHO pretty well defines the execution order of subexpressions.
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^9: eval order of args to a sub
by mrpeabody (Friar) on Jun 04, 2007 at 10:41 UTC | |
|
Re^9: eval order of args to a sub
by ikegami (Patriarch) on Jun 04, 2007 at 13:38 UTC | |
by shmem (Chancellor) on Jun 05, 2007 at 09:49 UTC |