Control Structures


In order to write more interesting scripts, you will need to know about control structures.

if Statements

An if statement tests to see if a condition is true. If it is, the following block of code is executed. This example tests to see if the value of $x is less than 0. If so, it multiplies by 1 to make it positive:

 if ($x < 0) {       $x *= −1; }

Perl is not sensitive to line breaks, so you can write short statements like the one just shown all on one line. The following example checks to see if $x or $y is equal to 0:

 if ($x == 0 | $y == 0) {print "Cannot divide by 0.\n";}

There are a few things to notice here. The comparison == is used to see if two numbers are equal. Be careful not to use =, which in this case would set $x to 0. Also, | | means “or”. If we wanted to know if both $x and $y were 0, we could use && for “and”.

Another way to write a one-line if statement is to put the test last:

 print "Error: input expected\n" if (! defined $input);

In this example, the ! stands for “not”. The function defined is used to determine if a variable has been assigned a value. This statement says “print an error message if $input has not been defined”.

In some cases you may find it more natural to write this type of statement as

 print "Error: input expected\n" unless (defined $input);

if statements can have an else clause that gets executed if the initial condition is not met. This example checks whether a hash contains a particular key:

 if (exists $hash{$key}){       print "$key is $hash{$key}\n"; } else {       print "$key could not be found\n"; }

You can also include elseif clauses that test additional conditions if the first one is false. This example has one elseif clause. It uses the keyword eq to see if two strings are equal:

 if ($str eq "\L$str") {       print "$str is all lowercase.\n"; } elseif ($str eq "\U$str") {       print "$str IS ALL UPPERCASE.\n"; } else {       print "$str Combines Upper And lower case letters.\n"; }

Comparison Operators

Table 22–1 lists the operators used for comparison. Notice that there are different operators, depending on whether you are comparing numbers or strings. Be careful to use the appropriate operators for your comparisons. For example, “0.67” == “.67” is true, because the two numbers are equal, but “0.67” eq “.67” is false, because the strings are not identical.

Table 22–1: Comparison Operators

Numerical

String

Meaning

==

eq

is equal to

!=

ne

does not equal

>

gt

is greater than

<

lt

is less than

>=

ge

is greater than or equal to

<=

le

is less than or equal to

while Loops

The while loop repeats a block of code as long as a particular condition is true. For example, this loop will repeat five times, until the value of $n is 0:

 my ($n, $sum) = (5, 0); while ($n > 0) {      $sum += $n;      $n--; } print "$sum\n";

The first line of the loop could also have been written as

 until ($n == 0) {

A common use of while loops is to process input. The assignment $input=<STDIN> will have a value of true as long as there is data coming from standard input. The following example will center each line of input from the keyboard, stopping when CTRL-D signals the end of input:

 while (my $input = <STDIN>) {       $indent = (80 − length ($input))/2;       print " "x $indent;       print "$input"; }

The $ Variable

The $_ variable is a shortcut you can use to make scripts like the one just shown even more compact. Many Perl functions operate on $_ by default. The output from <STDIN> is assigned to $_ if you do not explicitly assign it elsewhere. print sends the value of $_ to standard output if no argument is specified. Similarly, chomp works on $_ by default.

With $_, the preceding centering script could be rewritten as

 while (<STDIN>){      print " " x  ((80 − length())/2) . $_; }

Note that this use of length returns the length of $_. This could even be written on a single line, as

 print " " x  ((80 − length())/2) . $_ while (<STDIN>);

Iterating Through Hashes

You can use a while loop to iterate through the elements in a hash with the each function. This function returns a key/value pair each time it is called. For example, you could print the elements of the hash %userinfo as shown:

 while (my ($key, $value) = each %userinfo) {      print "$key −> $value\n"; }

foreach Loops

The foreach loop iterates through the elements of a list. This example will print each list element on its own line:

 foreach $line (@list){       print "$line\n"; }

The syntax here could be read as “for each line in the list, print.”

If you leave out the variable, foreach will use $_:

 foreach (@emailaddr) {       print "Email sent to $_\n"; }

This example could be written on a single line as

 print "Email sent to $_\n" foreach (@emailaddr);

The foreach loop is also handy for working with hashes. This loop will print the contents of a hash:

 foreach $key (keys %userinfo) {       print "$key −> $userinfo{$key}\n"; }

for Loops

The Perl for loop syntax is just like the syntax in C. The loop

 for (my $i=0; $i<=10; $i++) {       print $i**2 . "\n"; }

prints the squares of the integers from 0 to 10. This is the same as

 foreach (0..10) {       print $ **2 . "\n"; }




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net