in reply to interchanging variables the tough way

The canonical answer (that perl is able to sometimes avoid) is to use a temporary variable, like so:

my $temp; $temp=$a; $a=$b; $b=$c; $c=$temp;

In the above code, we save the value of $a to a temporary variable. Then we assign $a to $b - without worrying about clobbering the value of $a, because we have just saved it. And now that the value in $b has been copied to $a, we can safely assign into $b, etc. etc...

Update: Thanks to those below. Yes, it should assign $c back to $temp, not $a.

Replies are listed 'Best First'.
RE (tilly) 2: interchanging variables the tough way
by tilly (Archbishop) on Aug 30, 2000 at 18:40 UTC
    Um, you are supposed to actually assign $temp to $c at the end...

    I am a big fan of Perl constructs that result in my making fewer mistakes. Particularly silly thinkos like the above (which I am likewise prone to). :-)

RE: Re: interchanging variables the tough way
by ColtsFoot (Chaplain) on Aug 30, 2000 at 18:40 UTC
    Should the code snippet not read
    my $temp; $temp=$a; $a=$b; $b=$c; $c=$temp;
    Or am I missing something (-;
RE: Re: interchanging variables the tough way
by ANKUR (Novice) on Aug 30, 2000 at 18:53 UTC
    Sorry
    I completely forgot to type without using a fourth variable
    .Can we do it without using a fourth variable?