Linux Mall - The Linux 
SuperStore!
Linux books, Linux CDs, Linux toys, you name it, they have it!

W W W . L I N U 
X D O T . O R G

Newbie's Linux Manual
Introduction to Perl
by Laurence Hunter
[ Home ] [ Contents ] [ Download*] [ Previous ] [ Next ]
* In Linux enter: unzip nlm.zip
Your First Program
- 1 -

Enter:

pico hello.pl

Note:

To identify all your Perl programs use a .pl file extension.

- 2 -

Enter the following program:


#!/usr/bin/perl print ("Hello Perl!\n");

...and press Ctrl+o to save it, and Ctrl+x to exit Pico.

- 3 -

To run the program you need to make the file executable. To do this, enter:

chmod +x hello.pl

Note:
You only need to make the file executable once. After that you just modify and run.

- 4 -

To run the program, enter:

./hello.pl

Note:

From now on I'll just say, "Enter this program:". I'll leave it to you to decide which text editor to use, and what to name the program. You'll also have the sense to realise that from now on, you: Enter the program; save and exit the editor; make the file executable; then run it.

Output From Program

Hello Perl!
Explanation of Program

1: #!/usr/bin/perl 2: 3: print ("Hello Perl!\n");

1: Must be the first line of all Perl programs. This tells Linux where to find the Perl interpreter (required to make sense of the program). Nothing else (not even a comment) is allowed on this line.

3: Displays the message Hello Perl!. print () is what's called a function. You give a function something, and it does something with it. In this case, we're giving the print () function: "Hello Perl!\n"

"Hello Perl!\n" is a string. The " " characters indicate the start and end of a string. The \n means, "now print a 'newline' character" (like pressing the Return key in a text editor).

A statement is one particular task or instruction (usually corresponding to a line of code).

A semi-colon (;) is added to the end of a statement to tell Perl it is the end of the statement.

Getting Interactive: Comments, Variables & Input

Enter the following program (ignoring the line numbers e.g. "1: "):


 1: #!/usr/bin/perl 2: 3: # Get two number from user, multiply them, 4: # and display the result. 5: 6: print ("Enter a number: "); 7: $first = <STDIN>; 8: 9: print ("Enter another number: "); 10: $second = <STDIN>; 11: 12: $result = $first * $second; 13: 14: print ("Result = $result\n"); # Display result.
Example Output From Program

Enter a number: 5 Enter another number: 3 Result = 15
Explanation of Program
Comments

Lines 3 and 4 are examples of comments. Anything after the comment character # is ignored by Perl -- but only on that line (which is why another comment character is used on line 4). Comments allow you to make notes throughout you program so that when you come back to the program 6 months from now you know what's going on. Line 14 demonstrates the fact that a comment can come after a statement.

Variables

Line 7 introduces the variable. The variable is the $first part of the command. A variable is used to store a value. You can name a variable anything you want so long as you stick to the following rules:

  • Must start with a dollar-sign ($).
  • The next character after the dollar-sign must be a letter from a-z or A-Z.

  • Anything after the first 2 characters mentioned above can only be a-z, A-Z, 0-9, or _ (the 'underline' character).

A variable can be as long as you want, and it's case-sensitive, meaning $first, $First, and $FIRST, are all different variables.

Standard Input

Line 7 also introduces something called standard input i.e. <STDIN>.

<STDIN> just means get the user to input something. So:

$first = <STDIN>;

...means, "Get input from the user and store it in the variable $first".

The Result

In line 12, $first is multiplied (*) by $second, and the result is stored in $result.

Line 14 then displays the result. When Perl sees $result contained inside a string, it replaces it with the value stored in $result before displaying the string.

if...elsif...else

The if, if...else, and if...else...elsif constructs allow Perl to make decisions. Here you can see the syntax for each:

if (expression is true) {
    do this
}

if (expression is true) {
    do this
} else {
    do this
}

if (expression is true) {
    do this
} elsif (expression is 
true) {
    do this
} elsif (expression is 
true) {
    do this
} else {
    do this
}
Note:

In the if...elsif...else construct you can have as many elsif () {} entries as you want.

An Example Program:

#!/usr/bin/perl print ("Enter a number from 1 to 3: "); $number = <STDIN>; if ($number == 1) { print ("You entered 1.\n"); } elsif ($number == 2) { print ("You entered 2.\n"); } elsif ($number == 3) { print ("You entered 3.\n"); } else { print ("Can't you follow simple instructions?\n"); }
Example Output From Program

Enter a number from 1 to 3: 3 You entered 3.
Explanation of Program

