Control structures
1. foreach
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
@books = ("book1","book2","book3");
foreach $thing (@books ) # Visit each item in turn
# and call it $thing
{
print "$thing\n"; # Print the item
print "--------------- \n"; # That was nice
}
2. The loop for:
for ($i = 0; $i < 10; ++$i) # Start with $i = 1
# Do it while $i < 10
# Increment $i before repeating
{
print "$i\n";
}
3. While
---------
print "Password? "; # Ask for input
$a = ; # Get input
chop $a; # Remove the newline at end
while ($a ne "fred") # While input is wrong...
{
print "sorry. Again? "; # Ask again
$a = ; # Get input again
chop $a; # Chop off newline again
}
4. chop() function
------------------
removes and returs the last character from a string.
chomp(0 removes a new line
Example:
--------
my @array = ("bob\n", "jill", "fred\n");
print "Before chomp:\n";
print "@array\n";
chomp(@array);
print "After chomp:\n";
print "@array\n";
outputs
---------
bob
jill fred
After chomp:
bob jill fred
4. Do while:
-----------
do
{
"Password? "; # Ask for input
$a = ; # Get input
chop $a; # Chop off newline
}
while ($a ne "fred") # Redo while wrong input
|