173
|
1 package IMPL::clone;
|
|
2
|
174
|
3 use Scalar::Util qw(blessed reftype refaddr);
|
173
|
4
|
|
5 use base qw(Exporter);
|
|
6 our @EXPORT_OK = qw(&clone);
|
|
7
|
|
8 {
|
|
9 my %handlers = (
|
|
10 HASH => sub {
|
|
11 my $class = blessed($_[0]);
|
|
12
|
|
13 my $new = {};
|
|
14 while (my ($key,$val) = each %{$_[0]}) {
|
174
|
15 $new->{$key} = clone($val,$_[1]);
|
173
|
16 }
|
|
17 $class ? bless $new, $class : $new;
|
|
18 },
|
|
19 ARRAY => sub {
|
|
20 my $class = blessed($_[0]);
|
174
|
21 $class ? bless( [ map clone($_,$_[1]), @{$_[0]} ], $class ) : [ map clone($_), @{$_[0]} ];
|
173
|
22 },
|
|
23 SCALAR => sub {
|
|
24 my $class = blessed($_[0]);
|
|
25
|
|
26 my $v = ${$_[0]};
|
|
27 $class ? bless \$v, $class : \$v;
|
|
28 },
|
|
29 REF => sub {
|
|
30 my $class = blessed($_[0]);
|
174
|
31 my $v = clone ( ${$_[0]},$_[1] );
|
173
|
32 $class ? bless \$v, $class : \$v;
|
|
33
|
|
34 },
|
|
35 REGEXP => sub {
|
|
36 $_[0];
|
|
37 }
|
|
38 );
|
174
|
39
|
173
|
40 sub clone {
|
|
41 return unless @_;
|
|
42
|
|
43 return $_[0] unless ref $_[0];
|
|
44
|
174
|
45 return $_[1]->{refaddr($_[0])} ||= ($handlers{reftype($_[0])} || sub { die "Unknown reftype " . reftype($_[0])} )->($_[0]);
|
173
|
46 }
|
174
|
47
|
173
|
48 }
|
|
49
|
|
50 1;
|