Reputation: 43
my $var1=[{'a'=>'1','b'=>'2'},1];
print @$var1[0]->{a};
it will print 1
but, if i print like below:
print @$var1->{a};
it will print error like below
Can't use an undefined value as a HASH reference;
Can anyone explain diff between both print statement?
Upvotes: 0
Views: 2880
Reputation: 1341
my $var1=[{'a'=>'1','b'=>'2'},1];
$var1 is array reference which contains hash reference at index 0 and scalar at index 1
to derefer $var1 to array, we have to use @$var1.(which gives the 2-element array) And for accessing single element we have to use $$var1[0] or $var1->[0].
And again $var1->[0] is a hash reference. To derefer it, we have to use $var1->[0]{'a'}.
But the statement "@$var1->{'a'}" is invalid, since
For more information, please refer
Upvotes: 0
Reputation: 64
In the first statement you print the value of key 'a' of the first element in your array (which is $var1) In the second statement you print the value of key 'a' of your array (and get an error as array doesn't have keys)
Hope this helps
Upvotes: 1
Reputation: 241898
@$var1[0]->{a}
is usually written as
$var1->[0]{a}
The second syntax, though, is different.
@$var1->{a}
is equivalent to
@{$var1}->{a};
You can't dereference an array (@{$var1}
) as a hash. Another question is why undef
is reported, to which I don't know the answer.
Upvotes: 5