DekGenius.com
[ Team LiB ] Previous Section Next Section

2.2 Inserting Code with eval

The Skipper can save disk space (and brainspace) by bringing the definition for turn_towards_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.pl, which consists only of the needed subroutines.

But now, how can you tell Perl to pull in that program snippet from another file? You could do it the hard way:

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

The code from navigation.pl is read into the $more_code variable. You then use eval to process that text as Perl code. Any lexical variables in $more_code will remain local to the evaluated code.[1] If there's a syntax error, the $@ variable is set and causes the subroutine to die with the appropriate error message.

[1] 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, you simply have one subroutine to insert in each file.

But that's not very nice, especially if you need to keep doing this kind of task repeatedly. Luckily, there's (at least) one Perl built-in to help you out.

    [ Team LiB ] Previous Section Next Section