ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. Special Variables 4. Subroutines 5. Regexp
6. Ties & DBM 7. Functions 8. Eval 9. Larger Example 10. Exercises  

eval Function

 

 
   
 
     
Block Form - Error Trapping
 

The block form of eval is just used for error trapping. Usage is eval { code }; where code is perl code (not a perl string) that can be compiled when the overall program is compiled.

The key point is that any fatal errors inside code, particularly calling the die function, will not cause your program to crash. Instead, the eval will exit, and the $@ variable will be set to an error message.

    eval { $a/$b };
    print "division failed:$@\n" if $@;
    eval { some_subroutine(); };
    print "some_subroutine failed: $@" if $@;
 
     
String Form - Code Evaluation on the Fly
 

The string form of eval allows you to construct perl code on the fly, store it in a string, and execute that code in the context of the current perl program, with access to all appropriate variables.

This was more commonly used before references, but not used as often now. You can set variables whose name you don't know until runtime with soft references. You can use references and typeglobs to define subroutines at runtime. But if you really have to execute arbitrary code at runtime, you still need eval. Here is a perl interpreter that you run one line at a time:

    while ( defined($line=<STDIN>) ) {
	print eval($line), "\n";
    }
 
 

Perl II Previous: 7. Functions Next: 9. Larger Example


1999-4-4  BobG
UIC Home Page Search UIC Pages Contact UIC