Thursday, February 17, 2011

Perl generic data structure dumper

Here is a quick function to dump the contents of a generic mass of variables. I use it to debug the mass of random data structures that appear in random perl scripts

sub rec_print
{
    my ($message, $lead) = @_;
    
    if (ref($message) eq 'ARRAY') 
    { 
       # print  ":\n";        
        rec_print($_, $lead . " ")  foreach (@$message);
    }
    elsif (ref($message) eq 'HASH') 
    {
        foreach my $k (keys %$message)
        {
            print  "$lead$k:\n";
            rec_print($message->{$k}, $lead . " ");
        }
    }
    else
    {
        print "$lead$message\n";
    }
}

#example
rec_print({a=>"abc", b=>"bcd"},"");

2 comments:

  1. Chorny.. Simply put.. didn't know about it.. Thanks for the tip Ill try it out next time

    ReplyDelete