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

%host_groups = get_host_groups(); foreach my $group (keys %host_groups) { print "$group = $group\t"; foreach (@{$host_groups{$group}}) { print "$host = $_\n"; } } sub get_host_groups() { .... while ($line = <FILE>) { .... $group_name = $hgn[2]; .... $hash{$group_name}= [@hosts]; .... .... } return (%hash); }

Replies are listed 'Best First'.
Re: Is it right method to use Hash
by GrandFather (Saint) on Jun 10, 2011 at 10:43 UTC

    It depends what you want to achieve. If you want to ensure that you retain only the last set of hosts for each group in the file (assuming there may be multiple lines for the same group) and don't care what order the groups are printed, then yes what you are doing is appropriate. If that is not what you want you better tell us a little more about the problem you are trying to solve.

    You could of course try running your code to see if it does what you want. Even better, you could generate a few test data sets and see that you get the results you expect for each data set. If you wrap that testing up in a test script that checks the results then you can regression test your system when you make changes to it or fix bugs.

    True laziness is hard work
      Thanks for your reply. As group has only one line of hosts and sub is used only for reading, this script is working exactly fine. But I was bit confused about returning hash variable in sub am I doing it correctly?
Re: Is it right method to use Hash
by bart (Canon) on Jun 10, 2011 at 11:19 UTC
    I think what you're trying to do is something like this:
    my %test = ('a' => {'b' => 'c'}); while ( my($name1, $value1) = each %test ) { print "$name1:\n"; if(ref $value1 eq 'HASH') { while ( my($name2, $value2) = each %$value1 ) { print " $name2: $value2\n"; } } else { print "$value1\n"; } }
    which prints:
    a:
      b: c
    

    The test using ref might be a bit superfluous here, but it opens the door to indeed making the implementation using a recursive sub, and for using uneven leveled hashes. This way, you can nest to an indefinite level.