0
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?

1
  • 1
    The only way you can access a is through element 0 of the array. Not sure what you expected of the second print statement. Commented Jun 16, 2015 at 11:34

3 Answers 3

5
@$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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note: @{$var1}->{a} should be equivalent to "0"->{a}, but it's not. It produces really odd code instead.
1

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.