[Israel.pm] swap arrays

Yosef Meller mellerf at netvision.net.il
Tue Feb 17 05:38:27 PST 2004


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

Mikhael Goikhman wrote:
|> | 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
|
| This is true, but there are 2 major problems making this unusable.
|
| First, such swap only works on package variables (i.e. globals,
| optionally localized). Since most of variables in a normal program
| are "my" variables and not global, this trick does not swap them.

True, I stand corrected. Still nice though :-)

|> 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.
|
|
| I disagree here regarding bad programming style, for example the
| following lines is perfectly good Perl programming style:
|
| my $names = \@names; my %names = map { $_ => 1 } @names;
|

Yes, I use these constructs too, but only when I need to use the same
data in different ways. (like both a list and a hash). Perhaps I
shouldn't have been so general, but it's still not a good idea to use
two variables with the same name if they're not actually the same.
Anyway, you're right of course.

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

iD8DBQFAMhlSaElZPz0soKgRAorPAJ41lNw7mqa35uqM4f8Ctra7hkft2QCgklAG
CcPsOYm6iIh8t8OLxVqaGHw=
=VzEk
-----END PGP SIGNATURE-----



More information about the Perl mailing list