subroutine's name

Discussion in 'Perl Misc' started by nazrat, Feb 4, 2008.

  1. nazrat

    nazrat Guest

    hi,

    i have the following setting

    *f1 = \&foo;

    sub foo {
    print 'i am ', (caller(0))[3] , "\n";
    }

    f1(); # this prints main::foo


    is it possible for 'foo' to see its alias being called? (ie. f1() =>
    gives main::f1) thanks.
    nazrat, Feb 4, 2008
    #1
    1. Advertising

  2. nazrat

    Ben Morrow Guest

    Quoth nazrat <>:
    >
    > i have the following setting
    >
    > *f1 = \&foo;
    >
    > sub foo {
    > print 'i am ', (caller(0))[3] , "\n";
    > }
    >
    > f1(); # this prints main::foo
    >
    > is it possible for 'foo' to see its alias being called? (ie. f1() =>
    > gives main::f1) thanks.


    Not usually, no. Glob aliases point to the same sub, which only has one
    name. You can change that name with Sub::Name, but that will change the
    name of all aliases to this sub at once.

    If you *really* want to do this, you can clone the sub with
    Clone::Closure (actually, I think plain Clone will work for subs that
    aren't closures), assign that clone a new name, and put that in the
    symbol table:

    use Clone::Closure qw/clone/;
    use Sub::Name qw/subname/;

    *f1 = subname f1 => clone \&foo;

    but it would probably be better to have foo and f1 call a subordinate
    sub with a parameter:

    sub _dofoo {
    my $name = shift;
    warn "I am $name";
    }

    for my $sub (qw/foo f1/) { # $sub must be lexical
    no strict 'refs';
    *$sub = sub { _dofoo $sub, @_ };
    }

    Ben
    Ben Morrow, Feb 4, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Billy N. Patton
    Replies:
    9
    Views:
    6,776
    Alan Balmer
    Jul 27, 2004
  2. Michael Preminger

    obtaining name of the current subroutine

    Michael Preminger, Jul 16, 2004, in forum: Perl Misc
    Replies:
    1
    Views:
    85
    Vetle Roeim
    Jul 16, 2004
  3. Madhu Ramachandran

    calling subroutine , name derived from variable

    Madhu Ramachandran, Jan 6, 2006, in forum: Perl Misc
    Replies:
    26
    Views:
    225
    Matt Garrish
    Jan 9, 2006
  4. king
    Replies:
    5
    Views:
    177
  5. Hein, Nashua NH

    Sort using reference to subroutine name?

    Hein, Nashua NH, Aug 5, 2008, in forum: Perl Misc
    Replies:
    3
    Views:
    88
    Ben Morrow
    Aug 5, 2008
Loading...

Share This Page