Sourcecode
Sourcecode

Reputation: 315

Updated: Initialise and Clear multiple hash in one line

How can I Initialise and clear multiple hash in one line.

Ex:

my %hash1 = ();
my %hash2 = ();
my %hash3 = ();
my %hash4 = ();

to

my ( %hash1, %hash2, %hash3, %hash4 ) = ?

Upvotes: 3

Views: 1023

Answers (4)

user1919238
user1919238

Reputation:

It appears (from your comments) that you really want to empty hashes that already have stuff 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 you 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 $x to retain its value, it does not.

Explanation: Perl allows list assignment like ($foo,$bar) = (1,2). If the list on the right is shorter, any remaining elements get assigned undef. Thus assigning the empty list to a list of variables makes them all undefined.

Another useful way to set a bunch of things is the x operator:

my ($x,$y,$z) = (100)x3;

This sets all three variables to 100. It doesn't work so well for hashes, though, because each one needs a list assigned to it.

Upvotes: 5

Zaid
Zaid

Reputation: 37156

It's as simple as doing

my ( %hash1, %hash2, %hash3, %hash4 );

and they will not contain any keys or values at that point.

The same technique applies to scalars and arrays.

To undef multiple hashes, you could do

undef %$_ for ( \%hash1, \%hash2 );

Upvotes: 5

TLP
TLP

Reputation: 67920

You do not need to assign anything to a new variable in order to assure it is empty. All variables are empty, if nothing has been assigned to them.

my %hash;  # hash contains nothing
%hash = () # hash still contains nothing

The only time it would be useful to assign the empty list to a hash is if you want to remove previously assigned values. And even then, that would only be a useful thing to do if it could not already be solved by applying the correct scope restriction to the hash.

my (%hash1, %hash2);
while (something) {
    # some code
    (%hash1,%hash2) = ();   # delete old values
}

Emptying the hashes. Better written as:

while (something) {
    my (%hash1, %hash2);    # all values are now local to the while loop
    # some code
}

Upvotes: 0

Andrii Tykhonov
Andrii Tykhonov

Reputation: 538

You can initialize it as:

my %hash1 = %hash2 = %hash3 = %hash4 = ();

Upvotes: 0

Related Questions