[Israel.pm] swap arrays

Yosef Meller mellerf at netvision.net.il
Tue Feb 17 01:42:11 PST 2004


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

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
code first:
perl -e '@a=(1,2);@b=(3,4);(*a,*b)=(*b,*a);print @a, at b,"\n"'
Output: 3412

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).

- --
perl -e'$b=unpack"b*",pack"H*","59dfce2d6b1664d3b26cd9969503";
for(;$a<length$b;$a+=9){print+pack"b8",substr$b,$a,8;}'

My public key:
http://wwwkeys.pgp.net:11371/pks/lookup?op=get&search=0x3D2CA0A8
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFAMeHzaElZPz0soKgRApqSAKCSgoeoIsufkusgq1ijNMjUxKxsUQCgj5IY
NRkt1clalBp7ydD9eUrwKZo=
=BduO
-----END PGP SIGNATURE-----



More information about the Perl mailing list