use strict;
use warnings;
package DieWithCode;
BEGIN {
our @EXPORT = 'die_with_code';
require Exporter;
*import = \&Exporter::import;
}
use Carp qw( carp croak );
sub die_with_code {
my $code = shift(@_);
if ($^S) {
croak(@_);
} else {
carp(@_);
exit($code);
}
}
1;
####
use strict;
use warnings;
use DieWithCode qw( die_with_code );
$|=1;
eval { die_with_code(4, "Foo"); };
print "Caught: $@" if $@;
eval { die_with_code(5, "Bar\n"); };
print "Caught: $@" if $@;
s/\\n/\n/g for @ARGV;
die_with_code(@ARGV);
####
>perl 587042.pl 6 "Baz"
Caught: Foo at 587042.pl line 9
Caught: Bar
Baz at 587042.pl line 16
>echo %ERRORLEVEL%
6
>perl 587042.pl 7 "Boo\n"
Caught: Foo at 587042.pl line 9
Caught: Bar
Boo
>echo %ERRORLEVEL%
7