21天入门Perl系列,DAY02

Basic Operators and Control Flow

More about scalar variables and how to assign values to them
The basic arithmetic operators and how they work with scalar variables
What an expression is
How to use the if statement and the == operator to test for simple conditions
How to specify two-way and multi-way branches using else and elsif
How to write simple loops using the while and until statements

01 Storing in Scalar Variables Assignment
This section tells more about variables such as $inputline and how to assign values to these variables.

the definition of a scalar variable
a scalar variable stores exactly one item-a line of input, a piece of text, or a number, for example.

Scalar variable syntax
the name of scalar variable consists of the characher $ followed by at least one letter, which is followed by any number of letters,digits,or underscore characters “_” , for example:$var, $x, $_ but the second character must be a letter,and without any special elements,variables are case-sensitive.

Assigning a value to a scalar variable
$var = 42;
$var = 113;
$name = “inputdata”;
please noted that the spaces or tabs contained inside the pair of “” characters are treated as part of the text, and “” characters are just there to enclose the text.
Performing Arithmetic
the assignment operator = takes the value to the right of the = sign and assigns it to the variable on the left of the =: $var = 45;
and there are basic operators: +, -, *, /, which were as simple as we learn in primary school, so i did not take more time to explain those operations.

Here is an example of Miles-to-Kilometers conversion.

#!/usr/bin/perl
print (“Enter the distance to be converted:\n”);
$originaldist = <STDIN>;
chop ($originaldist);
$miles = $orginaldist * 0.6214;
$kilometers = $orginaldist * 1.609;
print ($originaldist, ” kilometers = “, $miles, ” miles\n”);
print ($originaldist, ” miles = “, $kilometers,” kilometers\n”);

Note that the \n at the end of the text is not printed. The \n is a special sequence of characters that represents the newline character; when the print library function sees \n, it starts a new line of output on your screen.

chop, which gets rid of the closing newline character that is part of the input line you entered. The chop library function is described in the following section, “The chop Library Function.”

Introduction to Conditional Statements

As we know the example of distance conversion, it starts at the top of the program and executes each statement in turn. When the final statement is executed, the program is terminated. All above are unconditional statements, means the statements will never stop until the final statement is finished.But sometimes we may need certain condition to execute the statements, which are known as conditional statements.

Perl supports a variety of conditional statements. In the following sections, you’ll learn about these conditional statements: if :excutes when a specified contion is true; if-else :chooses between two alternatives; if-elsif-else :choose between more than two alternatives; while and until :repeats a group of statements a specificed number of times.
The if Statement
if ($number) { #part1, conditional expression.
print (“The number is not zero.\n”); #part2, statement block.
}
The Conditional Expression

If the result is a nonzero value, the conditional expression is true.
If the result is zero, the conditional expression is false.
If the conditional expression is true, the statements are executed. If the conditional expression is false, the statements are not executed.

Listing 2.2. A program containing a simple example of an if statement.

#!/usr/local/bin/perl
print (“Enter a number:\n”);
$number = <STDIN>;
chop ($number);
if ($number) {
print (“The number is not zero.\n”);
}
print (“This is the last line of the program.\n”);
The syntax for the if statement is
if (expr) {
statement_block
}

Testing for Equality Using ==

Perl provides special operators that are designed for use in conditional expressions. One such operator is the equality comparison operator, ==.
If the two subexpressions evaluate to the same numeric value, the == operator yields the result true.
If the two subexpressions have different values, the == operator yields the result false.

Listing 2.3. A program that uses the equality-comparison operator to compare two numbers entered at the keyboard.

#!/usr/local/bin/perl
print (“Enter a number:\n”);
$number1 = <STDIN>;
chop ($number1);
print (“Enter another number:\n”);
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print (“The two numbers are equal.\n”);
}
print (“This is the last line of the program.\n”);

Other Comparison Operators

Two-Way Branching Using if and else

Listing 2.4 is a modification of the program in Listing 2.3. It uses the if-else statement to print one of two messages, depending on whether the numbers are equal.

Listing 2.4. A program that uses the if-else statement.

#!/usr/local/bin/perl
print (“Enter a number:\n”);
$number1 = <STDIN>;
chop ($number1);
print (“Enter another number:\n”);
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print (“The two numbers are equal.\n”);
} else {
print (“The two numbers are not equal.\n”);
}
print (“This is the last line of the program.\n”);
The syntax for the if-else statement is

if (expr) {
statement_block_1
} else {
statement_block_2
}
As in the if statement, expr is any expression (it is usually a conditional expression). statement_block_1 is the block of statements that the Perl interpreter executes if expr is true, and statement_block_2 is the block of statements that are executed if expr is false.
Multi-Way Branching Using

Listing 2.5. A program that uses the if-elsif-else statement.

#!/usr/local/bin/perl
print (“Enter a number:\n”);
$number1 = <STDIN>;
chop ($number1);
print (“Enter another number:\n”);
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print (“The two numbers are equal.\n”);
} elsif ($number1 == $number2 + 1) {
print (“The first number is greater by one.\n”);
} elsif ($number1 + 1 == $number2) {
print (“The second number is greater by one.\n”);
} else {
print (“The two numbers are not equal.\n”);
}
print (“This is the last line of the program.\n”);

The syntax of the if-elsif-else statement is as follows:

if (expr_1) {
statement_block_1
} elsif (expr_2) {
statement_block_2
} elsif (expr_3) {
statement_block_3

} else {
default_statement_block
}

