Difference between revisions of "Perl eval"
From Teknologisk videncenter
m (New page: Perl eval can be used as a '''try''' and '''catch''' error recovery procedure <source lang="perl"> eval { # try }; if($@) { # catch } </source> Category:Perl) |
m (→Example) |
||
(2 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | Perl eval can be used as | + | Perl eval can be used as '''try''' and '''catch''' exception handling. |
<source lang="perl"> | <source lang="perl"> | ||
eval | eval | ||
Line 10: | Line 10: | ||
} | } | ||
</source> | </source> | ||
+ | = Throwing an exception = | ||
[[Category:Perl]] | [[Category:Perl]] | ||
+ | <source lang="perl"> | ||
+ | eval | ||
+ | { | ||
+ | # try | ||
+ | die "Exception text to be catched"; | ||
+ | }; | ||
+ | if($@) | ||
+ | { | ||
+ | # catch | ||
+ | } | ||
+ | </source> | ||
+ | =Example= | ||
+ | <source lang=perl> | ||
+ | #!/usr/bin/perl | ||
+ | |||
+ | eval | ||
+ | { | ||
+ | my $res = 1/0; | ||
+ | }; | ||
+ | if($@) | ||
+ | { | ||
+ | print("Help - I'm dying\n"); | ||
+ | print(" Perl Script.: $0\n"); | ||
+ | print(" Perl verson.: $]\n"); | ||
+ | print(" Error #.....: ",$@,"\n"); | ||
+ | exit; | ||
+ | } | ||
+ | </source> | ||
+ | Yields | ||
+ | <pre> | ||
+ | |||
+ | Help - I'm dying | ||
+ | Perl Script.: C:\Programmer\Perl Express\Debug\temp6.cgi | ||
+ | Perl verson.: 5.010001 | ||
+ | Error #.....: Illegal division by zero at C:\Programmer\Perl Express\Debug\temp6.cgi line 5. | ||
+ | </pre> |
Latest revision as of 12:40, 27 June 2010
Perl eval can be used as try and catch exception handling.
eval
{
# try
};
if($@)
{
# catch
}
Throwing an exception
eval
{
# try
die "Exception text to be catched";
};
if($@)
{
# catch
}
Example
#!/usr/bin/perl
eval
{
my $res = 1/0;
};
if($@)
{
print("Help - I'm dying\n");
print(" Perl Script.: $0\n");
print(" Perl verson.: $]\n");
print(" Error #.....: ",$@,"\n");
exit;
}
Yields
Help - I'm dying Perl Script.: C:\Programmer\Perl Express\Debug\temp6.cgi Perl verson.: 5.010001 Error #.....: Illegal division by zero at C:\Programmer\Perl Express\Debug\temp6.cgi line 5.