Reputation: 581
how to fetch all the values and print it, in the code follows multiple values per key
%ages = (
" Michael Caine" => {39,34,11,12},
" Dirty Den" => {34,56,76,58},
" Angie" => {27,56,78,89}
);
@keys = keys %ages;
@val = values %ages;
print @keys;
print @val; #it will not work in case of multiple values per key
Upvotes: 1
Views: 2633
Reputation: 4204
Bhargav Gor, bhai, this is a common way of storing multiple values for a key.
But,
keep in mind that this is an anonymous hash i.e key-value pair: {39,34,11,12} = ("39"=>34, "11"=>12)
and this is an anonymous array: [39,34,11,12]
You have used 1. which means you are using another hash as a value for the %ages hash, i.e
%ages =
" Michael Caine" => ("39"=>34,"11"=>12),
" Dirty Den" => ("34"=>56,"76"=>58),
" Angie" => ("27"=>56,"78"=>89)
If you want to extract the values for the key "39" of key " Michael Caine"
print %{$ages{" Michael Caine"}}->{"39"} #prints 34
if really you want such a structure, then this is how you can display all values
foreach(keys %ages) {
$name = $_;
foreach(keys %{$ages{$name}}) {
print %{$ages{$name}}->{$_},",";
}
print "\n";
}
#output:
#>34,12,
#>56,58,
#>56,89,
I do not think that you wanted this kind of a stucture, you probably wanted to use an array, (an anonymous array).
%ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89]
);
Now you can easily display output like this:
foreach(keys %ages) {
$name = $_;
foreach( @{$ages{$name}} ) {
print $_,",";
}
print "\n";
}
#output:
#>39,34,11,12,
#>34,56,76,58,
#>27,56,78,89,
I'm sorry I have to rush, sorry for typos, hope you understand what you should do for such a storage
Upvotes: 1
Reputation: 1128
%ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89],
);
@keys = keys %ages;
@val = values %ages;
print "@keys\n";
print "@{$_}\n" for @val;
Upvotes: 1
Reputation: 943639
You have three problems.
@val
(at least, you weren't before you edited the question)Such:
use v5.10;
my %ages = (
" Michael Caine" => [39,34,11,12],
" Dirty Den" => [34,56,76,58],
" Angie" => [27,56,78,89]
);
foreach my $key (keys %ages) {
say $key;
say @{$ages{$key}};
}
Upvotes: 3