O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

D.5. Many, Many More Functions

Yes, Perl has a lot of functions. I'm 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 (1) manpage 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:

@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 function 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 "unchomp"
@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 run-time and then eval it, just as you can do with the shell. It's actually rather useful, because you can get some compiletime optimizations (like a compiled regular expression) at run-time. You can also use it to trap otherwise fatal errors in a section of code: a fatal error inside the eval merely ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required