Broad Network


Perl Eval Function

Perl eval Function and Error Checking – Part 1

Perl Course

Foreword: In this part of the series, I explain the use and operation of the Perl eval function.

By: Chrysanthus Date Published: 23 Nov 2015

Introduction

This is part 1 of my series, Perl eval Function and Error Checking. In this part of the series, I explain the use and operation of the Perl eval function.

Pre-Knowledge
This series is part of the volume, Perl Course. At the bottom of this page, you will find links to the different series you should have studied before coming here.

eval Function Syntax
eval means evaluate. The syntaxes for the eval function are:

    eval EXPR

    eval BLOCK;

    eval

In the first case, the argument is an expression. In the second case, the argument is a block, within curly brackets. In the third case the argument is the value of the special variable, $_.

The eval function is a special predefined function in Perl. You do not call it with conventional arguments. That is, it does not have a @_ array (with its $_[index] scalars).

Whether you are dealing with the first or second syntax, the argument to the eval function is a Perl program (small program). For the first syntax, the expression can be simple or complex. It can be made up of statements, in which case, you place the statements, separated by semicolons, all within a string.

Note: when a Perl program is evaluated, there is some minimal compilation before interpretation. The compilation phase is when syntax errors (wrongly typed statements) are checked. The interpretation phase is when the program does its job for which it was written.

For the first syntax, eval function operates at runtime, which means EXP can be input from the user (console). For the second syntax, it is the compiled BLOCK that evaluates, which means, BLOCK as a whole, cannot come from the user (console).  Runtime is when the program is running, receiving inputs and printing outputs.

For both syntaxes, the value of the last expression (statement) is returned. If you do not want that, then use a return statement for any of the syntaxes. You can place the first or second syntax inside a user-defined function (body).

For the rest of this tutorial, I illustrate the operation and use of the two syntaxes. The third syntax is almost like the first.

eval EXPR
For this syntax, EXPR can be simple or complex. If it is made up of more than one statement, separate with semicolons, then place all in quotes. Try the following code:

use strict;

    my $x = 2;

    my $ret = eval $x;

    print $ret, "\n";

    my $ret2 = eval "$x * 10";   #multiply the value of $x by 10

    print $ret2, "\n";

    my $ret3 = eval '$x * 10';  

    print $ret3;

The output is:

2
20
20

For the first eval function, no quotes have been used to delimit the argument.

Now, whether you use single quotes or double quotes, with the eval function, there is expansion of variables (replaced by value). The above code shows that the expression can be delimited by quotes. In the following example, you really must use quotes, since there are more than one statement:

use strict;

    my $y=5;
    my $ret = eval "print 'yes\n'; return $y if $y ==5";  

    print $ret;

The output is:

yes
5

There are two statements in the eval function: The first one actually prints, “yes” while the function is evaluating. The second one returns the value of 5 to $ret, which is printed by the last statement in the complete program. Note that within double quotes of the eval function, an escape sequence in single quotes is interpolated.

You do not always have to code the eval function such that it returns a value. Try the following code:

use strict;

    eval "print 'yes'; print ' no'";

The output is:

yes no

Both the first and the second syntaxes can be placed inside a function body. Try the following code:

use strict;

    sub fn
        {
            my $ret = eval 2*3;
            print $ret;
        }

    fn();

The output is:

6

Input from the user, can be used directly as all the argument for the first syntax. Try the following code for the console. I will explain the code in a different series. When the program ask for input, type,

    print 'yes'; print ' no'

and press the Enter Key.

use strict;

    print "Type in Code: ";

    my $input = <STDIN>;

    eval $input;

The output is:

yes no

I will explain this code in a different series. However, know that the first syntax, “eval EXPR”, operates at run time and not at compile time. So it can actually execute a code at run time, as just illustrated.

eval BLOCK;
I now talk about the second syntax. Before I continue, know that this syntax has a semicolon after the closing curly brackets. The argument for this syntax is mainly a program (mini-Perl program). The first syntax can take a program, but should typically take an expression. For the second syntax, you type all the statements in the block. It is compiled, so you cannot really send it a code argument at runtime. That is, the block cannot really be an entire argument at runtime. Try the following code:

use strict;

    my $y;

    my $var = eval
        {
            my $x = 5;
            $y = 3;
            my $z = $x + $y;
            return $z;
        };

    print $var;

The output is:

8

An eval function must not necessarily return a value. Try the following code:

use strict;

    eval
        {
            print "I like beautiful women.\n";
            print "Every man likes beautiful women.\n";
            print "Are you sure?";
        };

All the strings to be printed should have been displayed, each on its own line.

The second syntax, “eval BLOCK”, as well as the first, can be used inside a function body. Try the following code:

use strict;

    sub fn
        {
            my $ret = eval
                {
                    my $z = 2 * 5;
                    return $z;
                };
            return $ret;
        }

    my $var = fn();
    print $var;

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message