Monday 10 November 2014

Perl: the Eval Function

Excerpts from Perl Eval Function Examples – Regex, Error Handling, Require, Timeout, Dynamic Code

Regular Expressions Handling with Eval
$line = <>;
%hash = ( number => qr/^[0-9]+$/,
                 alphabets => qr/^[a-zA-Z]+$/
);

while( my ($key,$value) = each(%hash) )
{
    if(eval "$line =~ /$value/") { print "$key\n"; }
}

Trapping Errors

During the execution of the subroutine the program might die because of errors, or external calling of die function. During this time, if the block of perl code is executed inside the eval, then program continues to run even after the die or errors, and it also captures the errors or dieing words.

Zero Divide Error:
eval { $average = $total / $count }; print “Error captured : $@\n”;











No comments:

Post a Comment