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?
Consider the following code: #!/usr/bin/perl use Data::Dumper; my %hash = (); $hash{currency_symbol} = 'BRL'; $hash{currency_name} = 'Real'; print Dumper(%hash);
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.
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...
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.
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