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

Hi !
I have a question about iteratively printing values of elements in multi-dimensional keys hash. For example I am building an hash dynamically from a data set such as
my %test;
Now I get emp_id, dept_id,week_id as values, I want to build a hash whc ih stores departmentwise, employeewise weekwise hours worked (as example)

so I start adding these figures as
$test{$deptid}{$empid}{$weekid}+=$hrs_worked;

Once all data set is parsed I want to print this hash iteratively. How do I do this? Also is there anyway with which given a hash it will programatically find out the dimensions and iterate through dynamically to print end values?

Thanks
  • Comment on How to print Hash with multidimensional keys

Replies are listed 'Best First'.
Re: How to print Hash with multidimensional keys
by stajich (Chaplain) on Jun 04, 2002 at 19:46 UTC
    Data::Dumper would work - but if you actually want to do something special with the data, sort it in a special way, or change the output style you might want to define your own function to dump things recursively. If you wanted to do this on the web you could replace "\n" with <br> and "\t" with <dd> or wrap some <ul >.. </ul >around each recursive call.
    #!/usr/bin/perl -w use strict; my %test; $test{'bio'}{900}{1} = 40; $test{'bio'}{900}{2} = 45; $test{'bio'}{901}{1} = 38; $test{'chem'}{1800}{1} = 27; $test{'chem'}{1800}{3} = 47; print_recursive(\%test); sub print_recursive { my ($hash,$depth) = @_; return unless $hash && ref($hash) =~ /HASH/i; $depth ||= 0; foreach my $key ( keys %{ $hash } ) { print "\t"x$depth, $key, "\n"; print_recursive($hash->{$key},$depth+1); } }
      Thanks
      This is really useful direction.

      Thanks all
Re: How to print Hash with multidimensional keys
by George_Sherston (Vicar) on Jun 04, 2002 at 18:59 UTC
      Certainly this helped.

      But is there any way that this output can be formatted (say pipe separated for a particular key wise etc? So as it prints
      key1_val|key2_val|key3_val|element_val \n
      And so on?

      Of course now I will study more abourt Dumbper class

      Thanks
        As you've probably seen from the Data::Dumper docs, several output formats are offered, one of which may suit your needs.

        In any event, the Dumper output follows regular rules, so you can write regexes to convert it to whatever format was useful. Arguably it's quicker to let Data::Dumper turn it into a regular format and then regex, than try to iterate through and do the conversion yourself.

        When I have done this, I've always been glad when I remembered the /s regex modifier ;)

        § George Sherston