zen.org Communal Weblog

July 14, 2008

Java’s toString() for perl

Filed under: — sven @ 15:11 GMT

I post it here so I can find it again if needed again. Sometimes I just want to see everything that is going on in a perl object. Sort of what Java’s toString() function does when printing out maps or lists. This is what I ended up with. Now it’s public domain!

our $join = ' ';
sub to_string{ # ug, java
    my $s = shift;
    my $out;
    if (ref $s) {
	if ($s =~ m/ARRAY/) {
	    $out .= '[' . join($join, map {
		to_string($_);
	    } @$_) . ']';
	} elsif ($s =~ m/HASH/) {
	    $out .= '{' . join($join, map {
		"$_=" . to_string($s->{$_});
	    } keys(%$s)) . '}';
	} else {
	    $out .= $s;
	    warn "How do i display '$s'?";
	}
    } else {
	$out .= quotemeta($s);
    }
    return $out;
}

Powered by WordPress