Here, expr_1, expr_2, and expr_3 are conditional expressions. statement_block_1, statement_block_2, statement_block_3, and default_statement_block are blocks of statements. The … indicates that you can have as many elsif statements as you like. Each elsif statement has the same form.
Writing Loops Using the while Statement
Each statement in the conditional statements Perl programs that you have seen is either not executed or is executed only once.Perl also enables you to write conditional statements that tell the Perl interpreter to repeat a block of statements a specified number of times. A block of statements that can be repeated is known as a loop. The simplest way to write a loop in Perl is with the while statement.

here is a simple example of a while statement:

while ($number == 5) { #part1
print (“The number is still 5!\n”); #part2
}

First, the conditional expression located between the parentheses is tested.
If the conditional expression is true, the statement block between the { and } is executed.If the expression is false, the statement block is skipped, and the Perl interpreter jumps to the statement following the while statement. (This is called exiting the loop.)
If the statement block is executed, the Perl interpreter jumps back to the start of the whilestatement and tests the conditional expression over again. (This is the looping part of the while statement, because at this point the Perl interpreter is executing a statement it has executed before.)
Listing 2.6. A program that demonstrates the while statement.
#!/usr/local/bin/perl
$done = 0;
$count = 1;
print (“This line is printed before the loop starts.\n”);
while ($done == 0) {
print (“The value of count is “, $count, “\n”);
if ($count == 3) {
$done = 1;
}
$count = $count + 1;
}
print (“End of loop.\n”);
Nesting Conditional Statements
while (expr_1) {
some_statements
while (expr_2) {
inner_statement_block
}
some_more_statements
}

Similarly, you can have an if statement inside another if statement, or you can have a whilestatement inside an if statement. You can nest conditional statements inside elsif and else parts of if statements as well:
if ($number == 0) {
# some statements go here
} elsif ($number == 1) {
while ($number2 == 19) {
# here is a place for a statement block }
} else {
while ($number2 == 33) {
# here is a place for another statement block
}
}
The braces ({ and }) around the statement block for each conditional statement ensure that the Perl interpreter never gets confused.

Looping Using the until Statement

Another way to loop in Perl is with the until statement. It is similar in appearance to the whilestatement, but it works in a slightly different way.
The while statement loops while its conditional expression is true.
The until statement loops until its conditional expression is true (that is, it loops as long as its conditional expression is false).

Listing 2.7. A program that uses the until statement.

#!/usr/bin/perl
print (“What is 17 plus 26?\n”);
$correct_answer = 43; #the correct answer
$input_answer = <STDIN>;
chop ($input_answer);
until ($input_answer == $correct_answer){
print (“Wrong!Keep trying!\n”);
$input_answer = <STDIN>;
chop ($input_answer);
}
ptint (“You’ve got it \n”);
Summary
The following conditional statements were described today:
The if statement, which is executed only if its conditional expression is true
The if-else statement, which chooses between two alternatives
The if-elsif-else statement, which chooses between multiple alternatives
The while statement, which loops while a condition is true
The until statement, which loops until a condition is true

Q&A
Q:Which should I use, the while statement or the until statement?
A:It doesn’t matter, really; it just depends on which, in your judgment, is easier to read. Once you learn about the other comparison operators on Day 4, “More Operators,” you’ll be able to use the while statement wherever you can use an until statement, and vice versa.

Q:In Listing 2.7, you read input from the standard input file in two separate places. Is there any way I can reduce this to one?
A:Yes, by using the do statement, which you’ll encounter on Day 8, “More Control Structures.”

Q:Do I really need both a $done variable and a $count variable in Listing 2.6?
A:No. On Day 4 you’ll learn about comparison operators, which enable you to test whether a variable is less than or greater than a particular value. At that point, you won’t need the $done variable.

Q:How many elsif parts can I have in an if-elsif-else statement?
A:Effectively, as many as you like. (There is an upper limit, but it’s so large that you are not likely ever to reach it.)

Q:How much nesting of conditional statements does Perl allow? Can I put an if inside a while that is inside an if that is inside an until?
A:Yes. You can nest as many levels deep as you like. Generally, though, you don’t want to go too many levels down because your program will become difficult to read. The logical operators, which you’ll learn about on Day 4, make it possible to produce more complicated conditional expressions. They’ll eliminate the need for too much nesting.
Workshop
Quiz

1.Define the following terms:
a. expression
b. operand
c. conditional statement
d. statement block
e. infinite loop

2. When does a while statement stop looping?

3. When does an until statement stop looping?

4. What does the == operator do?

5. What is the result when the following expression is evaluated? 14 + 6 * 3 – 10 / 2
6. Which of the following are legal scalar variable names?
a. $hello
b. $_test
c. $now_is_the_time_to_come_to_the_aid_of_the_party
d. $fries&gravy
e. $96tears
f. $tea_for_2

Exercises

1. Write a Perl program that reads in a number, multiplies it by 2, and prints the result.

2. Write a Perl program that reads in two numbers and does the following: mIt prints Error: can’t divide by zero if the second number is 0. mIf the first number is 0 or the second number is 1, it just prints the first number (because no division is necessary). mIn all other cases, it divides the first number by the second number and prints the result.

3. Write a Perl program that uses the while statement to print out the first 10 numbers (1-10) in ascending order.

4. Write a Perl program that uses the until statement to print out the first 10 numbers in descending order (10-1).

5. BUG BUSTER: What is wrong with the following program? (Hint: there might be more than one bug!)#!/usr/local/bin/perl$value = <STDIN>;if ($value = 17) {print (“You typed the number 17.\n”);else {print (“You did not type the number 17.\n”);

6. BUG BUSTER: What is wrong with the following program?
#!/usr/local/bin/perl
# program which prints the next five numbers after the
# number typed in$input = <STDIN>;chop ($input);
$input = $input + 1;
# start with the next number;
$input = $terminate + 5;
# we want to loop five times
until ($input == $terminate) {
print (“The next number is “, $terminate, “\n”);

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s