Ragav_krish
Ragav_krish

Reputation: 43

Perl Array Reference with hash reference

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

Answers (3)

karsas
karsas

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

  1. Hash reference is present at 0 index of the array "@$var1".
  2. All references are scalar, Array cannot be used to derefer at hash reference.

For more information, please refer

  1. Perl Data Structures Cookbook
  2. Bless my Referents

Upvotes: 0

Alex G
Alex G

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

choroba
choroba

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

Related Questions