# 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.
Perl Hash Accessing To access single element of hash, ($) sign is used before the variable name. And then key element is written inside {} braces.
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.
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 (%).
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With