You can use the eval() function to trap a normally fatal error, eval.pl:
eval { alarm(15) }; warn() if $@; eval { print("The print function worked.\n"); }; warn() if $@;
This program displays the following:
The Unsupported function alarm function is unimplemented at test.pl line 2. ...caught at test.pl line 3. The print function worked.
The $@ special variable holds the error message, if any, returned by the execution of the expression passed to the eval() function.
If the expression is evaluated correctly, then $@ is an empty string. You probably remember that an empty string is evaluated as false when used as a conditional expression.
In an die() sectionearlier the following code snippet was used:
$code = "chdir('/user/printer')"; eval($code) or die("PROBLEM WITH LINE: $code\n$! , stopped");
This program shows that eval() will execute a line of code that is inside a variable. You can use this capability in many different ways besides simply trapping fatal errors. The program listing below presents a prompt and executes Perl code as you type it. Another way of looking at this program is that it is an interactive Perl interpreter:
The Perl code is, eval2.pl:
do { print("> "); chop($_ = <>); eval($_); warn() if $@; } while ($_ ne "exit");
When you run this program, you will see a > prompt. At the prompt, you can type in any Perl code. When you press Enter, the line is executed. You can even define functions you can use later in the interactive session. The program can be stopped by typing exit at the command line.
If you like powerful command-line environments, you can build on this small program to create a personalized system. For example, you might need to perform a backup operation before leaving work. Instead of creating a batch file (under DOS) or a shell file (under UNIX), you can add a new command to the Perl interactive program, as below:
The Perl for this is, eval3.pl:
sub backItUp { '\backup /user/*'; 'delete /user/*.bak' } sub help { print("do#backup will perform the nightly backup\n"); print("help will display this message.\n\n"); } do { print("> "); chop($_ = <>); if (/^do#/) { backItUp)() if /backup/; } elsif (/^\s*help/) { help(); } else { eval($_); warn() if $@; } } while ($_ ne "exit");
This program invokes the backup program and deletes the backup files if you enter do#backup at the > prompt. Of course, you need to modify this program to perform the customized commands you'd like to have. This technique also enables you to centralize your administrative tasks, which will make them easier to document and maintain.
N ote If you are running Perl on a DOS or Windows machine, consider replacing your small batch utility programs with one Perl interpreter and some customized commands. This saves on hard disk space if you use a lot of batch files because each file may take up to 4,096 bytes, regardless of its actual size.