📄 ch3.htm
字号:
<HTML>
<HEAD>
<TITLE>Chapter 3 -- Programming with Perl</TITLE>
<META>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#CE2910">
<H1><FONT SIZE=6 COLOR=#FF0000>Chapter 3</FONT></H1>
<H1><FONT SIZE=6 COLOR=#FF0000>Programming with Perl</FONT></H1>
<HR>
<P>
<CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER>
<UL>
<LI><A HREF="#RegularExpressions">
Regular Expressions</A>
<UL>
<LI><A HREF="#PerlControlStructures">
Perl Control Structures</A>
<LI><A HREF="#AssociativeArrays">
Associative Arrays</A>
<LI><A HREF="#IO">
I/O</A>
<LI><A HREF="#UsingaRegularExpression">
Using a Regular Expression</A>
<LI><A HREF="#TheGuestbook">
The Guestbook</A>
<LI><A HREF="#RegularExpressionsasPatterns">
Regular Expressions as Patterns</A>
<LI><A HREF="#OtherMatchingOperatorTidbits">
Other Matching Operator Tidbits</A>
</UL>
<LI><A HREF="#ChapterinReview">
Chapter in Review</A>
</UL>
</UL>
<HR>
<P>
To program with Perl, we can take variables, assign them values
from within the program or user input, and then manipulate them.
Before we can get right into Perl programming, we have to get
another central concept under our belt: regular expressions, which
are dealt with in detail in this chapter.
<H2><A NAME="RegularExpressions"><FONT SIZE=5 COLOR=#FF0000>
Regular Expressions</FONT></A></H2>
<P>
Regular expressions are a concept from the UNIX world. They are
a like a pattern, or template, which is matched against a string.
Strings are sequences of characters, like "hello" or
"please pass the butter." When a regular expression
tries to make a match, it either succeeds or fails. The regular
expression is not a literal translation of the string, but a representation
of it.
<P>
Think of a regular expression as being like a verbal expression
in slang. When the guys are hanging out and one of them calls
to another, "Yo, Homie! You look fat today!" he is not
referring to a weight problem his friend may be having. "Fat"
is a slang term, and means "looking good" or "your
appearance is exceptional."
<P>
The key to using regular expressions is two-fold. The first thing
you must understand is the pattern you are trying to match. The
second is to understand the different patterns available to you
to make a pattern match.
<P>
Regular expressions are used in many different operating systems,
and by many different programs and processes. If you are already
familiar with regular expressions in another context, then you're
in luck. While the syntax of regular expressions vary between
operating systems, the concepts remain the same.
<P>
Before getting into the nitty-gritty of regular expressions, it
might help if we looked into some related programming issues in
Perl. The issues include control structures, associative arrays,
and data I/O using <STDIN>.
<H3><A NAME="PerlControlStructures">
Perl Control Structures</A></H3>
<P>
It is important to be able to tell the Perl interpreter when you
want things done in your script. To do this you use control structures,
like a statement block, or different kinds of loops.
<H4>The Statement Block</H4>
<P>
The simplest control structure in Perl is the statement block,
which is made up of a series of statements that are enclosed in
curly braces, and might look something like this:
<BLOCKQUOTE>
<PRE>
{
$one = "1";
@two = (1,2,3);
%three = $two[Ø};
}
</PRE>
</BLOCKQUOTE>
<P>
where the statements inside the statement block are indented one
tab past the curly braces.
<P>
When Perl encounters a statement block it executes each statement
consecutively, starting with the first, and working its way to
the last. Perl will treat the entire block as a single statement
in the script as a whole.
<P>
Statement blocks are often used as part of the syntax of statement
loops.
<H4>The If/Unless Statement Loop</H4>
<P>
In an if/unless loop a designated expression is examined for truth,
and if it is true, then one series of events is started. If it
is false, then another path is taken in the script. A simple format
for an if/unless statement loop is
<BLOCKQUOTE>
<PRE>
if (the_expression) {
statement_if_expression_true;
} else {
statement_if_expression_false;
}
</PRE>
</BLOCKQUOTE>
<P>
where Perl will evaluate the _expression, called the control expression,
to see if it is true or false. If it is true then it goes to the
statement in the first block following the if command. If the
control expression is false, Perl goes to the statement following
the else command.
<P>
Applying this we can get a script that asks for some user input,
then evaluates it with different possible outcomes depending on
the input received, like this:
<BLOCKQUOTE>
<PRE>
print "What is the temperature?";
$temp = <STDIN>;
chop ($temp);
if ($temp < 7Ø) {
print "Brrr, you better get a sweater!\n";
} else {
print "Is it hot enough for ya?\n";
}
</PRE>
</BLOCKQUOTE>
<P>
If you want to return a statement only if the result of the expression
test is false, you can use the unless command:
<BLOCKQUOTE>
<PRE>
print "What is the temperature?";$temp = <STDIN>;
chop ($temp);
unless ($temp < 7Ø) {
print "Is it hot enough for ya?\n";
}
</PRE>
</BLOCKQUOTE>
<P>
so that the user will receive the print statement unless their
input is determined to be false.
<P>
Another option in an if/else loop is the elsif command. You may
want to have several choices for the script's execution, so you
include the elsif command to handle the other options, like this:
<BLOCKQUOTE>
<PRE>
print "What is the temperature?";$temp = <STDIN>;
chop ($temp);
if ($temp < 7Ø) {
print "Brrr, you better get a sweater!\n";
} elsif (7Ø < $temp < 8Ø) {
print "A little cool, but comfortable.\n";
} elsif (8Ø < $temp < 9Ø) {
print "Nice and cozy./n";
} else {
print "Is it hot enough for ya?\n";
}
</PRE>
</BLOCKQUOTE>
<P>
where you are not limited in your options with elsif, and can
have as many of these branch control structures as you need.
<H4>The While/Until Loop Statement</H4>
<P>
There may come a time (probably sooner rather than later) where
you'll need to have a block of statements repeatedly read until
a certain condition is met. This is done with the while/until
loop statement.
<P>
A typical use for this loop is to count something down, like:
<BLOCKQUOTE>
<PRE>
print "How high for your countdown?"; # where
# the user sets the upper limit
# of the countdown
$count = <STDIN>;
chop ($count);
while ($count > Ø) {
print "T minus $count, and counting...\n";
$count--;
}
</PRE>
</BLOCKQUOTE>
<P>
where the while loop is executed until the value of $count is
equal to 0. You may have noticed the use of the autodecrement
operator on $temp to lower the value each cycle.
<P>
The while loop also has an option to return a statement if the
condition of the input is false, called the until command. Used
in the same way, until looks like this:
<BLOCKQUOTE>
<PRE>
print "How long for your countdown?";
$count = <STDIN>;
chop ($count);
until ($count > Ø) {
print "Lift off!\n";
$count--;
}
</PRE>
</BLOCKQUOTE>
<P>
The print statement is not executed until the condition of $count
is satisfied.
<P>
Another way to repeat, or iterate, a statement block is with the
for and foreach commands.
<H4>The For/Foreach Loop Statements</H4>
<P>
When you need a script to evaluate an expression and then re-evaluate
it in a countdown fashion, you can use the for command like this:
<BLOCKQUOTE>
<PRE>
for ($count = 15; $count >= 1; $count--) {
print "$count \n";
}
</PRE>
</BLOCKQUOTE>
<P>
The countdown is printed from 15 to 1, with each number appearing
on a new line. $count is given the value 15, tested against the
condition of being >=1, printed, then autodecremented and looped.
When $count = 1, then loop dies after printing the final value
for $count.
<P>
There may be an instance where you need to create a loop with
a variable in which its value will change in the loop, but you
need it restored after the loop dies. You need the variable to
be local to the loop. You can do this with the foreach command.
<P>
With foreach, a list of values is created and then it places them
into a scalar variable one at a time, and then computes that statement
block designated by the foreach command. An example of this might
be:
<BLOCKQUOTE>
<PRE>
@letters = ("A","B","C","D");
foreach $new (reverse @letters){
print $new;
}
</PRE>
</BLOCKQUOTE>
<P>
where the output will be D C B A. A special Perl variable can
be used here to simplify the code. The $_ scalar variable is the
default variable with many commands, like foreach, into which
values can be placed. The same script above would look like this:
<BLOCKQUOTE>
<PRE>
@letters = ("A","B","C","D");
foreach $_ (reverse @letters) {
print $_;
}
</PRE>
</BLOCKQUOTE>
<P>
and this can be shortened even more, because Perl will see the
$_ variable, even if it is left out, like this:
<BLOCKQUOTE>
<PRE>
@letters = ("A","B","C","D");
foreach (reverse @letters) {
print ;
}
</PRE>
</BLOCKQUOTE>
<P>
The foreach statement is also handy if you want to change the
values of an entire array. It works like this:
<BLOCKQUOTE>
<PRE>
@numbers = (2,4,6,8);
foreach $two (@numbers) {
$two *= 2;
}
</PRE>
</BLOCKQUOTE>
<P>
which give @numbers the new element values of (4,8,12,16). Just
by changing the scalar $two you can change the entire array @numbers.
<H3><A NAME="AssociativeArrays">
Associative Arrays</A></H3>
<P>
In Perl, associative arrays take the place of other recursive
data types, like trees, that are used in other computer languages.
<P>
These kinds of arrays are very similar to the list kind of arrays
discussed in <A HREF="ch2.htm" tppabs="http://210.32.137.15/ebook/PC%20Magazine%20Programming%20Perl%205.0%20CGI%20Web%20Pages%20for%20Microsoft%20Windows%20NT/ch2.htm" >Chapter 2</A> The main difference between them is that
a list array has index values for its elements, which start at
0 and increment by whole numbers to the end of the array, whereas
the associative array uses arbitrary scalars, also called keys.
<P>
What this means is that you are not limited to referring to an
element in an array by its integer-based index value, but you
can use whatever value you choose to associate with the array
element. It is quite normal, and quite desirable, to associate
strings with particular array elements in this way.
<P>
A good model for getting a better understanding of how associative
arrays work might be a Rolodex. New names and phone numbers are
written on separate cards and filed in the Rolodex's alphebetical
sections. When you want to find out the number of a new friend,
you go to the letter your friend's name is filed under to find
the number.
<P>
With associative arrays, the new names and phone numbers are scalar
values, while the letters on the Rolodex cards themselves are
the keys. To find the values, you look for the key to that value
in the associative array, like looking for the phone number using
the letters.
<P>
Associative arrays use a variable in this format:
<BLOCKQUOTE>
<PRE>
%variable_name
</PRE>
</BLOCKQUOTE>
<P>
Unlike array list variables, associative arrays are usually referred
to with their keys. Let's look at one:
<BLOCKQUOTE>
<PRE>
%month = (
"'Jan', 'January',"
"'Feb', 'February',"
"'Mar', 'March',"
"'Apr', 'April',"
"'May', 'May',"
"'Jun', 'June',"
"'Jul', 'Jul',"
"'Aug', 'August',"
"'Sept', 'September',"
"'Oct', 'October',"
"'Nov', 'November',"
"'Dec', 'December',"
);
</PRE>
</BLOCKQUOTE>
<P>
where single and double-quotes have the same powers they did in
array lists.
<P>
If you want to subscript an associative array, the process is
similar to subscripting an array list, but curly braces replace
the square brackets, so:
<BLOCKQUOTE>
<PRE>
# a simpe array
@wolf = (4,5,6);
$wolf[3] = "moon"; # making @wolf
# now (4,5,6,"moon")
$wolf[5] = "howl"; # producing
# (4,5,6,"moon",undef,"howl")
</PRE>
</BLOCKQUOTE>
<P>
becomes this as an adapted associative array:
<BLOCKQUOTE>
<PRE>
%wolf = (4,"four",5,"five",6,"six");
$wolf{4} = "moon"; # making %wolf
# now (4,"moon",5,"five",6,"six")
$wolf{5} = "howl"; # producing %wolf values
# (4,"moon",5,"howl",6,"six")
</PRE>
</BLOCKQUOTE>
<P>
Note that there are always an equal number of elements in an associative
array. There has to be a value and its key, otherwise the missing
value or key is given the undef value.
<P>
When you call up an associative array's values there is no literal
equivalent as there is with array lists. Instead, Perl creates
a string of key/value pairs in whatever order is easiest at the
time, depending on the phases of the moon. (Just kidding! Perl
creates the literal list of pair values based on what is fastest
at that moment based on where you are in the Perl script, so each
time you determine a literal list, the order will be slightly
different.)
<P>
Associative arrays also have their own operators.
<H4>The Keys Operator</H4>
<P>
To get a list of all the current keys of an associative array,
put the array name in parentheses behind the operator keys, like
this:
<BLOCKQUOTE>
<PRE>
keys(%wolf); #which would create
# the key/value list (4,5,6,), or
# something similar since the order
# does not have to remain the same
</PRE>
</BLOCKQUOTE>
<P>
where the use of parentheses is an option, and can be used as
you see fit.
<H4>The Values Operator</H4>
<P>
As you might imagine, the values operator works like the keys
operator, except that it returns a list of values of an associative
array
<BLOCKQUOTE>
<PRE>
values(%wolf); # creates
# ("moon","howl","six")
</PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -