9. Perl Scripting

Although Perl might have started as a simple scripting language, it has grown into a robust language designed to tackle many different coding situations. There is a great deal to learn about Perl scripting (as well as the other programming languages discussed in this book), so don’t expect to become an expert overnight.

This chapter’s focus is to give you a firm understanding of how to write basic Perl scripts as well as provide an understanding of some of Perl’s more advanced features.

Basics of Perl Scripting

Perl is an unstructured language, which means white space within the program is typically ignored. For example, the following code prints “hi” to the screen:

print "hi ";

This could also be written as follows:1

print
"hi "
               ;

Note that a semicolon (;) is used to end a statement in Perl. Also note that the string represents a newline character. The print statement doesn’t naturally display a newline character, which makes for awkward output when multiple print statements are executed.

Comments in Perl begin with a pound sign character (#) and extend to the end of the line. For example:

# This is my first Perl script
print "hello "; #displays "hello"

Executing Perl Code

In most cases, you place Perl code within a file and execute the code as shown in the following:

[student@OCS ~]$ more hello.pl
print "hello ";
[student@OCS ~]$ perl hello.pl
hello

Typing the perl command before each execution can become annoying. To avoid that, make use of the #! line:

[student@OCS ~]$ more hello.pl
#!/bin/perl

print "hello ";
[student@OCS ~]$ chmod a+x hello.pl
[student@OCS ~]$ ./hello.pl
hello

You can also make use of a feature called the Perl debugger to execute Perl code interactively. Start by executing the following command: perl -d -e "1;"

The -d option enters the Perl debugger, which requires valid Perl code. The -e option means “execute the code provided on the command line.” The "1;" is valid Perl code; it doesn’t do anything but return the value of true. The result of this command should be a prompt like the one shown in Listing 9.1.


Listing 9.1 The interactive Perl debugger

[student@OCS ~]$ perl -d -e "1;"

Loading DB routines from perl5db.pl version 1.37
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1): 1;
DB<1>


At the DB<1 prompt you can type a Perl statement. Press the Enter key to execute the command. This enables you to test Perl code interactively.2 A couple of things to note:

Normally you need to place a ; character after each Perl statement. In the Perl debugger, the Enter key acts like a ; character. This means you don’t need a ; character at the end of a Perl statement within the debugger.

A few things don’t work in the Perl debugger (for example, a regular expression feature called backreferencing). However, almost everything that works in a Perl script also works in the interactive Perl debugger.

To exit the Perl debugger, type q and then press the ENTER key.

Additional Perl Documentation

Perl is a language that offers a large number of features, well beyond what is covered in this book (or any book for that matter). Fortunately, you can use a number of resources to get additional information about Perl:

perldoc.perl.org—Primary documentation website.

man perl—On UNIX and Linux systems, this command provides details about Perl.

perldoc—On all platforms, this command provides information about Perl.

The perldoc command is especially useful. Try running the following command: perldoc perl

Man page-like output appears that provides information about Perl. Included in this is a list of additional categories as shown in Figure 9.1.

Figure 9.1 Perl help topics

So, if you want to learn about Perl regular expressions, you could execute the perldoc perlrequick or perldoc perlretut commands. You can view dozens of different categories to learn more about Perl. As you learn more details about Perl while reading this book, consider diving into this documentation as well.

Variables and Values

Perl has three data structure types:

Scalar—A single data type that can be used as either a string or a number.

Array—An ordered list of scalar values, separated by commas.

Hash—A collection of unordered values that are referenced by using a scalar key. Also called an associate array.

Scalar variables are assigned and referenced using a $ character:

[student@localhost Desktop]$ perl -d -e "1;"

Loading DB routines from perl5db.pl version 1.37
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1): 1;
DB<1> $name="Bob"
DB<2> print $name
Bob


Note

To read data from the user (the keyboard), use the syntax $name=<STDIN>;


Several useful built-in Perl statements are used on scalars, including the statements shown in Listing 9.2.


Listing 9.2 Useful scalar statements

[student@localhost Desktop]$ perl -d -e "1;"

Loading DB routines from perl5db.pl version 1.37
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):  1;
  DB<1> $name=<STDIN>    #grabs data from keyboard and assigns to $name
Bob Smith
  DB<2> print $name      #prints "Bob Smith "; is a newline character
Bob Smith
  DB<3> chomp $name      #removes newline character at the end of string
  DB<4> print $name      #prints "Bob Smith" without newline character
Bob Smith
  DB<5> $name=lc ($name) #returns lower case "bob smith"
  DB<6> print $name
bob smith


Arrays are defined by creating variables that begin with an @ character:

DB<1> @colors=("red", "blue", "green")
DB<2> print "@colors"
red blue green

One confusing element of Perl is how you refer to individual elements in an array. Because those individual elements are scalar values, you use a $ character to display a single value. For example, to display the first element in an array you do something like the following:

DB<1> @colors=("red", "blue", "green")
DB<2> print $colors[0]
red

Important statements that manipulate arrays include the following:

push—Adds a new element to end of the array

