how to write a subroutine that takes a subroutine as a parameter, executes it, but prints out the name

Posted on 2006-05-13
Last Modified: 2010-03-05
sub dispatch($doIt, $sub) {
  if (!doIt) { return; }
  if ($debuglevel > 1) {
# RIGHT HERE, how do I print the name of the subroutine?
  &$sub(); # execute the subroutine

dispatch(1, \&copyIn);
Question by:dbkruger
    LVL 84

    Accepted Solution

    You can't in general, the sub you pass may not have a name
    dispatch(1, sub{print "annonymous sub"})
    but you could also pass it a name
    LVL 84

    Expert Comment

    sub dispatch($doIt, $sub) { is not the proper syntax for subroutine prototypes
    perldoc perlsub
    LVL 11

    Author Comment

    sorry, I was tired:

    sub dispatch {
      my ($doIt, $sub) = @_;

    the question still stands.
    LVL 17

    Expert Comment

    How about the built-in function "caller" (see  Or a module on CPAN, like the DB module ( or Hook::LexWrap (

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
    Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    758 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now