fugu
fugu

Reputation: 6578

Empty hash declaration

I've never known the difference, if there is one, between the following:

my %hash;
my %hash = ();

Could anyone shed some light on this?

Upvotes: 7

Views: 3819

Answers (2)

ikegami
ikegami

Reputation: 386361

In some languages, new variables are provided uninitialized. In Perl, scalars are created undefined, and array and hashes are created empty.

The second is wasteful. Assigning an empty list to an empty hash has no effect.

Upvotes: 6

Sobrique
Sobrique

Reputation: 53498

You're quite correct. There's no difference. Declaring a hash (or array) creates an empty data structure.

This is slightly at odds with declaration of scalars - a scalar can be declared but undefined. This doesn't really make sense for a hash or array, so it makes no difference.

use Data::Dumper;

my $scalar;
my $scalar2 = '';

print Dumper \$scalar;
print Dumper \$scalar2;

my %hash;
my %hash2 = ();
print Dumper \%hash;
print Dumper \%hash2;

my @array;
my @array2 = ();

print Dumper \@array;
print Dumper \@array2;

If you look at the defined docs, you see:

"Use of defined on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate had ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size:"

Upvotes: 4

Related Questions