unshift—Adds a new element to beginning of the array

pop—Removes (and returns) the last element of the array

shift—Removes (and returns) the first element of the array

splice—Add or remove one or more items in any part of the array

sort—Sorts elements in an array

You can perform an operation on each element in an array by using the foreach statement:

DB<1> @names=("Smith", "Jones", "Rothwell")
DB<2> foreach $person (@names) {print "Hello, Mr. $person ";}
Hello, Mr. Smith
Hello, Mr. Jones
Hello, Mr. Rothwell

Creating an array can be a pain because of all the quotes3 and commas. To make life easier, use the qw or qq statements:

  DB<1> @colors=qq(red blue green) #same as @colors=("red", "blue", "green")
  DB<2> @colors=qw(red blue green) #same as @colors=('red', 'blue', 'green')


Single versus Double Quotes

A double-quoted string allows for special characters whereas a single-quoted string does not. For example, the string "hello " means hello followed by a newline character ( = newline character). However, the string 'hello ' means hello .


A hash (called a dictionary in some other languages) provides a way to associate a key with a value. For example, to keep track of the favorite color of some people, you could use the following code:

  DB<1> %favorite=("Sue" => "blue", "Ted" => "green", "Nick" => "black")
  DB<2> print $favorite{"Ted"}
green

To see all the keys in a hash, use the keys command:

  DB<1> %favorite=("Sue" => "blue", "Ted" => "green", "Nick" => "black")
  DB<2> @people=keys(%favorite)
  DB<3> print "@people"
Ted Nick Sue


Special Variables

Several variables in Perl have a special meaning to the language. Typically these variables have cryptic names, such as $| or $_. For example, the $$ variable contains the process ID of the Perl process itself.

Some of these variables hold important information whereas others can be modified to change the behavior of how Perl functions. To see a description of all of these special variables, visit this URL: http://perldoc.perl.org/perlvar.html.


Flow Control

Perl supports many traditional flow control statements, including the if statement:4

$name=<STDIN>;
chomp $name;
if ($name eq "Tim")
    {
        print "Welcome, Tim!";
    }
elsif ($name eq "Bob")
    {
        print "Welcome, Bob!";
    }
else
    {
        print "Welcome, stranger!";
    }


elsif?

Be careful when writing Perl if statements because the “else if” statement is oddly spelled. It is a single word, with the second “e” missing!


Another common conditional statement is the while loop. With the while loop, a conditional check is performed and, if the condition is true, a block of code is executed. After the block of code is executed, the conditional check is performed again. See Listing 9.3 for an example.


Listing 9.3 The while loop

print "Enter your age: ";
$age=<STDIN>;
chomp $age;

#Make sure the user entered a proper age:
while ($age < 0)
{
   print "You can't be that young! ";
   print "Enter your age: ";
   $age=<STDIN>;
   chomp $age;
}
print "Thank you! ";


Additional flow control statements include the following:

untilOpposite of the while statement; executes a block of code as long as the conditional statement returns false.

unlessOpposite of the if statement; executes a block of code if the conditional statement is false.

forDesigned to perform a specific number of operations. Example:

