Perl Scripting on Linux
Script 1: Adding the numbers 1 to 100, Version 1
$top_number = 100; $x = 1; $total = 0; while ( $x <= $top_number ) { $total = $total + $x; # short form: $total += $x; $x += 1; # do you follow this short form? } print "The total from 1 to $top_number is $total\n";
Script 2: Adding the numbers 1 to 100. Version 2
This script uses a form of the for loop to go through the integers 1 through 100:
$total = 0;
#the for loop gives $x the value of all the
#numbers from 1 to 100;
for $x ( 1 .. 100 ) {
$total += $x; # again, the short form
}
print "The total from 1 to 100 is $total\n";
Script 3: Printing a menu
This script uses an array to store flavors. It also uses a terrific form of the for loop to go through them.
@flavors = ( "vanilla", "chocolate", "strawberry" ); for $flavor ( @flavors ) { print "We have $flavor milkshakes\n"; } print "They are 2.95 each\n"; print "Please email your order for home delivery\n";
Script 4: Going one way or the other:
This allows you to program in a word to make a decision. The "ne" in the if statement stands for "not equal" and is used to compare text. The "die" statement shows you a way to get out of a program when you're in trouble.
#You can program answer to be heads or tails $answer = "heads"; if ( $answer ne "heads" and $answer ne "tails" ) { die "Answer has a bad value: $answer!"; } print "Answer is programmed to be $answer.\n"; if ( $answer eq "heads" ) { print "HEADS! you WON!\n"; } else { print "TAILS?! you lost. Try your coding again!\n"; }
Script 5: Going one way or the other, interactively:
This allows you to type in a word to make a decision. A shameless sneak peek at the next lesson on input and output. <STDIN> allows us to read a word from the keyboard, and "chomp" is a function to remove the newline that's attached to our answer after hitting the carriage return.
print "Please type in either heads or tails: "; #The <STDIN> is the way to read keyboard input $answer = <STDIN>; chomp $answer; while ( $answer ne "heads" and $answer ne "tails" ) { print "I asked you to type heads or tails. Please do so: "; $answer = <STDIN>; chomp $answer; } print "Thanks. You chose $answer.\n"; print "Hit enter key to continue: "; #This line is here to pause the script #until you hit the carriage return #but the input is never used for anything. $_ = <STDIN>; if ( $answer eq "heads" ) { print "HEADS! you WON!\n"; } else { print "TAILS?! you lost. Try again!\n"; }
Comments
Post a Comment