in reply to Complex hash?

I don't recommend this, but just so you can see how you can do it:

for (sort keys %hash) { print "$_ => "; if (ref($hash{$_}) eq 'ARRAY') { print join(', ', @{ $hash{$_} }); } elsif (ref($hash{$_}) eq 'HASH') { # do something else } else { print $hash{$_}; } print "\n"; }
I'll leave handling the HASH case as your excercise. ;)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re^2: Complex hash?
by GrandFather (Saint) on Aug 24, 2006 at 20:48 UTC

    Consider:

    use strict; use warnings; use Tk; my $mw = MainWindow->new (-title => 'Hello World'); my @arr=('first', 'second', 'third'); my %hash = (A => 100, B => 200, C => [@arr], D => \&hi, E => $mw); $hash{'A'}=100; $hash{'B'}=200; $hash{'C'}=[@arr]; for (sort keys %hash) { print "$_ => "; if (ref($hash{$_}) eq 'ARRAY') { print "Array: ", join(', ', @{ $hash{$_} }); } elsif (ref($hash{$_}) eq 'HASH') { # do something else print "Hash: ..."; } else { print "Scalar: $hash{$_}"; } print "\n"; } sub hi { print "hello World"; }

    Prints:

    A => Scalar: 100 B => Scalar: 200 C => Array: first, second, third D => Scalar: CODE(0x21bdf50) E => Scalar: MainWindow=HASH(0x21d97ac)

    Adding:

    elsif (ref($hash{$_})) { print "Unknown ref: $hash{$_}";

    alters the output to:

    A => Scalar: 100 B => Scalar: 200 C => Array: first, second, third D => Unknown ref: CODE(0x21be538) E => Unknown ref: MainWindow=HASH(0x21d9e38)

    References come in many flavours. There is probably no good general answer to OP's question for "display" output (as opposed to debugging output), but at least unhandled cases can be caught by noting that ref returns undef for non-reference values.


    DWIM is Perl's answer to Gödel