How can I create an anonymous hash from an existing hash in Perl?

How can I create an anonymous hash from an existing hash?

For arrays, I use:

@x = (1, 2, 3);
my $y = [@x];

but I cannot find how to do the same for the hash:

my %x = ();
my $y = ???;

thanks

+5
source share
7 answers
my $new_hash = { %existing_hash };

Please note that this solution does not make a deep copy. Read Brian's answer for an explanation.

+13
source

Why do you need an anonymous hash? Although the answers tell you about the various methods of an anonymous hash, we do not know if any of them are suitable for what you are trying to do.

, , , dclone Storable, Perl. :

use Storable qw(dclone);
my $clone = dclone \%hash;

, . c - -:

use Data::Dumper;

my %original = ( a => 1, b => 2, c => { d => 1 } );
my $copy = { %original };

print 
    "Before change:\n\n",
    Data::Dumper->Dump( [ \%original], [ qw(*original) ] ),
    Data::Dumper->Dump( [ $copy ], [ qw(copy) ] ),
    ;

$copy->{c}{d} = 'foo';

print 
    "\n\nAfter change:\n\n",
    Data::Dumper->Dump( [ \%original], [ qw(*original) ] ),
    Data::Dumper->Dump( [ $copy ], [ qw(copy) ] ),
    ;

, , , , :

Before change:

%original = (
              'c' => {
                       'd' => 1
                     },
              'a' => 1,
              'b' => 2
            );
$copy = {
          'c' => {
                   'd' => 1
                 },
          'a' => 1,
          'b' => 2
        };


After change:

%original = (
              'c' => {
                       'd' => 'foo'
                     },
              'a' => 1,
              'b' => 2
            );
$copy = {
          'c' => {
                   'd' => 'foo'
                 },
          'a' => 1,
          'b' => 2
        };
+15

, . :

my %hash = (1 => 'one',2 => 'two');

:

my $ref = \%hash;
my $anon = {%hash};

$ref %hash. $anon - ; , .

, , ,

print $ref->{1},"\n";
> one
print $anon->{1},"\n";
> one

:

$hash{1} = "i";

print :

print $ref->{1},"\n";
> i
print $anon->{1},"\n";
> one
+8

my %hash = ...

my $hashref = \%hash;
+2

, , , .

  • . . .
  • . , , , . . (, : . .)

1, :

my $hash_ref = { foo => 1, bar => 2 };

2, :

my %hash = ( foo => 1, bar => 2 );

# Then later
my $anon_copy_hash_ref = { %hash };

( -.) -. . .

+1

:

$hashref = {};
0

Quick / easy way to achieve a deep copy:

use FreezeThaw qw(freeze thaw);
$new = thaw freeze $old;
0
source

All Articles