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

Hi,

Is it possible to override exec globally, from a required package?

Perldoc example

does seem to indicate global override is possible, but this test case did not work:

execover.pl:
package execOverride;
BEGIN {
   *CORE::GLOBAL::exec = sub {
      my $cmd = shift;
      print "Called exec override\n";
      CORE::exec($cmd);
   };
}
1;

main.pl:
require execover.pl
exec(<something to exec>);

It works fine if the override is in the same file as the exec() call.

Short background:

Semantics for invoking a DCL shell script changed between original OpenVMS perl and HP's currently distributed perl build. Old requires "$@file.com", new requires "@file.com". I have a number of programs that have to work under both perls, and was hoping to make the necessary adjustments to the calls in an exec overload.

It would be painful to add the overload manually to each program needing it (and its something that may be forgotten).

- Tracy

Replies are listed 'Best First'.
Re: Overriding exec globally
by almut (Canon) on Mar 22, 2010 at 21:05 UTC

    When you use require, the code will execute too late.  The BEGIN {} within the module doesn't achieve the desired result, because it won't be seen before the require loads the file at runtime, at which time the exec statement has already been compiled.

    Just make a proper .pm module of it and use it in the main script (which implies BEGIN {}):

    package execOverride; # execOverride.pm *CORE::GLOBAL::exec = sub { my $cmd = shift; print "Called exec override\n"; CORE::exec($cmd); }; 1; # main script #!/usr/bin/perl use execOverride; exec("/bin/echo foo"); __END__ $ ./830161.pl Called exec override foo

    (btw, the package statement isn't really needed here, but it doesn't do any harm either)

Re: Overriding exec globally
by Anonymous Monk on Mar 23, 2011 at 20:06 UTC
    I have benefitted from what's here, and applied it to my situation (i.e. perldb in emacs) by: (perldb "perl -I<path-to-override.pm> -Moverride <other-args>) Perl's -M command line arg makes sure you override module is 'use'd in any perl pgm that you run via perldb this way, without having to add 'use' statements to existing code.
Re: Overriding exec globally
by delson (Initiate) on Mar 23, 2011 at 20:10 UTC
    I have benefitted from what's here, and applied it to my situation (i.e. perldb in emacs) by: (perldb "perl -I<path-to-override.pm> -Moverride <other-args>) Perl's -M command line arg makes sure you override module is 'use'd in any perl pgm that you run via perldb this way, without having to add 'use' statements to existing code.