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;
}

2 Comments »

  1. Have you looked at Data::Dumper? Part of every recent Perl release?

    print Data::Dumper->Dump ([$self],[qw(*self)) will print out the reference in $self, including all sub-components.

    Comment by david zuhn — July 14, 2008 @ 16:17 GMT

  2. Data::Dumper is pretty cool. I’ll likely replace my to_string() function with it. Thanks!

    Comment by sven — July 14, 2008 @ 18:34 GMT

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)


Powered by WordPress