Reputation: 3049
I'll be glad if someone can enlighten me as to my mistake:
my %mymap;
@mymap{"balloon"} = {1,2,3};
print $mymap{"balloon"}[0] . "\n";
Upvotes: 5
Views: 17079
Reputation: 67900
Well, first off, always use strict; use warnings;
. If you had, it might have told you about what is wrong here.
Here's what you do in your program:
my %mymap; # declare hash %mymap
@mymap{"balloon"} = {1,2,3}; # attempt to use a hash key on an undeclared
# array slice and assign an anonymous hash to it
print $mymap{"balloon"}[0] . "\n"; # print the first element of a scalar hash value
For it to do what you expect, do:
my %mymap = ( 'balloon' => [ 1,2,3 ] );
print $mymap{'balloon'}[0];
Upvotes: 3
Reputation: 29854
$mymap{'balloon'}
is a hash not an array. The expression {1,2,3}
creates a hash:
{
'1' => 2,
'3' => undef
}
You assigned it to a slice of %mymap
corresponding to the list of keys: ('balloon')
. Since the key list was 1 item and the value list was one item, you did the same thing as
$mymap{'balloon'} = { 1 => 2, 3 => undef };
If you had used strict
and warnings
it would have clued you in to your error. I got:
Scalar value @mymap{"balloon"} better written as $mymap{"balloon"} at - line 3.
Odd number of elements in anonymous hash at - line 3.
Upvotes: 6
Reputation:
Okay, a few things...
%mymap
is a hash. $mymap{"balloon"}
is a scalar--namely, the value of the hash %mymap
corresponding to the key "balloon"
. @mymap{"balloon"}
is an attempt at what's called a hash slice--basically, you can use these to assign a bunch of values to a bunch of keys at once: @hash{@keys}=@values
.
So, if you want to assign an array reference to $mymap{"balloon"}
, you'd need something like:
$mymap{"balloon"}=[1,2,3]
.
To access the elements, you can use ->
like so:
$mymap{"balloon"}->[0] #equals 1
$mymap{"balloon"}->[1] #equals 2
$mymap{"balloon"}->[2] #equals 3
Or, you can omit the arrows: $mymap{"balloon"}[0]
, etc.
Upvotes: 1
Reputation: 4285
If you had used 'use strict; use warnings;' on the top of your code you probably have had better error messages.
What you're doing is creating a hash called mymap. A hash stores data as key => value pairs. You're then assigning an array reference to the key balloon. Your small code snipped had two issues: 1. you did not addressed the mymap hash, 2. if you want to pass a list, you should use square brackets:
my %mymap;
$mymap{"balloon"} = [1,2,3];
print $mymap{"balloon"}[0] . "\n";
this prints '1'.
You can also just use an array:
my @balloon = (1,2,3);
print $balloon[0] . "\n";
Upvotes: 5