Section 10.2.  Inserting Code with eval

Table of Contents

10.2. Inserting Code with eval

The Skipper can save disk space (and brain space) by bringing the definition for turn_toward_heading out into a separate file. For example, suppose the Skipper figures out a half-dozen common subroutines related to navigating the Minnow that he seems to use in most or all of the programs he's writing for the task. He can put them in a separate file called navigation.pm, which consists only of the needed subroutines.

But now, how can we tell Perl to pull in that program snippet from another file? We could do it the hard way, using the string form of eval that we discussed in Chapter 2.

sub load_common_subroutines {
  open MORE_CODE, 'navigation.pm' or die "navigation.pm: $!";
  undef $/; # enable slurp mode
  my $more_code = <MORE_CODE>;
  close MORE_CODE;
  eval $more_code;
  die $@ if $@;

Perl reads the code from navigation.pm into the $more_code variable. We then use eval to process that text as Perl code. Any lexical variables in $more_code remain local to the evaluated code.[*] If there's a syntax error, Perl sets the $@ variable and causes the subroutine to die with the appropriate error message.

[*] Oddly, the variable $more_code is also visible to the evaluated code, not that it is of any use to change that variable during the eval.

Now, instead of a few dozen lines of common subroutines to place in each file, we simply have one subroutine to insert in each file.

But that's not very nice, especially if we need to keep doing this kind of task repeatedly. Luckily, Perl has several ways to help us out.

Table of Contents
© 2000- NIV