SlideShare uma empresa Scribd logo
1 de 7
Baixar para ler offline
Some Simple Perl Scripts


To get an idea of how Perl works, we'll finish off the first lesson with some
simple Perl scripts. We'll build on the items you've learned earlier: scalars
and arrays, the if-else, while and for constructs, and the print statement.


Since we're writing real perl programs here, there are a few more things you
should know about.

Statements


Statements 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 something
else.

Comments


If you've ever had the nerve to scribble notes in the margin of a novel, you'll
know 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 program
so 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 the
end of the line is a comment. For example:

#This illustrates a comment.


#Note there is a semi-colon on the next line
print "The quick brown fox jumped over the lazy dogn";
There is another form of comment which is very useful when you want to
chop out large sections of code. Borrowing a technique from Perl's
embedded documentation, I like to use it in this way:

=comment until cut
$variable = 1;
print "The variable has the value of $variablen";
...
...


=cut


Commenting out large sections like this can be extremely helpful.

The Newline Character


In the examples leading up to this section, I've used the print statement a
lot. Each time, I've added the funny ending "n" onto the print statement.
This odd combo of n is the newline character. Without it, the print
statement would not go on to the next line.

Many people are surprised to learn you have to tell the program to go to a
new line each time. But if it did this all by itself every time, then you could
never 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
eight
 words altogether in this sentence.


Short Forms

In perl, some operations are so common they have a shortened form that
saves time. These may be strange to the novice, so I'll be careful here.
Where appropriate I'll make a comment near the statement to describe the
short form.

Programming Errors

Programming errors? Already? Yes. Programming errors, also affectionately
known as bugs, are a fact of programming life. You'll be encountering them
soon enough.


If you have a mistake in your perl script that makes your meaning unclear,
you'll get a message from the perl compiler when you try to run it. To check
for these errors before running, you can run perl with the -c flag. And turn
on the warnings flag, -w, while you're at it. This picks up hard to find errors
too. As an example you'd type in:

perl -wc hello.pl


to check on the health of the perl script, hello.pl. If there are any syntax
errors, you'll hear about them alright!

Running the example scripts


You can copy any of the following script examples into a file in Notepad and
save it as, say, perltest.pl. Then check it for errors by typing

perl -wc perltest.pl
If it comes back saying "syntax ok", then go ahead and run it by typing

perl perltest.pl


If it doesn't say "syntax ok", then go and fix the reported error, and try
again.

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 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 $totaln";



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 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 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";
}

Mais conteúdo relacionado

Semelhante a Simple Perl Scripts to Get Started

Perl courseparti
Perl coursepartiPerl courseparti
Perl coursepartiernlow
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng verQrembiezs Intruder
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
The swift programming language
The swift programming languageThe swift programming language
The swift programming languagePardeep Chaudhary
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statisticsDorothy Bishop
 
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...Mark Simon
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Learn python
Learn pythonLearn python
Learn pythonmocninja
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
Lecture 22
Lecture 22Lecture 22
Lecture 22rhshriva
 

Semelhante a Simple Perl Scripts to Get Started (20)

Simple perl scripts
Simple perl scriptsSimple perl scripts
Simple perl scripts
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Perl slid
Perl slidPerl slid
Perl slid
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
OS.pdf
OS.pdfOS.pdf
OS.pdf
 
Algorithm and psuedocode
Algorithm and psuedocodeAlgorithm and psuedocode
Algorithm and psuedocode
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
The swift programming language
The swift programming languageThe swift programming language
The swift programming language
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Learning R while exploring statistics
Learning R while exploring statisticsLearning R while exploring statistics
Learning R while exploring statistics
 
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Learn python
Learn pythonLearn python
Learn python
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-filesBioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Mais de University High School - Fresno (12)

Dah time mgmt matching exercise answers
Dah time mgmt matching exercise answersDah time mgmt matching exercise answers
Dah time mgmt matching exercise answers
 
Capm time mgmt fas track as
Capm time mgmt fas track asCapm time mgmt fas track as
Capm time mgmt fas track as
 
Capm ccvc capm time 4th edition pmbok review
Capm ccvc capm time   4th edition pmbok reviewCapm ccvc capm time   4th edition pmbok review
Capm ccvc capm time 4th edition pmbok review
 
Capm test taking preparation hints
Capm test taking preparation hintsCapm test taking preparation hints
Capm test taking preparation hints
 
Capm process cheat sheet
Capm process cheat sheetCapm process cheat sheet
Capm process cheat sheet
 
Capm time 150 question final key
Capm time 150 question final keyCapm time 150 question final key
Capm time 150 question final key
 
Capm scenario identifying the critical path answers
Capm scenario identifying the critical path   answersCapm scenario identifying the critical path   answers
Capm scenario identifying the critical path answers
 
Capm scenario identifying the critical path answers
Capm scenario identifying the critical path   answersCapm scenario identifying the critical path   answers
Capm scenario identifying the critical path answers
 
Capm time mgmt matching exercise
Capm time mgmt matching exerciseCapm time mgmt matching exercise
Capm time mgmt matching exercise
 
Source code examples
Source code examplesSource code examples
Source code examples
 
Business computing survey
Business computing surveyBusiness computing survey
Business computing survey
 
Watson
WatsonWatson
Watson
 

Simple Perl Scripts to Get Started

  • 1. Some Simple Perl Scripts To get an idea of how Perl works, we'll finish off the first lesson with some simple Perl scripts. We'll build on the items you've learned earlier: scalars and arrays, the if-else, while and for constructs, and the print statement. Since we're writing real perl programs here, there are a few more things you should know about. Statements Statements 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 something else. Comments If you've ever had the nerve to scribble notes in the margin of a novel, you'll know 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 program so 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 the end of the line is a comment. For example: #This illustrates a comment. #Note there is a semi-colon on the next line print "The quick brown fox jumped over the lazy dogn";
  • 2. There is another form of comment which is very useful when you want to chop out large sections of code. Borrowing a technique from Perl's embedded documentation, I like to use it in this way: =comment until cut $variable = 1; print "The variable has the value of $variablen"; ... ... =cut Commenting out large sections like this can be extremely helpful. The Newline Character In the examples leading up to this section, I've used the print statement a lot. Each time, I've added the funny ending "n" onto the print statement. This odd combo of n is the newline character. Without it, the print statement would not go on to the next line. Many people are surprised to learn you have to tell the program to go to a new line each time. But if it did this all by itself every time, then you could never 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. eight words altogether in this sentence. Short Forms In perl, some operations are so common they have a shortened form that saves time. These may be strange to the novice, so I'll be careful here. Where appropriate I'll make a comment near the statement to describe the short form. Programming Errors Programming errors? Already? Yes. Programming errors, also affectionately known as bugs, are a fact of programming life. You'll be encountering them soon enough. If you have a mistake in your perl script that makes your meaning unclear, you'll get a message from the perl compiler when you try to run it. To check for these errors before running, you can run perl with the -c flag. And turn on the warnings flag, -w, while you're at it. This picks up hard to find errors too. As an example you'd type in: perl -wc hello.pl to check on the health of the perl script, hello.pl. If there are any syntax errors, you'll hear about them alright! Running the example scripts You can copy any of the following script examples into a file in Notepad and save it as, say, perltest.pl. Then check it for errors by typing perl -wc perltest.pl
  • 4. If it comes back saying "syntax ok", then go ahead and run it by typing perl perltest.pl If it doesn't say "syntax ok", then go and fix the reported error, and try again. 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 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 }
  • 5. print "The total from 1 to 100 is $totaln"; 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 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 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";
  • 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 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
  • 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"; }