I'd like to (re)name an anonymous sub, at least for the purposes of svref_2object and it's brethren. It's cleaner to declare the sub anonymous, since it doesn't do much, is really a method call, and I'm using the anonymous "wrap up the lexicals" feature that named subs complain about.

I've tried the local *__ANON__ = "name"; solution, but it doesn't affect svref_2object. Below is the outline of the code I want to use this in.

use B qw(svref_2object); use Foo::Bar; my $self = Foo::Bar->new; # wrap a method call in a sub my $anon = sub { $self->mumble("blah\n") }; # pass the coderef to $self->grumble($anon, qw(one two three)); # ...meanwhile in Foo::Bar... sub grumble { my $self = shift; my $anon = shift; my @args = @_; # Get the name of the sub my $anon_cv = svref_2object ( $anon ); my $anon_gv = $anon_cv->GV; my $anon_name = $anon_gv->NAME; print "About to call $anon_name...\n"; $anon->(@args); }

Update: Added a catch for $self at the beginning of grumble.

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Naming an anonymous sub for svref_2object by QM

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.