NAME
Error::Return - return(), skipping a scope
SYNOPSIS
use Error ':try';
use Error::Return;
sub doit {
print " in doit, before try\n";
try {
print " in try: start\n";
RETURN 456;
print " in try: end\n";
} catch Error with {
my $E = shift;
print " caught error [$E]\n";
};
print " in doit, after try\n";
}
print "before doit\n";
my $x = doit();
print "doit() returned [$x]\n";
print "after doit\n";
# prints:
#
# before doit
# in doit, before try
# in try: start
# doit() returned [456]
# after doit
DESCRIPTION
The Error module provides try()
, which takes a coderef using the &
prototype so it looks more like a normal Perl block or like map()
or grep()
. But the "block" is still just an anonymous subroutine, so using return
within the sub won't do what you think it will do. For example:
sub doit {
print " in doit, before try\n";
try {
print " in try: start\n";
return 456;
print " in try: end\n";
} catch Error with {
my $E = shift;
print " caught error [$E]\n";
};
print " in doit, after try\n";
}
print "before doit\n";
my $x = doit();
print "doit() returned [$x]\n";
print "after doit\n";
The return
in the try
block (we call it a block, but it really isn't) looks like it should return from doit()
, but it doesn't - it just returns from the anonymous sub that was passed to try()
. Therefore, this program prints the following:
before doit
in doit, before try
in try: start
in doit, after try
doit() returned [1]
after doit
So in doit, after try
is still reached, and doit()
returns 1
because of its last print
statement.
While that is the correct behaviour, it is unintuitive. This module provides a more powerful way of returning.
METHODS
RETURN
-
Like
return
except that it doesn't just return to its upper scope but smashes right through it to the next-higher scope. Actually, it skips two scopes, because it has to return from thetry()
subroutine as well. It does take care of the cleanup thattry()
would normally perform.See the Synopsis as an example - this way, the
try
block will "do what you mean".
BUGS AND LIMITATIONS
No bugs have been reported.
Please report any bugs or feature requests through the web interface at http://rt.cpan.org.
INSTALLATION
See perlmodinstall for information and options on installing Perl modules.
AVAILABILITY
The latest version of this module is available from the Comprehensive Perl Archive Network (CPAN). Visit http://www.perl.com/CPAN/ to find a CPAN site near you. Or see http://search.cpan.org/dist/Error-Return/.
The development version lives at http://github.com/hanekomu//. Instead of sending patches, please fork this project using the standard git and github infrastructure.
AUTHORS
Marcel Grünauer, <marcel@cpan.org>
COPYRIGHT AND LICENSE
Copyright 2009 by Marcel Grünauer
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.