[Israel.pm] swap arrays
Mikhael Goikhman
migo at homemail.com
Tue Feb 17 03:06:10 PST 2004
On 17 Feb 2004 11:42:11 +0200, Yosef Meller wrote:
>
> 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
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.
Second, like you mentioned, the bad side effect is that it also swaps $a
and $b, and %a and %b, and &a and &b. So, it's dangerous to suggest such
swap for general use even for globals.
BTW, if you want to dispatch a glob, you may specify *a{ARRAY} that is
equivalent to \@a, or *a{HASH} that is \%a, and so on.
> 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;
Regards,
Mikhael.
--
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'
More information about the Perl
mailing list