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

Hi all! I'm using 2 perl scripts, "main.pl" that includes a script "extras.pl" (with extra functions in it)I want to do the following: If a sub exists in both scripts (i.e. "Sub1()" exists in both scripts), Sub1() in extras.pl should be used, otherwise the function in main.pl should be used. In other words, the subs in extras.pl should "override" the ones in main.pl I've done this in other object oriented languages ("overloading"), but in this case I can't use the OO capabilities...

Replies are listed 'Best First'.
Re: "Overriding" functions?
by almut (Canon) on Jul 04, 2007 at 15:42 UTC
    #!/usr/bin/perl use strict; use warnings; require "extras.pl"; # (with extras.pl containing:) # sub sub1 { # print "sub1() from extras\n"; # } # 1; sub sub1 { print "sub1() from main\n"; } sub1(); # prints "sub1() from extras"

    but what do you mean "I can't use the OO capabilities..."?

      Under -w, this gives a redefinition warning. extras.pl should have
      use warnings; no warnings "redefine";
      (or muck about with $^W for the hardcore anti-warnings.pm people).
        use warnings; no warnings "redefine";

        Just to be on the safe side,

        { no warnings "redefine"; sub that_must_be_redefined { ... } }

        If wanting to be very very picky...

        { my $redefined = sub { ... } no warnings "redefine"; *that_must_be_redefined = $redefined; }

      By "I can't use the OO capabilities..." I suppose OP meant that s?he cannot use OO style to provide for namespace[0] or polymorphism such that the desired method|function could be called.

      Addendum. [0]A namespace can also be provided for by a non-OO module which does not export the sub in question by default.