Simple perl scripts


Published on

sample scripts

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Simple perl scripts

  1. 1. Some Simple Perl ScriptsTo get an idea of how Perl works, well finish off the first lesson with somesimple Perl scripts. Well build on the items youve learned earlier: scalarsand arrays, the if-else, while and for constructs, and the print statement.Since were writing real perl programs here, there are a few more things youshould know about.StatementsStatements are complete thoughts in perl, just like sentences. In English,sentences end with a period. In Perl, statements must end with a semi-colon. This is for good reason — in perl the period is used for somethingelse.CommentsIf youve ever had the nerve to scribble notes in the margin of a novel, youllknow what comments are for.In perl, comments are words within the program that perl itself ignores.They are written by you for your own benefit. They help explain the programso when you look at it later you know what the heck is going on. In perl,comments are set off with the "#" character. Anything following the # to theend of the line is a comment. For example:#This illustrates a comment.#Note there is a semi-colon on the next lineprint "The quick brown fox jumped over the lazy dogn";
  2. 2. There is another form of comment which is very useful when you want tochop out large sections of code. Borrowing a technique from Perlsembedded documentation, I like to use it in this way:=comment until cut$variable = 1;print "The variable has the value of $variablen";......=cutCommenting out large sections like this can be extremely helpful.The Newline CharacterIn the examples leading up to this section, Ive used the print statement alot. Each time, Ive added the funny ending "n" onto the print statement.This odd combo of n is the newline character. Without it, the printstatement would not go on to the next line.Many people are surprised to learn you have to tell the program to go to anew line each time. But if it did this all by itself every time, then you couldnever print out complete lines a bit at a time, like this:$num_words = "eight";print "There are ";print $num_words;print " words altogether in this sentence.n";Instead the output would be:There are
  3. 3. eight words altogether in this sentence.Short FormsIn perl, some operations are so common they have a shortened form thatsaves time. These may be strange to the novice, so Ill be careful here.Where appropriate Ill make a comment near the statement to describe theshort form.Programming ErrorsProgramming errors? Already? Yes. Programming errors, also affectionatelyknown as bugs, are a fact of programming life. Youll be encountering themsoon enough.If you have a mistake in your perl script that makes your meaning unclear,youll get a message from the perl compiler when you try to run it. To checkfor these errors before running, you can run perl with the -c flag. And turnon the warnings flag, -w, while youre at it. This picks up hard to find errorstoo. As an example youd type in:perl -wc hello.plto check on the health of the perl script, If there are any syntaxerrors, youll hear about them alright!Running the example scriptsYou can copy any of the following script examples into a file in Notepad andsave it as, say, Then check it for errors by typingperl -wc
  4. 4. If it comes back saying "syntax ok", then go ahead and run it by typingperl perltest.plIf it doesnt say "syntax ok", then go and fix the reported error, and tryagain.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 $totaln";Script 2: Adding the numbers 1 to 100. Version 2This script uses a form of the for loop to go through the integers 1 through100:$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}
  5. 5. print "The total from 1 to 100 is $totaln";Script 3: Printing a menuThis script uses an array to store flavors. It also uses a terrific form of thefor loop to go through them.@flavors = ( "vanilla", "chocolate", "strawberry" );for $flavor ( @flavors ) { print "We have $flavor milkshakesn";}print "They are 2.95 eachn";print "Please email your order for home deliveryn";Script 4: Going one way or the other:This allows you to program in a word to make a decision. The "ne" in the ifstatement stands for "not equal" and is used to compare text. The "die"statement shows you a way to get out of a program when youre 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";
  6. 6. 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 sneakpeek at the next lesson on input and output. <STDIN> allows us to read aword from the keyboard, and "chomp" is a function to remove the newlinethats 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
  7. 7. #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";}