ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
D.5 Many, Many More FunctionsYes, 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 mapThe @bigpowers = grep $_ > 6, 1, 2, 4, 8, 16; # gets (8, 16) @b_names = grep /^b/, qw(fred barney betty wilma); @textfiles = grep -T, <*>; The @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 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 while (<>) { s/^(\S+)/$1+1/e; # $1+1 is Perl code, not a string print; } Another use of eval { some_hairy_routine_that_might_die(@args); }; if ($@) { print "oops... some_hairy died with $@"; } Here, Of these three constructs ( |