[Israel.pm] swap arrays

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

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

My public key:
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org


More information about the Perl mailing list