Here we'll use all 3 control structures in one program (save it as alphabet.pl):
First, initialize an array with all the alphabet:
@alphabet = (a-z);
Now, print the alphabet and a prompt:
print @alphabet, "\n"; print "Please type a letter.\n";
Once again, the while takes input from the keyboard (`<>') and saves it in '$_'.
while(<>){ chomp; alphabet($_); print @alphabet, "\n"; print "Please type a letter.\n"; }
`alphabet($_)' is a subroutine. When you are going to do something over and over, it can be clearer if you put the details in a subroutine and send it input as the argument - the stuff in the `()'. To define the subroutine use the perl function `sub':
sub alphabet { $input = $_[0]; $i = 0; foreach $letter (@alphabet) { if ($input eq $letter) { $alphabet[$i] = " "; } $i++; } }
The arguments of the subroutine are kept in the array ``@_''. The first item in the array is $_[0].
`$i' is an iteration variable. We use it to keep track of which letter we are working on. $alphabet[0] is `a', $alphabet[4] is `e', and so on until $alphabet[25] is `z'. Just like in section 4.2 , `foreach' sets $letter to each item of @alphabet, one at a time.
We test whether $input is equal to the currect item, $letter with the `if'. If it is equal we set that item of the array to be a space, `` ''. Then we increase $i by 1 using the ++ operator.