Perl eval

From Teknologisk videncenter
Jump to: navigation, search

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.