for ($i=1; $i <=10; $i++) {#code}

foreachPerforms a block of code for each item of a list (array).


What about Switch or Case Statements?

Natively, Perl doesn’t have a switch or case statement. You might see older Perl code make use of multiple if/elsif statements or clever use of other conditional statements to simulate a switch statement. However, modern Perl provides a means to access a switch-like statement called given:

use feature "switch";

    given ($setting) {

        when (/^Code/) { $code = 1 }

        when (/^Test/) { $test = 1 }

        default       { $neither = 1 }

    }

The ^Code and ^Test are regular expressions and are covered later in this chapter.


Many languages support loop control statements such as break and continue. Perl also supports loop control statements, but they are called last and next instead of break and continue. You can use these loop controls statements in while, until for, and foreach loops.

Conditions

Perl supports a large variety of conditional expressions, including numeric comparison, string comparison, file testing operations, and regular expressions. You can also use the outcome of a Perl statement, but be aware that only a handful of built-in Perl statements return a natural true or false value.

Numeric comparisons include the following:

== Determine whether two numbers are equal to each other.

Example:

if ($age == 35) {}

!= Determine whether two numbers are not equal to each other.

Example:

if ($age != 35) {}

< Determine whether one number is less than another number.

Example:

if ($age < 35) {}

<= Determine whether one number is less than or equal to another number.

Example:

if ($age <= 35) {}

> Determine whether one number is greater than another number.

Example:

if ($age > 35) {}

>= Determine whether one number is greater than or equal to another number.

Example:

if ($age >= 35) {}

String comparisons include:

eq Determine whether two scalars are equal to each other.

Example:

if ($name eq “Bob”) {}

ne Determine whether two scalars are not equal to each other.

Example:

if ($name ne “Bob”) {}

lt Determine whether one scalar is less than another scalar.

Example:

if ($name lt “Bob”) {}

le Determine whether one scalar is less than or equal to another scalar.

Example:

if ($name le “Bob”) {}

gt Determine whether one scalar is greater than another scalar.

Example:

if ($name gt “Bob”) {}

ge Determine whether one scalar is greater than or equal to another scalar.

Example:

if ($name ge “Bob”) {}

File test operators include:5

-r Determine whether a file is readable. Example: if (-r “file”) {}

-w Determine whether a file is writable

-x Determine whether a file is executable

-T Determine whether a file contains text data

-e Determine whether a file exists

-f Determine whether a file exists and is a plain file

-d Determine whether a file exists and is a directory6

Regular expressions are a powerful feature in the Perl programming language. For example, you can see whether a pattern exists inside of a scalar variable by using the following code:

$name=<STDIN>;
if ($name =~ m/Bob/)
{
    print "yes"
}

When reading Perl code, you should be aware of a few regular expression features:

You can also perform substitution by using the following syntax:

$name =~ s/Bob/Ted

This replaced “Bob” with “Ted” in the $name variable.

Because matching is more common than substitution, you can drop the “m” when performing a match:

if ($name =~ /Bob/) {}

The $_variable is called the default variable and is often used by default. For example:

if ($_ =~ /Bob/) {} is the same as if (/Bob/) {}

Additional Features

In addition to reading from the keyboard (STDIN), you can open files and read directly from the files. This is referred to as opening a filehandle:7

open (DATA, "<file.txt");
$line=<DATA>;
close DATA;    #when finished, close the filehandle

You can also open a file and write to the file:

open (DATA, ">file.txt");
print DATA "This is output";
close DATA;  #when finished, close the filehandle

Another important feature in Perl is functions. To create a function, use the following syntax:

sub welcome
{
print "This is my function";
}

You can call a function by using the following syntax:

&welcome;

By default, any variable created in the main part of the program is available in a function. Additionally, any variable in a function is available in the main part of the program:

sub total
{
  $z=$x + $y;   #  $x and $y from main program
}

$x=10;
$y=5;
&total;
print $z;   #  $z from total subroutine

To make variables private, use the my statement:8

sub total
{
  my $z=$x + $y;   #  $x and $y are not set here
}

my $x=10;
my $y=5;
&total;
print $z;   #  $z is not set here

To reuse code in other programs, Perl has a feature called modules. Modules are like libraries in other languages. By calling a module, you will have access to functions that are shared by that module to your program.

For example, the following module call provides a function called cwd, which displays the current directory:

[student@OCS ~]$ perl -d -e "1;"

Loading DB routines from perl5db.pl version 1.37
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):  1;
  DB<1> use Cwd;
  DB<2> print cwd;
/home/student

A few things to note about modules:

By convention, module names begin with a capital letter. If you see a use statement that calls something that is in all lowercase characters, it isn’t a module, but rather another Perl feature called a pragma. Pragmas are used to change the default behavior of Perl and are well documented on perldoc.perl.org in the “Pragmas” section.

Perl comes with literally hundreds of built-in modules that enhance the functionality of the language greatly. These are all well documented on perldoc.perl.org in the “Modules” section.

Which functions are provided by the module depend on the developer who created the module. View the module documentation to determine which functions are provided.

You can create your own modules, but that topic is beyond the scope of this book. See perldoc.perl.org → language → perlmodlib for details.


Perl Humor

Larry Wall continues to oversee further development of Perl and serves as the benevolent dictator for life of the Perl project. His role in Perl is best conveyed by the so-called 2 Rules, taken from the official Perl documentation:

1. Larry is always by definition right about how Perl should behave. This means he has final veto power on the core functionality.

2. Larry is allowed to change his mind about any matter at a later date, regardless of whether he previously invoked Rule 1.

Got that? Larry is always right, even when he was wrong.


Summary

As a robust language, Perl has many additional features that were not covered in this chapter. However, the goal of this chapter was to provide you with enough information to determine whether Perl is a good language for you. If you liked the features and syntax of Perl, considering exploring the documentation sources provided to learn more about this flexible language.

1 Just because it could be written this way doesn’t mean you should write your code like this. As with all languages, you should try to write Perl code that is easy to read.

2 This method also provides a way for me to demonstrate Perl features without having to create a full Perl script.

3 Yes, you should use quotes around strings, even though it seems like you don’t need them in Perl. By default, Perl tries to use an unquoted value as a function and replaces the function call with the return value of the function. Placing quotes around the string prevents function calls.

4 Note the formatting of this code. Perl really doesn’t care about formatting, but someone reading your code will. There is no standard convention as to how you format your Perl code, but I suggest that you at least be consistent within the program that you are writing to make it easier to read.

5 Note that when you look at Perl documentation, file test operators are not listed in the section regarding operators, but rather under the “Functions” section. Look for –X under functions to learn more about file test operators.

6 I know the wording of this seems odd, but a directory is technically a file in Linux. It is a file that contains specific data, a list of files that are in the directory.

7 Several techniques actually exist for reading from a file. This is just one of them.

8 This is a very simplistic view of variable scope in Perl. In reality, Perl provides you with the capability to have a much more robust (and complex) scoping process.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.213.242