To go through each line of an array or other list-like structure (such as lines in a file) Perl uses the foreach structure. This has the form
foreach $morsel (@food) {
print "$morsel\n"; # Print the item
print "Yum yum\n"; # That was nice
}
The actions to be performed each time are enclosed in a block of curly braces. The first time through the block $morsel is assigned the value of the first item in the array @food. Next time it is assigned the value of the second item, and so until the end. If @food is empty to start with then the block of statements is never executed.
Testing
The next few structures rely on a test being true or false. In Perl any non-zero number and non-empty string is counted as true. The number zero, zero by itself in a string, and the empty string are counted as false. Here are some tests on numbers and strings.
Test Numbers
$a == $b # Is $a numerically equal to $b?
$a != $b # Is $a numerically unequal to $b?
Test Strings
$a eq $b # Is $a string-equal to $b?
$a ne $b # Is $a string-unequal to $b?
Logical Comparisons
($a && $b) # Is $a and $b true?
($a $b) # Is either $a or $b true?
!($a) # is $a false?
for
Perl has a for structure that mimics that of C. It has the form
for ($i=0; $i<10; $i++){
print $i;
}
Do While Loop
do{
"Password? "; # Ask for input
$a =
chop $a; # Chop off newline
}
while ($a ne "fred") # Redo while wrong input
No comments:
Post a Comment