Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Tie subroutine to a built-in function call?

by bcarroll (Pilgrim)
on Aug 23, 2016 at 16:57 UTC ( [id://1170239]=perlquestion: print w/replies, xml ) Need Help??

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?

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1170239]
Approved by Perlbotics
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-29 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found