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.
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 had only put this at the top of your script:
use strict;
use warnings;
...you would have gotten some error messages indicating what was wrong:
Global symbol "@my_array" requires explicit package name at kunjan-array.pl line 8.
Global symbol "@my_array" requires explicit package name at kunjan-array.pl line 11.
So, declare the array first with my @my_array;
and then you would get:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at kunjan-array.pl line 14.
- You created an arrayref and attempted to assign it to an array - see perldoc perldata for how to declare an array
- You attempted to assign an array to a hash (you can only assign scalars, such as an arrayref - see perldoc perlref for more about references)
- You need to dereference the hash element to get at the array element, e.g.
$my_hash{"Kunjan"}->[0]
- again see perldoc perlref for how to dereference a hashref
You have a few errors in your program:
my @my_array = ("aa" , "bbb");
$my_hash{"Kunjan"} = \@my_array;
print $my_hash{"Kunjan"}[0];
I made three changes:
- Added
my
in front of@my_array
on the first line - Change the
[...]
to(...)
on the first line - Add a
\
in front of @my_array on the second line
Try these amendments:
my %my_hash;
# ["aa" , "bbb"] produces an array reference. Use () instead
my @my_array = ("aa" , "bbb");
# 'Kunjan' hash is given reference to @my_array
$my_hash{ Kunjan } = \@my_array;
# bareword for hash key is nicer on the eye IMHO
print $my_hash{ Kunjan }[0];
However there is still one thing you need to consider if you use this method:
unshift @my_array, 'AA';
print $my_hash{ Kunjan }[0]; # => AA - probably not what u wanted!
So what you are probably after is:
$my_hash{ Kunjan } = ["aa" , "bbb"];
Then the hash is no longer referencing @my_array.
/I3az/
Others already explained nicely what's what, but I would like to add, that (especially if you're new to Perl), it would be great if you spend some time and read the perldsc and perllol docs.
精彩评论