Data::Swap3pm
Swap type and contents of variables
Usage
use Data::Swap;my $p = [];my $q = {};print "$p $q\n"; # ARRAY(0x965cc) HASH(0x966b0)swap $p, $q; # swap referenced variablesprint "$p $q\n"; # HASH(0x965cc) ARRAY(0x966b0)my $x = {};my $y = $x; # $x and $y reference same varswap $x, [1, 2, 3]; # swap referenced var with an arrayprint "@$y\n"; # 1 2 3use Data::Swap 'deref';my @refs = (\$x, \@y);$_++ for deref @refs; # dereference a list of references# Note that I omitted \%z from the @refs because $_++ would fail# on a key, but deref does work on hash-refs too of course.
Overview
This module allows you to swap the contents of two referenced variables, even if they have different types.
The main application is to change the base type of an object after it has been created, for example for dynamic loading of data structures:
swap $self, bless $replacement, $newclass;
This module additionally contain the function "deref" which acts like a generic list-dereferencing operator.
Functions
swap REF1, REF2
Swaps the contents (and if necessary, type) of two referenced variables.
deref LIST
Dereferences a list of scalar refs, array refs and hash refs. Mainly exists because you can't use "map" for this application, as it makes copies of the dereferenced values.
Known issues
You can't "swap" an overloaded object with a non-overloaded one, unless you use Perl 5.10 or later.
Also, don't use "swap" to change the type of a directly accessible variable -- like "swap \$x, \@y". That's just asking for segfaults. Unfortunately there is no good way for me to detect and prevent this.
Releases
6 releases since Debian 8 (Jessie); the text changed 5 times.