Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a new, empty hash reference in Perl?

Say I had something like:

# %superhash is some predefined hash with more than 0 keys;
%hash = ();
foreach my $key (keys %superhash){
    $superhash{ $key } = %hash;
    %hash = ();
}

Would all the keys of superhash point to the same empty hash accessed by %hash or would they be different empty hashes?

If not, how can I make sure they point to empty hashes?

like image 372
Ritwik Bose Avatar asked Feb 23 '10 07:02

Ritwik Bose


People also ask

How do I initialize a hash in Perl?

Consider the following code: #!/usr/bin/perl use Data::Dumper; my %hash = (); $hash{currency_symbol} = 'BRL'; $hash{currency_name} = 'Real'; print Dumper(%hash);

How do I empty a hash array in Perl?

Empty values in a Hash: Generally, you can't assign empty values to the key of the hash. But in Perl, there is an alternative to provide empty values to Hashes. By using undef function. “undef” can be assigned to new or existing key based on the user's need.

How do I pass a hash reference in Perl?

This information can be found by typing perldoc perlref at the command line. Single element slice better written as %{$_[0]} , %{shift} is referring to a hash variable named shift , you probably meant %{+shift} or %{shift @_} . Named loop variables should be lexical foreach my $key...


1 Answers

You need to use the \ operator to take a reference to a plural data type (array or hash) before you can store it into a single slot of either. But in the example code given, if referenced, each would be the same hash.

The way to initialize your data structure is:

foreach my $key (keys %superhash) {
    $superhash{ $key } = {}; # New empty hash reference
}

But initialization like this is largely unnecessary in Perl due to autovivification (creating appropriate container objects when a variable is used as a container).

my %hash;

$hash{a}{b} = 1;

Now %hash has one key, 'a', which has a value of an anonymous hashref, containing the key/value pair b => 1. Arrays autovivify in the same manner.

like image 191
Eric Strom Avatar answered Oct 16 '22 04:10

Eric Strom