Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need $ when accessing array and hash elements in Perl?

Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do:

$x = $myarray[1];
$y = $myhash{'foo'};

instead of just doing :

$x = myarray[1];
$y = myhash{'foo'};

Why are the above ambiguous?

Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?

@var[0];
@var{'key'};
%var[0];
%var{'key'};
like image 597
Lorin Hochstein Avatar asked Sep 30 '08 15:09

Lorin Hochstein


People also ask

How can we access hash element in Perl?

Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.

Which one is the correct way of accessing array elements in Perl?

Perl Array Accessing To access a single element of a Perl array, use ($) sign before variable name. You can assume that $ sign represents singular value and @ sign represents plural values. Variable name will be followed by square brackets with index number inside it.

What is the difference between an array and a hash in Perl?

Arrays are ordered, and you access an element of an array using its numerical index. Hashes are un-ordered and you access a value using a key which is a string. Each hash key is associated with a single value and the keys are all unique inside a single hash structure.

What is hash of array in Perl?

A Perl hash is defined by key-value pairs. Perl stores elements of a hash in such an optimal way that you can look up its values based on keys very fast. Like a scalar or an array variable, a hash variable has its own prefix. A hash variable must begin with a percent sign (%). A hash key must be unique.


2 Answers

I've just used

my $x = myarray[1];

in a program and, to my surprise, here's what happened when I ran it:

$ perl foo.pl 
Flying Butt Monkeys!

That's because the whole program looks like this:

$ cat foo.pl 
#!/usr/bin/env perl

use strict;
use warnings;

sub myarray {
  print "Flying Butt Monkeys!\n";
}

my $x = myarray[1];

So myarray calls a subroutine passing it a reference to an anonymous array containing a single element, 1.

That's another reason you need the sigil on an array access.

like image 99
hexten Avatar answered Oct 14 '22 06:10

hexten


Slices aren't illegal:

@slice = @myarray[1, 2, 5];
@slice = @myhash{qw/foo bar baz/};

And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.

like image 45
zigdon Avatar answered Oct 14 '22 06:10

zigdon