Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: D.4 Other OperatorsAppendix D
Topics We Didn't Mention
Next: D.6 Many, Many Predefined Variables
 

D.5 Many, Many More Functions

Yes, Perl has a lot of functions. We're not going to list them here, because the fastest way to find out about them is to read through the function section of Programming Perl or the perlfunc documentation and look at anything you don't recognize that sounds interesting. Here are a few of the more interesting ones.

D.5.1 grep and map

The grep function selects elements from its argument list, based upon the result of an expression that's repeatedly evaluated for its truth value, with the $_ variable successively set to each element in the list. For example:

@bigpowers = grep $_ > 6, 1, 2, 4, 8, 16; # gets (8, 16)
@b_names = grep /^b/, qw(fred barney betty wilma);
@textfiles = grep -T, <*>;

The map operator is similar, but instead of selecting or rejecting items, it merely collects the results of the expression (evaluated in a list context):

@more = map $_ + 3, 3, 5, 7; # gets 6, 8, 10
@squares = map $_ * $_, 1..10; # first 10 squares
@that = map "$_\n", @this; # like "unchop"
@triangle = map 1..$_, 1..5; # 1,1,2,1,2,3,1,2,3,4,1,2,3,4,5
%sizes = map { $_, -s } <*>; # hash of files and sizes

D.5.2 The eval Operator (and s///e)

Yes, you can construct a piece of code at runtime and then eval it. This process forces a dynamic compilation of the code inside the eval. This compilation is actually rather useful, because you can get some compile-time optimizations (like a compiled regular expression) at runtime. You can also use it to trap otherwise fatal errors in a section of code: a fatal error inside the eval merely exits the eval and gives you an error status.

For example, here's a program that reads a line of Perl code from the user and then executes it as if it were part of the Perl program:

print "code line: ";
chop($code = <STDIN>);
eval $code; die "eval: $@" if $@;

You can put Perl code inside the replacement string of a substitute operator with the e flag. This is handy if you want to construct something complicated for the replacement string, such as calling a subroutine that returns the results of a database lookup. Here's a loop that increments the value of the first column of a series of lines:

while (<>) {
  s/^(\S+)/$1+1/e; # $1+1 is Perl code, not a string
  print;
}

Another use of eval is as an error-trapping mechanism:

eval {
  &some_hairy_routine_that_might_die(@args);
};
if ($@) {
  print "oops... some_hairy died with $@";
}

Here, $@ will be empty as long as the eval block worked; otherwise, it will have the text of the die message.


Previous: D.4 Other OperatorsLearning Perl on Win32 SystemsNext: D.6 Many, Many Predefined Variables
D.4 Other OperatorsBook IndexD.6 Many, Many Predefined Variables