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

Hello!
Could you guys show me an example of how to wrap a built-in function? push would be great , if it's not too much trouble. Thanks

Replies are listed 'Best First'.
Re: Hook::LexWrap and core functions
by ikegami (Patriarch) on Sep 19, 2008 at 22:36 UTC
    Overriding Built-in Functions

    First make sure you can override it

    >perl -wle"print( prototype( 'CORE::chomp' ) )" Use of uninitialized value in print at -e line 1. <- Can't >perl -wle"print( prototype( 'CORE::push' ) )" \@@ <- Can

    Then go ahead and do it:

    BEGIN { *CORE::GLOBAL::push = sub(\@@) { my $array = shift(@_); print("Pushing\n"); return CORE::push(@$array, @_); }; }
      Thank you for your reply ! But,is it possible to wrap it using Hook::LexWrap ? I get a "Can't wrap non-existent subroutine CORE::push"

        Nope, and the error accurately describes the reason you can't. push is not a sub, so you can't get its address, so it can't be wrapped.

        You might be able to wrap *CORE::GLOBAL::push once you create it.

      Now that I think of it, prototypes are already somewhat deprecated, and of course we're "all" (well, I for one, and I bet most too, but I'm sure someone will disagree instead...) waiting for Perl 6 and its multi's with real signatures, OTOH it would be nice and IMHO not terribly sci-fi-like if prototypes allowed alternation (which I sort of consistently, I hope, represent hereafter with a pipe | character) so that e.g. chomp could have a prototype of:

      @|_
      --
      If you can't understand the incipit, then please check the IPB Campaign.