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

I'm writing a low-level wrapper for backticks so that shelling out to run a command doesn't hang or kill my daemon. I'd like to be able to drop it in wherever I am using backticks without having to make any changes (beyond replacing the backticks with a subroutine call). By low-level I mean that I would prefer to have to do as little as possible within the wrapper -- e.g. as little error handling as possible (so even $@ would be handled outside of the wrapper). Does the code below fit the bill? And more importantly, is there a way to make it look prettier (e.g. reduce duplicate code)?

sub cmd_wrapper { my $cmd = shift; # CASE: Called in list context if( wantarray() ) { my @out; eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 15; # Give the command 15 seconds to return @out = `$cmd`; alarm 0; }; return @out; } # CASE: Called in scalar context else { my $out; eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 15; # Give the command 15 seconds to return $out = `$cmd`; alarm 0; }; return $out; } }

Elda Taluta; Sarks Sark; Ark Arks

Replies are listed 'Best First'.
Re: Is there a way to clean up this backticks wrapper?
by BrowserUk (Patriarch) on Feb 16, 2010 at 00:05 UTC

    sub cmd_wrapper { my $cmd = shift; my @out; eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 15; # Give the command 15 seconds to return @out = `$cmd`; alarm 0; }; return wantarray ? @out : join '', @out; }

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Duh!! I was wracking my brain for fancy tricks, not something simple like join! I knew I was too close to the problem. Thanks!!

      Elda Taluta; Sarks Sark; Ark Arks