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

I'm asking as a point of learning here. I have a simple module that takes a key/value pair, stores it, then lets the user access it. Basically, a hash but as a module. Why? Just so I can try different things out.

The question is about naming methods in the module the same as Perl's built-in functions. For example, since I am storing key/value pairs I want to know if a key exists. Perl has a built-in function exists() and has to be called on an array or hash, e.g. exists(foo[0])

That name "exists" is the perfect description of what I want to do with this module. So if I write in the module:

sub exists { ... blah ... }
I can call it without issue like this:
use MyPackage; my $obj = MyPackage->new(); $obj->set_value('foo', 'bar'); if($obj->exists('foo')) { print "that key is there\n"; }

It works just fine. So I want to know why I'm able to override the built-in function? Is it because the procedure I'm writing is always called by the object handle? Does that make it NOT the same as the built-in function?

Just trying to understand how it works

Replies are listed 'Best First'.
Re: Override built-in functions?
by LanX (Saint) on Dec 15, 2020 at 12:29 UTC
    > Is it because the procedure I'm writing is always called by the object handle? Does that make it NOT the same as the built-in function?

    Exactly, because the method and the builtin are in different namespaces aka packages.

    The method call -> will look into the "STASH" of MyPackage:: while calls to builtins are resolved in CORE:: (resp. CORE::GLOBAL ) °

    You can actually override (some) builtin functions, but that's not what is happening here.

    EDIT

    °) see https://perldoc.perl.org/perlsub#Overriding-Built-in-Functions for details on real overriding

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      See also CORE for some details on overriding.

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Thank you both for the response and pointing me in interesting directions.