So I have this code (sub refto), it seems to work fine, but I feel like I'm missing a utility function somewhere - core modules very much preferred - that does this without me having to fall back on B. I've checked Scalar::Util and Symbol. I'm probably just having a dense moment - does anyone happen to know off the top of their head?
use warnings;
use strict;
use B qw/svref_2object/;
sub refto {
my $ref = shift;
my $gv = svref_2object($ref)->GV;
return $gv->STASH->NAME . '::' . $gv->NAME;
}
sub foo {}
sub Foo::Bar::blah { }
print refto(\&foo), "\n"; # prints "main::foo"
print refto(\&Foo::Bar::blah), "\n"; # prints "Foo::Bar::blah"
print refto(sub{}), "\n"; # prints "main::__ANON__"
Background: I am storing code references in a table and want to give each one a sensible name. For __ANON__ code refs, I'll probably append the address to make them unique.
-
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.
|