PerlKitten has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I have a two-dimensional hash: ManagerInCharge{month}{week} defined below. For any given month, I'd like to make a list variable containing all the weeks included in that month. For example, for 200610 (Oct 2006), I'd like to assign to some variable the list (1,2,3,4), while for 200701, I'd like to extract (1,2,3). Please help! (I did not find this in Learning Perl, though it may be there somewhere.)

%ManagerInCharge = (

200610 => {

1 => "jane",

2 => "john",

3 => "joe",

4 => "frank",

},

200701 => {

1 => "gunder",

2 => "abel",

3 => "frank",

},

);

  • Comment on Extracting a list of keys from a multi-dimensional hash.

Replies are listed 'Best First'.
Re: Extracting a list of keys from a multi-dimensional hash.
by moritz (Cardinal) on Jan 16, 2008 at 15:30 UTC
    Untested:
    for my $k (sort keys %ManagerInCharge){ print "Month: $k\n"; my @keys = keys %{$ManagerInCharge{$k}}; print "Managers: ", join(",", @keys), "\n"; }
Re: Extracting a list of keys from a multi-dimensional hash.
by memnoch (Scribe) on Jan 16, 2008 at 15:57 UTC

    The code provided by moritz above works, but does not sort the output as it seems you wanted. To have the output sorted, you could add a sort sub to his code as in the following:

    for my $k (sort keys %ManagerInCharge){ print "Month: $k\n"; my @keys = sort {$a <=> $b} keys %{$ManagerInCharge{$k}}; print "Managers: ", join(",", @keys), "\n"; }

    memnoch
Re: Extracting a list of keys from a multi-dimensional hash.
by dwm042 (Priest) on Jan 16, 2008 at 16:54 UTC
    I'm going on the assumption that you don't want the keys to be assigned to a list, but rather you want the hash values for a particular month to be assigned to the list. I haven't bothered sorting the result as you can sort the list however you want once it is assigned.

    #!/usr/bin/perl use warnings; use strict; my %ManagerInCharge = ( 200610 => { 1 => "jane", 2 => "john", 3 => "joe", 4 => "frank", }, 200701 => { 1 => "gunder", 2 => "abel", 3 => "frank", }, ); my $month = "200701"; # # If you need the keys assigned, then the statement # my @slice = keys %{$ManagerInCharge{$month}} # is enough. # my @slice = map { $ManagerInCharge{$month}{$_} } ( keys %{$ManagerInCharge{$month}} ); for (@slice) { print "value is $_\n"; }
    and the results are:

    C:\Code>perl assign_slice.pl value is gunder value is frank value is abel
      couldn't the statement:

      my @slice = map { $ManagerInCharge{$month}{$_} } ( keys %{$ManagerInCharge{$month}} );

      be written more simply as:

      my @slice = values %{$ManagerInCharge{$month}};