Array and hashes declared using $ symbol in perl

Viewed 51

I was studying arrow operator in perl when i came across this:

# Perl program to demonstrate the Arrow Operator

#!/usr/local/bin/perl

use strict;
use warnings;

# reference to array
my $arr1 = [4,5,6];

# array inside array
my $arr2 = [4,5,[6,7]];

# reference to hash
my $has1 = {'a'=>1,'b'=>2};

# hash inside hash
my $has2 = {'a'=>1,'b'=>2,'c'=>[1,2],'d'=>{'x'=>3,'y'=>4}};

# using arrow operator
print "$arr1->[0]\n";
print "$arr2->[1]\n";
print "$arr2->[2][0]\n";
print "$has2->{'a'}\n";
print $has2->{'d'}->{'x'},"\n";
print $has2->{'c'}->[0],"\n";

Here, arrays and hashes are declared using $ symbol, but the code runs perfectly fine with this. Also code incurred errors when i replaced the $ signs in the declaration with @ and % symbols. This code is from Geeksforgeeks.

I browsed the internet for explanation but found similar thing done on Educative.

1 Answers

Both [] and {} returns a reference, and references are scalars.

my $a = [ ... ];
my $h = { ... };

is equivalent to

my @anon_a = ...;
my $a = \@anon_a;

my %anon_h = ...;
my $h = \%anon_h;

And that's why you have to use

$a->[0]    # Access an element of the array referenced by `$a`.

instead of

$a[0]      # Access an element of the array `@a`.
Related