11

I'm writing code that runs all sorts of external commands as well as various filesystem commands that can fail.

Is there any module that can save me the trouble of adding or die to anything that can fail?

I'd like to be able to wrap the following in something so that instead of:

mkdir $dirname or die "can't create directory $dirname"; system("some external command") or die "can run some external command"; 

I get:

some_wrapper_code { mkdir $dirname; system("some external command"); } 

such that if mkdir fails it'll tell me that the failure was in mkdir, and if system fails it'll tell me that the failure was in system.

1 Answer 1

32

Yep. Check out autodie from CPAN.

From the docs:

The autodie pragma provides a convenient way to replace functions that normally return
false on failure with equivalents that throw an exception on failure.

The autodie pragma has lexical scope, meaning that functions and subroutines altered with autodie will only change their behaviour until the end of the enclosing block, file, or eval.

Sign up to request clarification or add additional context in comments.

1 Comment

And starting with Perl 5.10.1, autodie is included in the core. perldoc.perl.org/perl5101delta.html#New-Modules-and-Pragmata

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.