Introducing UNIX and Linux |
PerlOverview |
Control structuresThe phrase control structures refers to the statements in the language that allow for choices and repetitions. In practice, this usually means if statements and loops. The condition can be anything that evaluates to true or false. Similarly, a while statement will repeatedly execute until the condition ceases to be true:
We have already met a Worked exampleRead in two numbers from standard input, and prompt the user to
enter their product. Continue to do so until the correct answer is
entered. # Prompt for input, and read two numbers print "Type in the first number: "; $n1 = <STDIN>; print "Type in the second number: "; $n2 = <STDIN>; # Prompt for, and read, answer print "Type in their product: "; $answer = <STDIN>; # Loop until correct answer input while ($answer != $n1*$n2) { print "Wrong - try again: "; $answer = <STDIN>; } print "Correct - the answer is $answer\n"; Similary, at its simplest, an if statement takes the following form: if ( condition ) { code to execute if condition true } else { code to execute if condition false } There is also a variant of the syntax for
we can write condition and instead of
we can write condition The symbol open(INPUT, "myfile") || die "Cannot open myfile"; The Worked exampleYour login shell reads in commands from the first of the
following two files which may exist in your home directory:
# Try to open the one of the two files open(INPUT, ".bash_profile") || open(INPUT, ".profile") || die "Neither .bash_profile nor .profile found"; # If one is open, use filehandle INPUT to read from it while (<INPUT>) { print "$_"; } # Finally, close the file close(INPUT); |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck