Another solution using map. Does not pass an extra state variable around. More like a DFS approach. Handles array refs too. Uses brackets and curly brackets to differentiate between arrays and hashes.
sub flatten
{
my ($value) = @_;
my $rtype = ref $value or return "=$value\n"; # ends recursion
if ( $rtype eq 'ARRAY' ) {
return map {
my $i = $_; map { "[$i]$_" } flatten( $value->[ $_ ] );
} ( 0 .. $#$value );
}
elsif ( $rtype eq 'HASH' ) {
return map {
my $k = $_; map { "{$k}$_" } flatten( $value->{ $_ } );
} sort keys %$value;
}
die 'flatten only handles scalars, arefs, or hrefs';
}
print for flatten( \%hohoh );