http://qs321.pair.com?node_id=11144138


in reply to Re: Purpose of =~ and = in this statement
in thread Purpose of =~ and = in this statement

In fact, this is what Perl optimizes the above statement to:

You have it backwards. «and» isn't optimized into an «if». There isn't even an «if» opcode. An «if» statement is compiled into code that includes an «and» or an «or» opcode.

$ perl -MO=Concise,-exec -e'f() and g()' 1 <0> enter v 2 <;> nextstate(main 1 -e:1) v:{ 3 <0> pushmark s 4 <#> gv[*f] s/EARLYCV 5 <1> entersub[t2] sKS/TARG 6 <|> and(other->7) vK/1 7 <0> pushmark s 8 <#> gv[*g] s/EARLYCV 9 <1> entersub[t4] vKS/TARG a <@> leave[1 ref] vKP/REFC -e syntax OK $ perl -MO=Concise,-exec -e'g() if f()' 1 <0> enter v 2 <;> nextstate(main 1 -e:1) v:{ 3 <0> pushmark s 4 <#> gv[*f] s/EARLYCV 5 <1> entersub[t4] sKS/TARG 6 <|> and(other->7) vK/1 7 <0> pushmark s 8 <#> gv[*g] s/EARLYCV 9 <1> entersub[t2] vKS/TARG a <@> leave[1 ref] vKP/REFC -e syntax OK $ perl -MO=Concise,-exec -e'if (f()) { g() }' 1 <0> enter v 2 <;> nextstate(main 1 -e:1) v:{ 3 <0> pushmark s 4 <#> gv[*f] s/EARLYCV 5 <1> entersub[t2] sKS/TARG 6 <|> and(other->7) vK/1 7 <0> pushmark s 8 <#> gv[*g] s/EARLYCV 9 <1> entersub[t4] vKS/TARG a <@> leave[1 ref] vKP/REFC -e syntax OK

«f() and g()» and «g() if f()» generate exactly the same opcode tree, so Deparse outputs what it thinks is clearest.[1]

If the whole conditional expression is negated, the «not» and the «and» opcodes will be optimized into an «or».

$ perl -MO=Concise,-exec -e'if (!f()) { g() }' 1 <0> enter v 2 <;> nextstate(main 1 -e:1) v:{ 3 <0> pushmark s 4 <#> gv[*f] s/EARLYCV 5 <1> entersub[t2] sKS/TARG 6 <|> or(other->7) vK/1 7 <0> pushmark s 8 <#> gv[*g] s/EARLYCV 9 <1> entersub[t4] vKS/TARG a <@> leave[1 ref] vKP/REFC -e syntax OK

  1. «-exec» shows the code that's executed. And while the code executed for «if (f()) { g() }» is identical to the code executed for the other two, the opcode tree is different. There are vestiges in the opcode tree of which Deparse can take advantage to differentiate the «if (f()) { g() }» case from the others. Remove «,-exec» to see the tree.