[Israel.pm] swap arrays

Mikhael Goikhman migo at homemail.com
Mon Feb 16 07:34:00 PST 2004


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.

But you may write a function doing this elegantly (the signature is
critical here), like in this small program that may be pasted into perl:

	sub swap_arrays (\@\@) {
		my @temp = @{$_[0]};
		@{$_[0]} = @{$_[1]};
		@{$_[1]} = @temp;
	}

	my @a = (1, 2, 3, 4);
	my @b = qw(one two three);

	swap_arrays(@a, @b);

	print '@a = (', join(', ', @a), ")\n";
	print '@b = (', join(', ', @b), ")\n";

You may remove the '(\@\@)' signature from the function or replace it
with '($$)' with anything else unchanged, but then you should call it
less elegantly:

	swap_arrays(\@a, \@b);

Regards,
Mikhael.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list