PERL-how can I print this output

Thread Starter

Jaden5165

Joined Sep 9, 2011
69
Example:

%hh =
(
key1 =>
{
** key2 => 'abc',
** key3 => {* keymany = 'value', },
*}
key11 =>
{
***key22 => 'def',
*}
)
*
Output:
key1** key2** abc
key1** key3** keymany*** value
key11* key22* def
 

tkil

Joined Nov 15, 2012
1
Example:

%hh =
(
key1 =>
{
** key2 => 'abc',
** key3 => {* keymany = 'value', },
*}
key11 =>
{
***key22 => 'def',
*}
)
*
Output:
key1** key2** abc
key1** key3** keymany*** value
key11* key22* def
Jaden --

I'm assuming those "*" are tab characters?

If your hierarchy can be arbitrarily deep, you need a recursive function. Someting like this:
sub print_hash
{
my ( $prefix, $href ) = @_;

while ( my ( $key, $val ) = each %$href )
{
if ( ref $val )
{
print_hash "$prefix$key\t", $val;
}
else
{
print "$prefix$key\t$val\n";
}
}
}
Then you want a main program that just calls that function with an empty prefix and a reference to the hash:
print_hash "", \%hh;

Note that there is a built-in module (Data::Dumper) which will do much of this for you, especially if you are just trying to debug some internal structures.

Here's a working version, with indentation that is actually useful: http://ideone.com/psIIoV
 
Last edited:

Thread Starter

Jaden5165

Joined Sep 9, 2011
69
Jaden --

I'm assuming those "*" are tab characters?

If your hierarchy can be arbitrarily deep, you need a recursive function. Someting like this:
sub print_hash
{
my ( $prefix, $href ) = @_;

while ( my ( $key, $val ) = each %$href )
{
if ( ref $val )
{
print_hash "$prefix$key\t", $val;
}
else
{
print "$prefix$key\t$val\n";
}
}
}
Then you want a main program that just calls that function with an empty prefix and a reference to the hash:
print_hash "", \%hh;

Note that there is a built-in module (Data::Dumper) which will do much of this for you, especially if you are just trying to debug some internal structures.

Here's a working version, with indentation that is actually useful: http://ideone.com/psIIoV

Thanks Tkil.I will work on it. :)
 
Top