Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2024-04-18 13:23 GMT
Find Nodes?
    Voting Booth?

    No recent polls found