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

I want to create a function that will use the POSIX WEXITSTATUS function if it is defined, otherwise use a default function.
What I've come up with is this:
package Pexitstat; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(exitstatus); our $WEXITSTATUS = sub { $_[0] >> 8 }; sub exitstatus { &$WEXITSTATUS($_[0]); } if (eval "use POSIX; 1") { local $! = 0; my $EAGAIN = POSIX::constant("EAGAIN", 0); my $val = POSIX::constant("WEXITSTATUS", 0); if ($! == $EAGAIN) { $WEXITSTATUS = sub { POSIX::constant("WEXITSTATUS", $_[0]) }; } } 1;
I also tried the slightly shorter:
package Pexitstat; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(exitstatus); sub exitstatus { $_[0] >> 8; } if (eval "use POSIX; 1") { local $! = 0; my $EAGAIN = POSIX::constant("EAGAIN", 0); my $val = POSIX::constant("WEXITSTATUS", 0); if ($! == $EAGAIN) { *exitstatus = sub { POSIX::constant("WEXITSTATUS", $_[0]) }; } } 1;

which works, but gives the warning "Subroutine exitstatus redefined at Pexitstat.pm line 14."

Is there a better way to accomplish this?

Replies are listed 'Best First'.
Re: Conditional function replacement
by shotgunefx (Parson) on Apr 16, 2002 at 19:40 UTC
    undef &existstatus before the reassignment will silence the redefined warnings.

    -Lee

    "To be civilized is to deny one's nature."
      Thanks, that's just what I needed.
Re: Conditional function replacement
by Thelonius (Priest) on Apr 16, 2002 at 19:43 UTC
    I've come up with a third variant, which I like, but still wondering if anybody knows of any drawbacks with this or a better way:
    package Pexitstat; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(exitstatus); my $EAGAIN; if (eval "use POSIX; 1" && ($EAGAIN = POSIX::constant("EAGAIN", 0)) && defined(POSIX::constant("WEXITSTATUS", 0)) && $! == $EAGAIN) { *exitstatus = sub { POSIX::constant("WEXITSTATUS", $_[0]) }; } else { *exitstatus = sub { $_[0] >> 8} } 1;