Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the array's element stored in my hash in Perl?

  # I have a hash 
  my %my_hash;

 # I have an array
  @my_array = ["aa" , "bbb"];

 # I store the array in my hash
  $my_hash{"Kunjan"} = @my_array;

 # But I can't print my array's element
  print $my_hash{"Kunjan"}[0];

I am new to Perl. Please help me.

like image 469
unj2 Avatar asked Nov 24 '09 21:11

unj2


People also ask

How can we access hash elements 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.

How do you access an array element in Perl?

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. Indexing will start with 0 from left side and with -1 from right side.

How do I read a hash 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 (%).


1 Answers

Your array syntax is incorrect. You are creating an anonymous list reference, and @my_array is a single-element list containing that reference.

You can either work with the reference properly, as a scalar:

$my_array = ["aa" , "bbb"];
$my_hash{"Kunjan"} = $my_array;

Or you can work with the list as a list, creating the reference only when putting it into the hash:

@my_array = ("aa" , "bbb");
$my_hash{"Kunjan"} = \@my_array;
like image 144
Adam Bellaire Avatar answered Nov 09 '22 00:11

Adam Bellaire