Here's a little thing I put together when I was trying to do something similar. It relies on the ref function. First here's the code:
#!/usr/bin/perl -w use strict; use warnings; my %xxx = (a=>5, b=>10, c=> {ca=>9, cb=>10}); my @yyy = ( [0, 1], {red=>2, blue=>3} ); my $aa = 5; my $bb=\%xxx; my $cc=\@yyy; print "aa=", thing_to_string($aa), "\n"; print "bb=", thing_to_string($bb), "\n"; print "cc=", thing_to_string($cc), "\n"; sub thing_to_string { my $t = shift; return '???UNDEF???' if !defined $t; if (ref $t eq '') { # It's a scalar, return it's value return $t; } elsif (ref $t eq 'ARRAY') { # It's an array, turn all the elements into strings, # separate them with commas, and wrap 'em in '(' and ')' return "(".join(", ", map { thing_to_string($_) } @$t ).")"; } elsif (ref $t eq 'HASH') { # It's a hash, turn all the elements into "key:value", # separate them with commas, and wrap 'em in '{' and '}' return "{".join(", ", map { $_."=>".thing_to_string($$t{$_}) } sort keys %$t)."}"; } # some other thing... return "...other..."; }
The first trick is knowing what you're trying to turn into a string. Perl gives us the ref operator for that. It's a pretty nifty operator. It returns an empty string if you hand it a scalar (i.e. not a reference):
[10:41:17] ~ $ perl -e '$a=5; print ref($a)' [10:41:29] ~ $
If you hand it a reference to a scalar it'll return 'SCALAR'. Similarly, if you hand it a reference to an array or hash, it will return 'ARRAY' or 'HASH', accordingly:
[10:41:29] ~ $ perl -e '$a=5; print ref(\$a)' SCALAR [10:43:19] ~ $ perl -e '@a=(1,2); print ref(\@a)' ARRAY [10:43:23] ~ $ perl -e '%a=(1=>0,2=>0); print ref(\%a)' HASH [10:43:26] ~ $
Now that we know how to recognize *what* we're supposed to turn into a string, we just need to figure out how to do it. For a scalar it's easy--perl already treats a scalar as a string, so we just return the value.
An array is only slightly trickier: We first need to turn all the array elements into strings. Once we do that, we can join all the items together with commas between them, then wrap it all up in parenthesis and return it as a string.
For a hash, we get a list of the keys and use that list to access the elements. We turn the elements into strings, and then add the key value and "=>" to the front of each one. Then, like we do for arrays, we separate all the items with commas, then wrap in braces and return it as a string.
The final trick: When we need to turn the array or hash elements into strings, the function calls itself to do so.
...roboticus
In reply to Re: Generic Way of printing of Hash of Array
by roboticus
in thread Generic Way of printing of Hash of Array
by snape
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |