package TestTry;
use strict;
use warnings;
print "TestTry: module load\n";
sub life {
my $n = shift;
defined($n) or die "error: no argument provided";
print "TestTry::life n='$n'\n";
$n =~ /^\d+$/ or die "input error: '$n' must consist of digits only";
$n == 42 or die "Sadly there is no meaning in your life (n=$n)";
print "TestTry: congrats, your life has meaning!\n";
print "TestTry::life end\n";
}
1;
####
# trytest.pl - a simple test of new perl 5.38 try syntax:
# Put TestTry.pm in same dir as trytest.pl and run with:
# perl -I . trytest.pl
# Note: use v5.38 implies use strict and warnings
use v5.38;
# use feature 'try'; # throws 'try/catch is experimental' warnings (update: works with perl v5.40.0 if you are not using finally blocks)
use experimental 'try';
use TestTry;
sub do_one {
my $number = shift;
try {
TestTry::life($number);
}
catch ($e) {
chomp $e;
print "trytest: caught '$e'\n";
}
finally {
print "trytest: in finally block\n";
}
}
print "trytest: start\n";
do_one("invalid");
do_one(13);
do_one(42);
print "trytest: end\n";
##
##
$ perl -I . trytest.pl
TestTry: module load
trytest: start
TestTry::life n='invalid'
trytest: caught 'input error: 'invalid' must consist of digits only at TestTry.pm line 11.'
trytest: in finally block
TestTry::life n='13'
trytest: caught 'Sadly there is no meaning in your life (n=13) at TestTry.pm line 12.'
trytest: in finally block
TestTry::life n='42'
TestTry: congrats, your life has meaning!
TestTry::life end
trytest: in finally block
trytest: end