srinikar has asked for the wisdom of the Perl Monks concerning the following question:

Please help me understand how the swapping works in the below statement: ($a, $b) = ($b, $a);

Replies are listed 'Best First'.
Re: How swap works
by dave_the_m (Monsignor) on Jul 11, 2012 at 14:06 UTC
    In the case where the same variable appears on both sides of the assignment, perl makes a temporary copy of all the values of the RHS before performing the assignment.

    Dave.

Re: How swap works
by cheekuperl (Monk) on Jul 11, 2012 at 13:40 UTC
    A longer answer is this:
    1. A list pf values is first created by using variables given on RHS.
    2. LHS is a list of aliases to variables.
    3. Perl semantics cause the value on RHS list to be assigned to respective alias on LHS list.

      Actually, the list of values from the RHS is also a list of aliases (to values or to scalar variables, depending on what semantics you want to use at this point).

      [The list for the LHS is a list of aliases to variables (not values) but that only makes a difference for aggregate variables (arrays and hashes) -- for assigning from a list of scalar variables to a list of scalar variables, the two lists that get constructed contain identical types of aliases.]

      At the time that the code is compiled, Perl tries to determine if it is impossible for the same alias to end up in both lists. If Perl can't determine that that is impossible, then the AAssign op is flagged as "COMMON" (at compile time).

      When an AAssign op is executed, if it is flagged as "COMMON", then, before it does the assignments, it first replaces each item in the RHS list (of aliases) with a (non-alias) copy of itself.

      $ diff <( perl -MO=Concise -e'($a,$b)=($b,$a)' \ | perl -pe's/0x[\da-f]+/0x/g' ) +\ <( perl -MO=Concise -e'($x,$y)=($b,$a)' \ | perl -pe's/0x[\da-f]+/0x/g' ) -e syntax OK -e syntax OK 4c4 < 9 <2> aassign[t5] vKS/COMMON ->a --- > 9 <2> aassign[t5] vKS ->a 14c14 < 7 <#> gvsv[*a] s ->8 --- > 7 <#> gvsv[*x] s ->8 16c16 < 8 <#> gvsv[*b] s ->9 --- > 8 <#> gvsv[*y] s ->9

      - tye        

        That is a great explanation! Zoomed in :)
Re: How swap works
by cheekuperl (Monk) on Jul 11, 2012 at 13:34 UTC
    Most probably the same way in which $a=$a+1; works: