[Israel.pm] swap arrays
mellerf at netvision.net.il
Tue Feb 17 01:42:11 PST 2004
-----BEGIN PGP SIGNED MESSAGE-----
Mikhael Goikhman wrote:
| On 16 Feb 2004 15:58:28 +0200, Yossi.Itzkovich at ecitele.com wrote:
|> Is there an **elegant** way of swapping arrays in Perl ?
|> I call "elegant", the way we swap scalars: ($a,$b)=($b,$a);
| There is no built-in way to swap elements of two arrays.
Actually, there is. And it works the same way as scalar substitution.
The answer is in a seldom used feature of perl called 'typeglobs'. But
perl -e '@a=(1,2);@b=(3,4);(*a,*b)=(*b,*a);print @a, at b,"\n"'
Now, the explanation for those unfamiliar with typeglobs:
A typeglob is actually a hash that holds the references to all variables
of the same name. So, *a holds a reference to $a, @a, %a, sub a (code
reference) etc. The interesting thing is that this is what perl uses in
order to find where is, say, @a. So what I did in this code is swap the
two typeglobs so now @a points to the place where @b is, and vice versa.
Caviat: if you have two different variables of the same name (like
$count, @count), which is bad programming style anyway, you'll end up
swapping it too.
See also: perldoc perldata (under 'Filehandles and Typeglobs).
My public key:
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
-----END PGP SIGNATURE-----
More information about the Perl