Class-Cloneable
view release on metacpan or search on metacpan
lib/Class/Cloneable.pm view on Meta::CPAN
return Class::Cloneable::Util::clone($self);
}
package Class::Cloneable::Util;
use strict;
use warnings;
use overload ();
use Carp qw(confess);
use Scalar::Util qw(blessed reftype weaken isweak);
our $VERSION = '0.03';
sub clone {
(UNIVERSAL::isa((caller)[0], 'Class::Cloneable') ||
UNIVERSAL::isa((caller)[0], 'Class::Cloneable::Util'))
|| confess "Illegal Operation : This method can only be called by a subclass of Class::Cloneable";
my ($to_clone, $cache) = @_;
(defined($to_clone))
|| confess "Insufficient Arguments : Must specify the object to clone";
lib/Class/Cloneable.pm view on Meta::CPAN
}
sub cloneRef {
(UNIVERSAL::isa((caller)[0], 'Class::Cloneable') ||
UNIVERSAL::isa((caller)[0], 'Class::Cloneable::Util'))
|| confess "Illegal Operation : This method can only be called by a subclass of Class::Cloneable";
my ($to_clone, $cache, $ref_type) = @_;
(ref($to_clone) && (ref($cache) && ref($cache) eq 'HASH'))
|| confess "Insufficient Arguments : Must specify the object to clone and a valid cache";
$ref_type = ref($to_clone) unless defined $ref_type;
# check if it is weakened
my $is_weak;
$is_weak = 1 if isweak($to_clone);
my ($clone, $tied);
if ($ref_type eq 'HASH') {
$clone = {};
tie %{$clone}, ref $tied if $tied = tied(%{$to_clone});
%{$clone} = map { ref($_) ? clone($_, $cache) : $_ } %{$to_clone};
}
elsif ($ref_type eq 'ARRAY') {
$clone = [];
lib/Class/Cloneable.pm view on Meta::CPAN
$clone = \$var;
tie ${$clone}, ref $tied if $tied = tied(${$to_clone});
${$clone} = clone(${$to_clone}, $cache);
}
else {
# shallow copy reference to code, glob, regex
$clone = $to_clone;
}
# store it in our cache
$cache->{$to_clone} = $clone;
# and weaken it if appropriate
weaken($clone) if $is_weak;
# and return the clone
return $clone;
}
1;
__END__
=head1 NAME
t/10_Class_Cloneable_test.t view on Meta::CPAN
tied_hash => \%hash_to_tie,
tied_array => \@array_to_tie,
tied_scalar => \$scalar_to_tie,
code_ref => sub { "hello" },
regexp_ref => qr/(.*?)/,
glob_ref => \*new,
object_wo_clone => ObjectWithoutClone->new(),
object_w_clone => ObjectWithClone->new(),
cloneable_object => CloneableObject->new()
}, $class;
Scalar::Util::weaken($cloneable->{weak_scalar_ref});
$cloneable->{ref_to_ref} = \$cloneable->{scalar_ref};
return $cloneable;
}
}
{ # test cloneable object w/ overloading
package OverloadedCloneableTest;
our @ISA = ('CloneableTest');
use overload '""' => "toString";
sub toString { "This is my overloaded stringification method" }
( run in 0.230 second using v1.01-cache-2.11-cpan-65fba6d93b7 )