PERL-how can I print this output

Discussion in 'Programmer's Corner' started by Jaden5165, Nov 15, 2012.

  1. Jaden5165

    Thread Starter Member

    Sep 9, 2011
    69
    0
    Example:

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

    New Member

    Nov 15, 2012
    1
    0
    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: Nov 16, 2012
  3. Jaden5165

    Thread Starter Member

    Sep 9, 2011
    69
    0

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