This is a variant on an old assembly and 'C' trick that seems to work under Perl (at least, 5.005_03).

my $x = 123; my $y = 666; $x ^= $y ^= $x ^= $y;

It swaps the two values without using an intermediate variable. Now I know that can be done under Perl other ways, but it might make a cool little hack for a JAPH-type person (which is *very* not-me).

For a collection of cute C tricks that someone could port to Perl, see Steve's 'Cute Code' Collection

--Chris

e-mail jcwren

Replies are listed 'Best First'.
Re: Potentially useful code fragment for you JAPHer's
by spaz (Pilgrim) on Mar 20, 2001 at 08:58 UTC
    And for those of you wondering what the easiest other way is
    ($x, $y) = ($y, $x);
    -- Dave
      But the one jcwren posted can be easily abused:
      $==1,$^^=2,$^^^=$=^=$^^^=$=; $==1,$^^=2,$=^=$^^^=$=^=$^^;
      The traditional method (the swap you show) is only easily obfuscated by something like
      # if you're allowed to over-write $( and $) ($),$() = ($(,$));
      Kudos to the person who explains my XOR obfuscation.

      japhy -- Perl and Regex Hacker
Re: Potentially useful code fragment for you JAPHer's
by Dominus (Parson) on Mar 20, 2001 at 22:40 UTC
    The 'cute' version rather famously doesn't work. It obviously fails for floating-point numbers, references, objects, and soforth. It also fails in Perl when x and y are strings---try it with $x="foo" and $y = "y" for example.

    Even for integers, the value is specifically not defined by the C standard---the variable x is modified twice without an intervening sequence point, which is forbidden, and if you do it, you are not writing C. Different compilers can (and do) produce different results for this kind of expression. It might work in Perl, but the documentation doesn't say so.

    See the comp.lang.c FAQ list for more details about this 'cute trick'.