http://qs321.pair.com?node_id=173363


in reply to Nervously....How do I access the Name of a Perl variable?

Getting the line number and filename is relatively easy:

sub trace { my($package, $filename, $line) = caller; # ... }

You can also get the subroutine its in. See the docs for caller.

Getting the names of the relevant variables is much harder, because perl does not such a convinent mechanism for compile-time expanded macros as C. However there are things called source filters, and the Filter::Simple module provides a nice interface to them. So, we can use that to make a module that adds a TRACE() macro:

package TraceMacro; use Filter::Simple; FILTER_ONLY code => sub { s/TRACE\(\s*([^)]+)\s*\)/__PACKAGE__."::_trace(q($1),$1)"/eg; }; # replace each TRACE(...) with <this package>::_trace(q(...),...) sub _trace { my($names,@values) = @_; my @names = split /\s*,\s*/, $names; # extract varnames my($package,$file,$line) = caller; foreach my $i(0..$#names) { print STDERR "$file ($line): $names[$i]:'$values[$i]'"; } }

(The module just needs to be saved appropriately to a file called by the name of Package.pm where Package is whatever's specified by the package declaration. (You could change that.))

This has the side-effect of allowing arbitrary expressions instead of just variable names.

update: Usage would be like:

use TraceMacro; # ... TRACE( $foo, $bar );
If you want to change TRACE to trace (I prefer that compile-time-special things be uppercased), then it shouldn't be hard to fiquire that out.