abc
abc

Reputation: 113

Perl - Confusion between array and hash

How would you retrieve the 'A' from $this in the following line of code:

my $this = { 1 => "A", 2 => "B", 3 => "C" };

I am new to Perl and have a couple of questions from the above line.

1) Firstly, is this a valid line of code?

2) What kind of data structure is this? I thought it as hash, but the following line did not give me 'A'.

print "$this{1}";

Upvotes: 0

Views: 56

Answers (1)

Miller
Miller

Reputation: 35198

Yes, that is an anonymous hash reference.

It's roughly equivalent to saying:

my %hash = ( 1 => "A", 2 => "B", 3 => "C" );

my $this = \%hash;

To access the value "A", you would use:

print $this->{1};

For an intro to Perl, I suggest reading the Modern Perl Book. The Perl Language section will discuss data structures and references.

Upvotes: 4

Related Questions