Our Sites:  Tutorial Buzz  |  How To Tree  |  Recipe Voice  |  Golf Twist  |  DIY Click  |  Movie Lizard  |  Halloween Twist  
<
Search:
Submit Link
Mail to a Friend
RSS FeedReceive updates via our RSS feed

Perl Syntax

This tutorial is an introductory look at the Perl language and its syntax.

Semicolons
All Perl lines must end in semicolons. Perl does not use the carriage return to indicate the end of a line, it uses the semicolon.

$myName = "Jerry";
print "Hello, $myName\n";

Standard Shell Script Stuff

Where is the Perl program?
You need to tell the Unix shell where to find the “interpreter” for your shell script. Put the following line at the top of all of your Perl scripts.

#!/usr/local/bin/perl
Let UNIX Know Your Script is Executable
You need to tell the Unix shell that your text file is a script that can be run as if it were a computer program. Type “chmod u+x filename” on the Unix command line to make it “executable”.
chmod u+x hello
Comments
It is always a good idea to put “comments” in your programs. These remind you what you were doing later on. Perl completely ignores your comments. For these, preface the line with the pound sign (‘#’). Perl will ignore any line that begins with a pound sign. You do not need to end your comments with semicolons.

Put the following line in front of the line that contains your name:

#tell Perl my name

Put the following line in front of the line that contains “print”:

#say hello to me!

You can also use comments to tell Perl to ignore parts of your program. You might want to do this to track down a bug, or to bypass a part of the program that isn't working correctly.

Scalar Variables
Variables store information. You set a variable with the “=” modifier:
$myName = "Jerry";

A “scalar” variable is a variable that only holds one value. Later, we’ll get into “array” variables, which can hold more than one value, for example, all the first names in Academic Computing. Scalar variables always begin with a dollar sign.

Text vs. Numeric
Text variables are surrounded by quotes. Numeric variables can only contain numbers and maybe a decimal point. Perl doesn't care whether a variable is numeric or text until it uses it. If you try to use a variable as numeric when it can’t be converted to a number, Perl assumes it is zero.
#Test text and numeric variables
$First = "1.0";
$Second = "1";
if ($First eq $Second) {
	print "$First and $Second are the same with EQ!\n";
} else {
	print "$First and $Second are different with EQ!\n";
}
if ($First == $Second) {
	print "$First and $Second are the same with ==!\n";
} else {
	print "$First and $Second are different with ==!\n";
}

What happens if you get rid of the quotes, and why?

Working with Numbers
You can do any normal math with numbers: addition, subtraction, multiplication, and division. And you can use parentheses to partition off parts of the equations. Perl uses “algebraic” precedence, which means that certain operations take precedence over other operations. Multiplication and division, for example, take precedence over addition and subtraction. Two plus five times three is seventeen, not twenty-one.

Example

Result

$x = 2; $y = 5;

Scalar variable ‘x’ is now ‘2’ and ‘y’ is ‘5’

$z = $x + $y;

‘z’ is now ‘7’.

$a = $z - $y;

‘a’ is now ‘2’

$b = $y * $x;

‘b’ is now ‘10’

$c = $z/$a;

‘c’ is now ‘3.5’

$d = ($a + $b)*$c;

‘d’ is now ‘42’

Functions
Perl uses ‘functions’ in much the same way as any other programming language. The function has a name, and it takes ‘arguments’ in ‘parentheses’. The function is on the left, and the repository for the answer is on the right:

$a = sqrt($b);
print “The square root of $b is $a.\n”;

Look in the Perl man pages or reference guide for a complete listing of functions. Here are some common ones:

Function

Result

cos($number)

cosine of number

int($number)

the integer portion of number

sin($number)

sine of number

sqrt($number)

square root of number

ord($string)

the ascii value of the first character of string

index($string1,$string2,$number)

returns the position of string2 in string1, starting at character number

length($string)

the length in characters of string

substr($string,$number1,$number2)

the number2 characters in string from location number1

Structure
A program’s “structure” controls which program lines get used. The three basic structural items in Perl are the “if” statement, the “while” statement, and the “foreach” statement.

These statements all use a “comparison” to determine whether or not to execute other Perl statements. Structural statements can be nested, so that a “while” can be inside an “if” which is inside another “if” inside another “while”.

The comparison is always inside parentheses. Curly brackets determine which part of the Perl program are controlled by the structural statement.

If Else
An “if” statement can be as simple as
if (comparison) {
	do this!
}

An “if” can also contain an “else”. If the comparison is “true”, the first part is done. Otherwise, the second part is done:

if (comparison) {
	do this!
} else {
	do something else!
}

An “if” can also contain multiple “elsifs” which contain their own comparisons:

if (comparison) {
	do this!
} elsif (another comparison) {
	do that!
} elsif (yet another comparison) {
	do something!
}

Go ahead and try here:

$myName = $ARGV[0];
if ($myName eq "Jerry") {
	print "Welcome!\n";
} elsif ($myName eq "Steve") {
	print "Go away!\n";
} elsif ($myName) {
	print "Who are you really, $myName?\n";
} else {
	print "Who are you?\n";
}

You’ll notice at least two new items in this program. First, that “ARGV[0]” is an array. Don’t worry about it for now. All you need to know is that it is the first item on the command line. “ARGV[1]” would be the second, and so on.

In the third “elsif”, the comparison doesn’t compare with anything. If a comparison is nothing except a variable name, we are checking to see whether or not that variable exists at all. If you type nothing on the command line, “ARGV[0]” doesn't have anything in it, so “$myName” doesn’t have anything in it, either, and “($myName)” ends up being false. Otherwise, we know that “$myName” has something in it, we just don’t have a plan for it yet.

While
“While” is a loop. That means it keeps going from top to bottom and back again until some condition is false. That is, it keeps going as long as the condition is true. Text variables are true if they exist, numeric variables are true if they are not zero. Comparisons are true if they compare well. For example:
while (0) {
	print "The king is a fink.\n";
}

will never print, because 0 is never true. On the other hand,

while ($myName) {
	print "Hello, $myName.\n";
}

will print only if the variable “$myName” exists. And then, it will continue to print forever, because “$myName” will always exist. The following is slightly more useful:

#countdown from a user specified number
$Counter = $ARGV[0];
while ($Counter) {
	print "T-$Counter seconds...\n";
	$Counter--;
}
print "Boom!\n";

Two dashes after a variable name reduces that variable’s numeric value by one. You can also use two plusses to increase the variable’s value by one. What happens if the variable isn't a numeric variable? How would you fix it in the above program?

In general, you want your comparisons to be as robust as possible. Look for any conditions that could result in your loop going forever (called an “infinite loop”), and guard against it. In this case, replace the line “while ($Counter)” with “while ($Counter >= 0)”

#countdown from a user specified number
$Counter = $ARGV[0];
while ($Counter >= 0) {
	print "T-$Counter seconds...\n";
	$Counter--;
}
print "Boom!\n";
Foreach
“Foreach” is very useful for looping through arrays, which we have seen in passing. We’ll talk more about arrays later, but for now, know that the list of “command line arguments” is an array of scalar values.
foreach $variable (@array) {
	do something with $variable
}

Foreach loops once through itself for each value in the array. If there are four values in the array, the loop will happen four times. Each time through the loop, it resets the value of the scalar variable to next value in the array.

foreach $argument (@ARGV) {
	print "Merry Christmas, $argument!\n";
}

You can also use “foreach” to loop through a range of numbers.

foreach $Counter (1..10) {
	print "$Counter potato...\n";
}
print "Jump!\n";

About this Tutorial
This tutorial is written by Jerry Stratton and is published under the GNU Free Documentation License.

NASA Tech Briefs features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems. Authored by the engineers or scientists who did the work, the briefs span a wide array of fields, including electronics, physical sciences, materials, computer software, mechanics, machinery/automation, manufacturing/fabrication, mathematics/information sciences, and life sciences. NASA Tech Briefs also contains feature articles on successful NASA spinoffs, profiles of NASA tech transfer resources, news briefs, and application stories. Regular columns describe new patents, industry products, software, and literature.
 
Subscribe Free!

Home  |  News  |  Source Code  |  Tutorials  |  Components  |  Tools  |  Books  |  Free Magazines  |  Jobs  |  Gear  |  Hosting  |  Links
 
Copyright © 2000 - 2006 Code Beach  |    |  Privacy Policy
 
Free thumbnail preview by Thumbshots.org