bcarroll has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to tie a callback/subroutine that will be automatically executed when another function/subroutine is called?

For example: If I call the built-in open() function, it does it's thing.

I would like to watch for calls to open() and execute my own subroutine at the same time (before or after, but automatically). Is this possible?

  • Comment on Tie subroutine to a built-in function call?

Replies are listed 'Best First'.
Re: Tie subroutine to a built-in function call?
by BrowserUk (Patriarch) on Aug 23, 2016 at 17:15 UTC

    See Overriding core functions.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Tie subroutine to a built-in function call?
by stevieb (Canon) on Aug 23, 2016 at 17:25 UTC

    Here's an example. You assign a reference to your own subroutine to the CORE::GLOBAL namespace for the function in question within a BEGIN block. In this case, the custom open() will only accept the 3-arg form of open.

    use warnings; use strict; BEGIN { *CORE::GLOBAL::open = sub (*;$@) { print "in my open...\n"; # the following line calls the built-in open() function # directly with the params your sub received CORE::open($_[0], $_[1], $_[2]); } }; open my $fh, '<', 'blah' or die $!; print <$fh>;

    Output:

    in my open... file contents
      This is exactly what I was looking for!