Bhargav Gor
Bhargav Gor

Reputation: 581

fetching all values from Hashes with Multiple Values Per Key in perl

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

Answers (3)

Patt Mehta
Patt Mehta

Reputation: 4204

Bhargav Gor, bhai, this is a common way of storing multiple values for a key.

But,

  1. keep in mind that this is an anonymous hash i.e key-value pair: {39,34,11,12} = ("39"=>34, "11"=>12)

  2. 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

cdtits
cdtits

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

Quentin
Quentin

Reputation: 943639

You have three problems.

  1. You are using hashrefs, not arrayrefs
  2. You aren't assigning anything to @val (at least, you weren't before you edited the question)
  3. You aren't doing anything to dereference your references

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

Related Questions