Search

Search this site:

Introspection in Perl

Some days ago, my RSS reader found Mark Jason Dominus' Help.pm - Yes, the module is (so far, at least - I could not find it on CPAN) only published as a blog post. But don't let that fool you - It's a beautiful (and simple!) Perl module that can help developers that are too lazy to go look up methods in the man pages.

Perl's introspection capabilities are not behind other dynamic languages' (i.e. Python's or Ruby's, speaking only about what I'm familiar with). However, it's used much more seldom, partly because Perl does not ship by default with an interactive console (such as Ruby's irb or Python's regular behaviour when called without an input script). Of course, writing a Perl console is an easy task, and good Perl consoles exist, although its use is not part of the Perl culture.

But of course, just glancing over MJD's code made me come up with a simple, yet useful, way to use introspection in Perl, usable as a simple one-liner. Say you want to look at all of the methods provided by IO::File:

gwolf@mosca[25]/tmp$ perl -e 'use IO::File; print join(", ", grep {defined &{"IO::File::$_"}} sort keys %{"IO::File::"}), "\n"'
binmode, carp, confess, croak, gensym, new, new_tmpfile, open, qualify, qualify_to_ref, ungensym
Want the scalar variables? Of course:
gwolf@mosca[26]/tmp$ perl -e 'use IO::File; print join(", ", grep {defined ${"IO::File::$_"}} sort keys %{"IO::File::"}), "\n"'
VERSION
Same goes for arrays and hashes. And, of course, leaving out the grep gives you anything. Yup, it's the magic package-name hash trick. Main difference between this and MJD's Help.pm? That Help.pm goes up the inheritance chain, and is thus much more correct.

Of course, I'll be uploading Help.pm to Debian very soon - And, why not, I think I'll add a way for it to query on different symbols, not just on methods. And the simple binary to call from the command line. Sounds very much worth it ;-) Thanks, MJD!

Comments

Ryan Dietrich 2008-07-25 20:43:00

This is amazing..

I’ve been looking for a simple way to interrogate a class in Perl, for what feels like forever.. This is an awesome solution.. THANK YOU.

Categories