Belmark Caday
Belmark Caday

Reputation: 1683

Different declaration of hash in Perl

I know that:

my %hash = {};

gets an anonymous hash, How about this:

my %hash = %{some values}

what is the difference of that above with this?

my %hash = (some hash values);

Upvotes: 0

Views: 502

Answers (2)

Magnus Bodin
Magnus Bodin

Reputation: 76

The difference is how you express the content of the hash. With the array notation below, for example; you do it like this:

my %hash = ( 'key 1' => 'value 1', 'key 2' => 'value 2');

The %{ } is a cast operator. It is used typically when you have a reference to something that is not obviously a hash. Typically a reference to a has:

Example:

my $hashref;
$hashref->{'key 1'}='value 1';
$hashref->{'key 2'}='value 2';
my %hash = %{$hashref}; 

Upvotes: 3

choroba
choroba

Reputation: 241988

No.

my %hash = {};

generates a warning (you turned them on, right?):

Reference found where even-sized list expected at -e line 1.

Reference is always scalar. The correct way is

my $hash_ref = {};

To dereference a reference, you can use the following syntax:

my %hash      = %$hash_ref;
my %also_hash = %{$hash_ref};          # Same as above.
$hash{key} eq $hash_ref->{key} or die; # Should survive.

Moreover,

%{ some values }

generates a syntax error:

perl -we 'my $h = %{1, 2, 3, 4}'
syntax error at -e line 1, near "%{"

Upvotes: 6

Related Questions