How can I create an anonymous hash from an existing hash?
For arrays, I use:
@x = (1, 2, 3);
my $y = [@x];
but I can't find how to do the same for a hash:
my %x = ();
my $y = ???;
Thanks
An anonymous hash is simply a hash without a name. Both named and anonymous hashes have references, and \%hash is no more a direct reference than { foo => "bar" } . You imply that the latter is an indirect reference.
According to my research, copying a hashref is just as simple as using the equals operator: my $hashref_copy = $hashref; But as far as I can tell, all that does is make $hashref_copy a pointer to the original object.
Perl anonymous references These types of references are called anonymous references. The rules of creating anonymous references are as follows: To get an array reference, use square brackets [] instead of parentheses. To get a hash reference, use curly brackets {} instead of parentheses.
Extracting Keys and Values from a Hash variable The list of all the keys from a hash is provided by the keys function, in the syntax: keys %hashname . The list of all the values from a hash is provided by the values function, in the syntax: values %hashname . Both the keys and values function return an array.
Why do you need an anonymous hash? Although the answers tell you various ways you could make an anonymous hash, we have no idea if any of them are the right solution for whatever you are trying to do.
If you want a distinct copy that you can modify without disturbing the original data, use dclone
from Storable, which comes with Perl. It creates a deep copy of your data structure:
use Storable qw(dclone);
my $clone = dclone \%hash;
Consider Dave Webb's answer, but with an additional layer of references. The value for the key of c
is another hash reference:
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) ] ),
;
By inspecting the output, you see that even though you have an anonymous hash, it's still linked to the original:
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With