Cleaning up code - flatten a nested hash structure

Posted by knorv on Stack Overflow See other posts from Stack Overflow or by knorv
Published on 2010-03-22T20:52:16Z Indexed on 2010/03/22 21:01 UTC
Read the original article Hit count: 261

Filed under:
|
|

The following Perl sub flattens a nested hash structure:

sub flatten {
  my $hashref = shift;
  my %hash;
  my %i = %{$hashref};
  foreach my $ii (keys(%i)) {
    my %j = %{$i{$ii}};
    foreach my $jj (keys(%j)) {
      my %k = %{$j{$jj}};
      foreach my $kk (keys(%k)) {
        my $value = $k{$kk};
        $hash{$kk} = $value;
      }
    }
  }
  return %hash;
}

While the code works it is not very readable or clean.

My question is two-fold:

  • In what ways does it not correspond to modern Perl best practices?
  • How would you clean it up?

© Stack Overflow or respective owner

Related posts about perl

Related posts about clean-up