Unfortunately, my attempts, while producing functional code, seem to still make copies. diotalevi suggests that this is because the ( $x, $y ) = ( $y, $x ) construct has its own optimizations that create the copies internally no matter what you do. I also suspect that my FETCH method's ${$self->{VRef}} construct is creating a copy.
So my attempt at a pure Perl solution to swapping the values of two lexically scoped scalars without creating (explicitly or internally) copies, and without explicitly using references in the main code, is a failure.
Nevertheless, I thought that the attempt was worth demonstrating to see if anyone else could do anything with it. I really thought I was on to something, but it seems that there isn't a pure-Perl solution to the OP's quandry. Before I paste it here, I just wanted to quickly thank blokhead for helping me test it. Here it is:
package Tie::Scalar::NoCopies; # This package compiles, runs, and implements a tied # scalar. But it doesn't do as it advertises... ie., # it doesn't suppress copies. use strict; use warnings; sub TIESCALAR { my ( $class ) = @_; my $self = {}; $self->{VRef} = undef; bless $self, $class; } sub STORE { my $self = shift; $self->{VRef} = \$_[0]; return ${$self->{VRef}}; } sub FETCH { my $self = shift; return ${$self->{VRef}}; } sub DESTROY { my $self = shift; } 1; package main; use strict; use warnings; my ($var1, $var2); tie $var1, "Tie::Scalar::NoCopies"; tie $var2, "Tie::Scalar::NoCopies"; $var1 = 'a' x 10; $var2 = 'b' x 10; print "$var1\t$var2\n"; ( $var1, $var2 ) = ( $var2, $var1 ); print "$var1\t$var2\n";
Enjoy!!!
Dave
In reply to Re: How to swap scalar values without copies
by davido
in thread How to swap scalar values without copies
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |