Perl

Perl “Eval” Function Examples

The “eval” function is one of the useful built-in functions of Perl. It is used to evaluate any Perl script. It can handle the compile and run-time errors when evaluating the Perl expression. The user input can also be validated using this function. Perl script with regular expression and file handling tasks can also be evaluated by the “eval” function. The uses of the “eval” function are shown in this tutorial using multiple examples.

Syntax:

The syntax of the “eval” command is given in the following. Any valid Perl script code is executed using this function:

eval  "Perl script"

Different Examples of the “Eval” Function

The uses of the “eval” function to perform arithmetic operations, compare the string data, and search the strings using regular expressions are shown in this part of the tutorial.

Example 1: Use of the “Eval” Function with the Numeric Data

Create a Perl file with the following script that executes an arithmetic expression using the “eval” function. The price and the discount in percentage are taken from the user. The “eval” command is used in the script to calculate the price of the product after deducting the discount amount. The original price and the discount price of the product are displayed in the output.

#!/usr/bin/perl

use strict;
use warnings;

print "Enter the original price of the product: ";
#Take the price value
my $original_price = <>;

print "Enter the discount value in %: ";
#Take the discount value
my $discount = <>;

#Calculate the discount price
my $discount_price = eval "$original_price - ($original_price * ($discount/100))";

#Print the original and discount price
print "The original price of the product is $original_price";
print "The discount price of the product is $discount_price\n";

Output:

The following output appears after executing the previous script:

Example 2: Use of the “Eval” Function with the String Data

Create a Perl file with the following script that validates the user credentials using the “eval” function. The username and password are taken from the user and are compared with the particular value. If the valid username and password are taken, 1 is returned by the “eval” function. Otherwise, 0 is returned. If the invalid username or password is taken, the loop repeats the task.

#!/usr/bin/perl

#Initialize the variable to start the loop
$valid = 0;
while(!$valid)
{

    print "Enter the username: ";
    #Take the username
    $un = <>;
    #Remove newline from the username
    chomp($un);

    print "Enter the password: ";
    #Take the password
    $pw = <>;
    #Remove newline from the password
    chomp($pw);

    #Check the username and password
    $valid = eval $un eq 'admin' && $pw eq 'secret' ?  1 : 0;

    #Check the return value of the `eval` function
    if($valid == 1)
    {
         print "Authenticated user.\n";
    }
    else
    {
         print "Username or password is wrong.\n";
    }

}

Output:

According to the output, the wrong password was taken for the first time and an error message is printed. Then, both valid username and password were taken:

Example 3: Use of the “Eval” Function with the Default Variable

Create a Perl file with the following script that calculates the sum of three input numbers using the “eval” function. A “while” loop is used to take three numbers and add the numbers after removing the newlines.

#!/usr/bin/perl

use strict;
use warnings;

#Initialize variables
my $counter = 0;
my $sum = 0;

while($counter < 3)
{
    print "Enter a number: ";
    #Take the input in the default variable
    $_ = <>;
    #Remove the newline
    chomp($_);
    #Add the input value with the $sum using `eval`
    $sum = eval $_ + $sum;
    #Increment the counter
    $counter++;

}
#Print the summation value
print "The summation value is $sum\n";

Output:

The following output appears after executing the previous script. Here, 7, 5, and 3 are taken as the input values and the sum of these numbers is 15:

Example 4: Use of the “Eval” Function with the Regular Expression

Create a Perl file with the following script where the first “eval” function is used to check whether the input value contains digits or not and the second “eval” command is used to search and replace the particular word using regular expressions.

#!/usr/bin/perl

use strict;
use warnings;

print "Enter the item code:";
#Take two inputs and remove the newlines
my $code = <>;
chomp($code);

#define a pattern for the code value
my $match_pattern = qr/^[0-9]+$/;

#Check whether the pattern matches the code value or not
if(!eval "$code =~ /$match_pattern/")
{
     #Print error message
     print "Invalid code.\n";

}

#Define a string variable
my $str = "PHP programming";
print "Original string is $str\n";

#Search and replace the string
my $r_val = eval $str =~ s/PHP/Perl/;

if($r_val == 1)
{
     print "Replaced string is $str\n";
}
else
{
     print "Nothing is replaced.\n";
}

Output:

The following output appears after executing the previous script if the input value is “abc”:

The following output appears after executing the previous script if the input value is “3490”:

Conclusion

Some basic uses of the “eval” function are used in the examples of this tutorial that will help the Perl users to know the purpose of using the “eval” function.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.