On Tuesday 15 Dec 2009 09:50:27 Xiao Lan (小兰) wrote:
> Hello,
>
> It seems in ruby and python we have a good exception capturing way.
> The ruby's:
>
> irb(main):042:0> begin
> irb(main):043:1* x=12/0
> irb(main):044:1> rescue
> irb(main):045:1> puts "0 div error"
> irb(main):046:1> end
> 0 div error
>
> The python's:
> >>> try:
>
> ... x=12/0
> ... except:
> ... print "0 div error"
> ...
> 0 div error
>
>
>
> But in Perl I have to use an eval:
>
> # perl -e '
> eval "$x=12/0";
> if ($@) { print "0 div error" }'
> 0 div error
>
>
>
> So what's the equivalent of perl's exception handling like python/ruby?
You can use block eval {} instead of string eval "":
<<<<<<<<<<<<<<<<
#!/usr/bin/perl
use strict;
use warnings;
my $x;
eval
{
$x=12/0;
};
if ($@)
{
print "0 div error\n";
}
>>>>>>>>>>>>>>>>
One problem with that is that Perl 5's exception handling is not inherently
object-oriented. If you'd like that (and you likely would), look at the
following CPAN modules:
* http://search.cpan.org/dist/Exception-Class/
* http://search.cpan.org/dist/TryCatch/ (never used it though).
* http://search.cpan.org/dist/Try-Tiny/ (likewise).
There's also http://search.cpan.org/dist/Error/ , which I've used, and have
been co-maintaining, but cannot really recommend because it is Black Magick
and quirky.
Regards,
Shlomi Fish
>
> Thanks in advance.
>
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Stop Using MSIE - http://www.shlomifish.org/no-ie/
Bzr is slower than Subversion in combination with Sourceforge.
( By: http://dazjorz.com/ )
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/