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.


In reply to Re: Nervously....How do I access the Name of a Perl variable? by wog
in thread Nervously....How do I access the Name of a Perl variable? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.