The only part that requires explaining is the 3 mentions of '=='. When you give a variable a value you say: $var = 5, but when you check if $var equals 5 you say: $var == 5. Think of it as = (equals) and == (is equal to). So:

$var = 5;
...reads as, "var equals 5",

...and:

if ($var == 5) {
...reads as, "if var is equal to 5".

The while Loop
while (expression is true) {
    do this
}
An Example Program:

1: #!/usr/bin/perl 2: 3: $num = 1; 4: 5: while ($num < 6) { 6: print ("$num\n"); 7: $num++; 8: }
Output From Program

1 2 3 4 5
Explanation of Program

5: The '<' means 'less than', so line 5 reads as, "while $num is less than 6".

7: This just means, "add 1 to $num".

The until Loop
until (expression is true) {
    do this
}
An Example Program:

The only difference between the following program and the last program's code is highlighted in blue, and both programs do the same thing (i.e. print the numbers 1 to 5); illustrating the fact that the while and until loop do pretty much the same thing.


1: #!/usr/bin/perl 2: 3: $num = 1; 4: 5: until ($num == 6) { 6: print ("$num\n"); 7: $num++; 8: }
Output From Program

1 2 3 4 5
Variables

In programming you get what's called datatypes: the types of information a variable can hold. The 3 fundamental datatypes of all programming languages are the integer (a whole number), the floating-point number (a number containing a decimal-point), and the string (text delimited by single or double quotes). Note that "42" and 42 are not the same datatype. The first is a string (indicated by the double-quotes), and the second is an integer.

In most programming languages you declare each variable before you use it, letting either the programming language's interpreter or compiler know what it's dealing with each time it encounters a variable. The advantage to being forced to declare a variable beforehand is that it makes programs easier to debug (fix errors), because the interpreter or compiler will almost always, point the errors out to you. The most common error being a typo in an instance of the variable's mention. This approach makes the programming language a strong-typed language, suited to the beginner, large programs, and those prone to typos.

Perl on the other-hand is weak-typed, meaning variables aren't declared and can hold one type of information e.g. a integer, and then swap to holding another type of information e.g. a string, if and when needed. Strong-typed languages can also do this, but it involves calling on functions which often won't work in certain circumstances and substantial amounts of slap-dash code is required and/or a certain amount of ingenuity.

For the disciplined programmer, wanting flexible, elegant programs, weak-typed languages outshine strong-typed languages.

With all that being said, here are the many different values a Perl variable can hold:

  42          integer
 -42          " " (showing the minus-sign in use)
  42.1        floating-point number
 -42.1        " " (again showing the minus-sign in use)
   4.2e+1     example of an exponential number
 "Laurence"   string
0x2A          42 in hexadecimal (base 16)
 052          42 in octal (base 8)
Note:

Don't panic if you've never come across hexadecimal or octal notation. They're rarely needed and easily learnt at a later date. Just remember, that in Perl, a hexadecimal number begins with 0x (zero x) and an octal number begins with a 0 (zero) (clearly though 0.42 is not an octal number since octal numbers (and hexadecimal numbers) can't contain a floating-point.

Exponent Explained

An exponent can be represented by an e or E, followed by an optional plus-sign or a minus sign, followed by a 1, 2 or 3 digit number. If a plus-sign is used then the left number is multiplied by 10 - the number of times of the number on the right. If a minus-sign is used then the left number is divided by 10 - the number of times of the number on the right. Here are some examples:

1.2e+0   = 1.2
1.2e+1   = 12  (1.2 x 10)
1.2e+2   = 120 (1.2 x 10 x 10)
1.2e2    = same as above (with optional plus-sign missing)

1.2e-0   = 1.2
1.2e-1   = 0.12  (1.2 / 10)
1.2e-2   = 0.012 (1.2 / 10 / 10)
Escape Sequences

So far you've only used the most common escape sequence, \n. The following is a list of every escape sequence available for use inside a double-quoted (" ") string:

\aBell (beep)
\bBackspace
\cnThe Ctrl+n character
\eEscape
\EEnd the effect of \L, \U, and \Q
\fForm feed
\lLowercase next letter
\LLowercase all following letters
\nNewline
\rCarriage return
\QDo not look for special pattern characters (explained later)
\tTab
\uUppercase next letter
\UUppercase all following letters
\vVertical tab
\\Backslash
\"Double-quote
\$Dollar-sign
\nnnASCII code in octal.
\xnnASCII code in hexadecimal.
Note:

I doubt you'll ever use this, but just so you know: strings can also be delimited with single-quotes (' ') instead of double-quotes (" "). The difference being variable names are not replaced and escape sequences are just printed as text (except for \' to display a single-quote, and \\ to display a back-slash at the end of a string). So:

$name = "Laurence";
$message = "My name is $name.\n"; # remains "My name is Laurence."
$message = 'My name is $name.\n'; # becomes 'My name is $name.\n'
"2 apples" + 2 = 4!

There's over a 1001 clever things Perl can do. One of the simplest is to automatically change a string to a number when it make sense to, i.e. when a sum takes place. What happens is Perl moves along from the start of the string until it comes to a character that can't be used as part of an integer. This integer it has the calculated from the string becomes the variable's new value. If the character that can't be used as part of an integer is the first character of the string then the variable is given the value zero.

Arithmetic Operators
The following is a list of the arithmetic operators available in Perl:
+Addition
-Subtraction
*Multiplication
/Division
**Exponentiation
%Remainder/modulo
- Unary negation

The first four require no explaining, but the last three do:

Exponentiation ( x ** y )
The first number is multiplied by itself the number of times on the right. So:
$result = 2 ** 4; # $result = 16

...is the equivalent of:

$result = 2 * 2 * 2 * 2; # $result = 16

The number on the right is the base value, and the number on the right is the exponent. Here are some more examples:

$result = $n ** 2; # $result = $n * $n (i.e. $n squared)
$result = $n ** 3; # $result = $n * $n * $n (i.e. $n cubed)
$result = 99 ** 1; # $result = 99 (i.e. no multiplication)
$result = $b ** $e; # Both the base and exponent can be variables

You can even have negative and/or floating-point numbers for the base or exponent, but unless you plan to get into mathematics with Perl you'll find you never do so.

Remainder ( x % y )

Whilst you may never use the exponentiation (**) or unary negation (- n) operator, never underestimate the power of this operator. Some of the things it can do for you are simply amazing. What happens is the the first number is divided by the second, and the remainder is the result. If either number is a floating-point number it is rounded down before division takes place, so:

$result = 5 % 2;   # $result = 1 (5 / 2 = 2 remainder 1)
$result = 17 % 7;  # $result = 3 (17 / 7 = 14 remainder 3)
$result = 17.9 % 7.3; # Same as above since both numbers rounded down
$result = 6 % 0;   # Error because you can't divide by zero
$result = 6 % 0.999;  # Error because 0.999 is rounded down to zero
Unary Negation ( - x )

Whilst subtraction takes place with two numbers, unary negation only uses one (this is how Perl tells them apart even though they both use the - sign). All it does is to swap the sign of a number, so:

$result = - 42;  # $result = -42
$result = - -42; # $result = 42
Comparison Operators

The following are the 7 numeric comparison operators (indicated in red, and their names indicated in blue). Each operators compares two values and the result is either true or false (except for the final example).

$num < 42   # True if $num is less than 42
$num > 42   # True if $num is greater than 42
$num == 42  # True if $num is equal to 42
$num <= 42  # True if $num is less than or equal to 42
$num >= 42  # True if $num is greater than or equal to 42
$num != 42  # True if $num is not equal to 42
$num <=> 42 #  0 if $num is equal to 42
            #  1 if $num is greater than 42
            # -1 if $num is less than 42 ('compared to')

For every numeric comparison operator, there is an equivalent string comparison operator:

                           Result | Equiv. | Operation
                           -------+--------+----------
$result = "aaa" lt "bbb";  True   |   <    | Less than
$result = "aaa" gt "bbb";  False  |   >    | Greater than
$result = "aaa" eq "bbb";  False  |   ==   | Equal to
$result = "aaa" le "bbb";  True   |   <=   | Less than or equal to
$result = "aaa" ge "bbb";  False  |   >=   | Greater than or equal
$result = "aaa" ne "bbb";  True   |   !=   | Not equal to
$result = "aaa" cmp "bbb"; -1     |   <=>  | Compared to
To be continued...
Link
>> Perl.com -- The official Perl site.
[ Home ] [ Contents ] [ Download*] [ Previous ] [ Next ]
* In Linux enter: unzip nlm.zip
Homepage | The Last 5 Days | The Daily Linux News | The Linux Bits | Newbie's Linux Manual
The Best Linux Sites | Linux Book Reviews | A Windows Vendetta?
Diary of a Linux Newbie | Diary of an Open Source Newbie
The Linux Forum | Just For Fun
Amazon - The World's Biggest 
Bookstore!
4.7 million books, CDs, videos, and DVDs available to buy!
© MM Linuxdot.org | Webmaster | Manual's Copyright Terms