Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^2: Purpose of =~ and = in this statement

by ikegami (Patriarch)
on May 23, 2022 at 19:14 UTC ( [id://11144138]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11144138]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-26 08:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found