}

In this simple example, the variable $a is repeatedly manipulated and tested in an endless loop. The word 'start' is printed only once.

do ... while and do ... until

The while and until loops evaluate the conditional first. You change the behavior by applying a do block before the conditional. With the do block, the condition is evaluated last, which results in the contents of the block always executing at least once (even if the condition is false). This is similar to the C language do ... while (conditional) statement.

Regular Expressions

Perl's greatest strength is in text and file manipulation, which it accomplishes by using the regular expression (regex) library. Regexes, which are quite different from the wildcard handling and filename expansion capabilities of the shell, allow complicated pattern matching and replacement to be done efficiently and easily. For example, the following line of code replaces every occurrence of the string bob or the string mary with fred in a line of text:

$string =~ s/bob|mary/fred/gi;

Without going into too many of the details, Table 25.7 explains what the preceding line says.

TABLE 25.7 Explanation of $string =~ s/bob|mary/fred/gi;

Element Explanation
$string =~ Performs this pattern match on the text found in the variable called $string.
s Substitutes one text string for another.
/ Begins the text to be matched.
bob|mary Matches the text bob or mary. You should remember that it is looking for the text mary, not the word mary; that is, it will also match the text mary in the word maryland.
/ Ends text to be matched; begins text to replace it.
fred Replaces anything that was matched with the text fred.
/ Ends replace text.
g Does this substitution globally; that is, replaces the match text wherever in the string you match it (and any number of times).
i Make the search text case insensitive. It matches bob, Bob, or bOB.
; Indicates the end of the line of code

If you are interested in the details, you can get more information from the regex (7) section of the manual.

Although replacing one string with another might seem a rather trivial task, the code required to do the same thing in another language (for example, C) is rather daunting unless supported by additional subroutines from external libraries.

Access to the Shell

Perl can perform any process you might ordinarily perform if you type commands to the shell through the `` syntax. For example, the code in Listing 25.4 prints a directory listing.

LISTING 25.4 Using Backticks to Access the Shell

$curr_dir = `pwd`;

@listing = `ls -al`;

print 'Listing for $curr_dir ';

foreach $file (@listing) {

 print '$file';

}

Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату