Note: Programs run on penguin can start the first line with the
following (shorter) perl path: #!/usr/bin/perl
w3.1.pl The "if" and "elsif" statements
#!/usr/bin/perl
#w3.1.pl statement blocks; if statement
print ("How many hotdogs would you like? ");
chomp($no= );
if ($no <= 0){
print ("So you are the vegetarian.\n");
}
elsif ($no <= 2){
print ("We can handle $no. \n");
}
elsif ($no >=3){
print ("We can put more on. ");
print ("By the way, you won't mind\nif we keep the ambulance handy.\n");
}
__END__
w3.2.pl A simple while statement.
#!/usr/bin/perl
#w3.2.pl while statement
@people = (Jim, Floyd, Fred, Jane, Marta, Jill, Sam, Joe, Alice, Andrea);
while (@people) {
$person = pop(@people);
print("$person\n");
}
__END__
w3.3.pl A more complex while statement
#!/usr/bin/perl
#w3.3.pl while statement (with last).
@people = (Jim, Floyd, Fred, Jane, Marta, Jill, Sam, Joe, Alice, Andrea);
print("Please enter your name: ");
chomp($name = );
while (@people) {
$try = pop(@people);
if ($try eq $name){
print("Yes, you can use our computer.\n");
$success = 1;
last;
} #End if statement
} #End while
if (!$success){ #The ! negates as in !=
print("Sorry $name, you are not on my list.\n");
}
__END__
w3.4.pl a complete for statement
#!/usr/bin/perl
#w3.4.pl the for statement
@people = (Jim, Floyd, Fred, Jane, Marta, Jill, Sam, Joe, Alice, Andrea);
print("Please enter your name: ");
chomp($name = );
for ($a=0;$a <= $#people; $a++) { # $#people counts @people
# print ("Last person is at sub $#people\n");
# print ("DEBUG: $people[$a]\n"); #DEBUG
if ($people[$a] eq $name){
print("Yes, you can use our computer.\n");
$success = 1;
last;
} #End if block
} #End for block
if (!$success){
print("Sorry $name, you are not on my list.\n");
}
__END__
w3.5.pl Things can be easier with foreach
#!/usr/bin/perl
#w3.5.pl foreach()
@people = (Jim, Floyd, Fred, Jane, Marta, Jill, Sam, Joe, Alice, Andrea);
print("Please enter your name: ");
chomp($name = );
foreach (@people){
# print ("Check $_\n"); #DEBUG
if ($_ eq $name){
print("Yes, $_, you can use our computer.\n");
$success = 1;
last;
} #End if block
} #End for block
if (!$success){
print("Sorry, $name, you are not on my list.\n");
}
__END__
w3.6.cgi: Import a text file. Add <p> to all blank lines. Put an
HTML header on the file so that a browser can display it.
#!/usr/bin/perl
#w3.6.cgi
open (FH, "sample.txt");
while (){ #puts each line from FH in $_
@lines = (@lines, $_);
}
##Print the HTML header
print("Content-type: text/html\n\n");
print < Tc392 w3.6.cgi