Implementing Swap [was Re: [Israel.pm] Report on Yesterday's Meeting]
Gaal Yahas
gaal at forum2.org
Sun Jun 5 10:37:28 PDT 2005
On Sun, Jun 05, 2005 at 08:04:50PM +0300, Shlomi Fish wrote:
> In the meeting, Shlomo used a swap($a, $b) function. Some people claimed it
> could not be implemented in Perl, or only by using prototypes. But in fact it
> can:
>
> sub swap
> {
> my ($v1, $v2) = (@_);
> $_[0] = $v2;
> $_[1] = $v1;
> }
If you know your arguments are not read-only, this works too.
sub swap {
($_[1], $_[0]) = @_;
}
# fatal error
print swap(1, 2);
# ok
my ($x, $y) = (1, 2);
swap($x, $y); # (2, 1)
--
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/
More information about the Perl
mailing list