Updated: Initializing and clearing multiple hashes in one line
It looks like (from your comments) that you really want to empty hashes that already have things in them. You can do it like this:
(%hash1,%hash2,%hash3) = ();
Complete example:
use strict;
use warnings;
my %hash1 = ('foo' => 1);
my %hash2 = ('bar' => 1);
my %hash3 = ('baz' => 1);
(%hash1,%hash2,%hash3) = ();
print (%hash1,%hash2,%hash3);
A variable declaration always gives an empty variable, so there is no need to set it to empty. This is true even in a loop:
for (0..100)
{
my $x;
$x++;
print $x;
}
This will print 1
over and over; even though you might expect it $x
to retain its value, it is not.
Explanation: Perl allows you to assign a list, eg ($foo,$bar) = (1,2)
. If the list on the right is shorter, all other items get undef
. So assigning an empty list to a list of variables makes them all undefined.
Another useful way to set a bunch of things is with the operator x
:
my ($x,$y,$z) = (100)x3;
This sets all three variables to 100. It doesn't work that well for hashes, because everyone needs a list assigned to it.
You don't need to assign anything to new to make sure it's empty. All variables are empty if nothing is assigned to them.
my %hash; # hash contains nothing
%hash = () # hash still contains nothing
The only time it would be useful to assign an empty list to a hash is if you want to remove previously assigned values. And even then it would only be a useful task if it couldn't be solved by applying the correct size limit for the hash.
my (%hash1, %hash2);
while (something) {
# some code
(%hash1,%hash2) = (); # delete old values
}
Emptying hashes. Better written as:
while (something) {
my (%hash1, %hash2); # all values are now local to the while loop
# some code
}
source to share