오래전 이야기/Server

Beginning Perl

리눅스 엔지니어였던 2008. 9. 15. 18:50
Free2Code » articles » Programming » Perl » Beginning Perl

Beginning Perl

Beginning Perl

Originally written for E-programmer(E-programmer) by Link, but now converted to HTML for Axion-Network [now Free2Code] by Link.

TOC
1. Hello World!
2. Variables
3. Arrays
4. Looping
5. Comparing and Conditionals
6. User Input
7. Files
8. Directories
9. Hashes
10. Subroutines
11. External Commands
12. Substitution and Translation

1. Hello World!

#!/usr/bin/perl
print "Hello World!";


Above is a simple hello world program written in Perl. You will notice the first line is #!/usr/bin/perl This is the path to your Perl interpreter. If you are using ActiveState Perl under Windows, you probably don't need to include the path to your Perl interpreter because upon installation it puts the path to the interpreter in your PATH. If you are planning to run a Perl program under Unix, however, this should always be your first line.

The next line which reads print "Hello World!"; makes "Hello World!" appear on the screen (without the quotes). You should also notice that the line ends with a semicolon. Almost every line of code in a Perl program must end with a semicolon.

Now to run this program copy the code into a simple text editor like Notepad, if you are using Windows, or Pico, if you are using Unix, and save it with a .pl extension. If you are using Windows, you will have to go to a command prompt, change the directory to where you just saved the file, and then run it by typing the filename along with the .pl extension. If you are running Unix, at the command line type "perl " and then the file name along with the .pl extension. The program should output Hello World!

2. Variables

Variables, for those who don't know, hold values that can be changed at a later time in the program. In Perl, variables are preceded by a $ and then the variable name. For example, $name. The $ indicates that the variable 'name' is a scalar. That means that it can only hold one value. For example, $name = "Bob" , assigns the variable 'name' the value 'Bob'. Also notice that we had to enclose the value 'Bob' in quotes.

You can assign values to variables in other ways, too:

#!/usr/bin/perl
$number = 5 + 5;


The above code assigns $number the value of 10. Don't forget to also notice that we had to end that line with a semicolon also. You can also assign the values of other variables to a variable. For example, $number = $anothernumber .

While you are free to create your own variables, Perl provides some special variables. Among these is the default variable: $_. You can assign values to $_ just as you would any other variable. For example:

#!/usr/bin/perl
$_ = 5;
print;

The above code will print out '5'. Notice the line of code print; As you can see we do not have to type print $_ because if you don't specify a variable to print, Perl automatically assumes you want to print the default variable ?$_?

Another thing to note about variables is that when you use them in the print statement you can perform what is called variable interpolation. This happens if you include the variable in double quotes when using the print statement. Lets view an example to get a better understanding.

#!/usr/bin/perl
$age = 5;
print "I am $age years old";


This will output the following: I am 5 years old . Now if you were to type something like: print 'I am $age years old'; the output would be: I am $age years old . Notice how if you were to use single quotes, Perl would not perform variable interpolation.

3. Arrays

With scalar variables you can hold a single value. But what if you need to hold more than one value? You simply use an array. Just as scalar variables begin with $, arrays begin with @. Lets look at an example that creates an array and assigns it values.

#!/usr/bin/perl
@cities = ("New York", "Washington", "Jacksonville", "Atlanta");


The code above assigns the array 'cities' four values. Some important information to know about arrays is that each individual value is called an element. Individual elements are accessed by their index number. Also, index numbers begin at 0. So, lets say you want to access the first element of the array 'cities'. You would type $cities[0] . This would be 'New York'. Notice that when you access individual elements of an array you precede the array name with a $ instead of an @. Just remember that when you want one use $ and when you want many use @. Now lets look at printing elements in an array:

#!/usr/bin/perl
print @cities;

The above would output: New YorkWashingtonJacksonvilleAtlanta . If you were to type print "@cities"; then the output would be: New York Washington Jacksonville Atlanta.

There are many functions you can perform on arrays. The following will give you a brief description of some common array functions and an example:

push - This adds an element to the end of an array.
ex: push(@cities, "Hamburg");
@cities now contains New York, Washington, Jacksonville, Atlanta, and Hamburg

pop - This removes and returns the last element of an array.
ex: $lastcity = pop(@cities); @cities now contains New York, Washington, Jacksonville, and Atlanta and $lastcity = "Hamburg"

shift - This removes and returns the first element of an array.
ex: $firstcity = shift(@cities);
@cities now contains Washington, Jacksonville, and Atlanta and $firstcity = "New York"

unshift - This adds an element to the beginning of an array.
ex: unshift(@cities, "New York");
@cities now contains New York, Washington, Jacksonville, and Atlanta

split - This splits up a string and places it into an array
ex: $string = "How:Are:You";
     @words = split(/:/, $string);

The above is the same as doing @words = ("How", "Are", "You");
Notice that where you want to split the string is contained in the / /

splice - This allows you to delete elements in the middle of the array or add elements to the middle.
ex: splice(@words, 1, 2, "Is", "You");
The first argument in the parenthesis, @words, is the array which you want to splice. The next argument, 1, is the offset. This is the index number of the elements at which you want to begin splicing. The next number, 2, is the length. This specifies how many elements should be replaced. The last two arguments, "Is", "You", is what you want the elements you are replacing to be replaced with.
Now I said that you could also add items to the middle of an array with splice. To do this, just set the length to 0. Then what you want added will be included before the offset.
ex: splice(@words, 1, 0, "Is", "You");
The above does this: @words = ("How", "Is", "You", "Are", "You");

Perl also provides a special array. This array is @argv. This array holds any command line arguments. For example, lets say I have a Perl program called test.pl. Now when I run it, I could type perl test.pl 15. The '15' is an example of a command line argument. Here's an example to show you how you can manipulate these.

#!/usr/bin/perl
$number = shift(@argv);
$number = $number * 2;
print $number;

The above code takes the first element for '@argv' and puts it into the variable '$number'. Then, '$number' is multiplied by 2 and is finally printed on the screen. So if I entered 15 at the command line when executing my Perl program, the product that would be printed is 30.

4. Looping

Perl offers many types of loops. If you have ever done any C or C++ programming, the loops in Perl are very similar. There are many types of loops so I will go through each type briefly and give an example of each.

foreach - This is a loop that allows you to loop through the elements of an array.
ex: @words = ("The", "quick", "brown", "fox");
      foreach $word (@words)
      {
        print "$word ";
      }
The code above goes through each element of the array one by one. It assigns the value of each element to the variable $word. So the first time through the loop, $word is assigned 'The' and then it is printed on the screen. Next, $word is assigned 'quick' which is also printed out. This continues until the last element of the array.

for - The 'for' loop is just like the 'for' loop in C or C++.
ex: for ($x = 0; $x < 10; $x++)
      {
        print $x;
      }
The first argument in the 'for' loop is the initialization. You create a variable named 'x' and set it equal to 0. The next argument is the condition that keeps the loop going. This statement must be true to continue the loop. So in this case the loop will continue while x remains less than 10. The last argument increments 'x' by one. So after the body of the loop is executed, in this case print $x;, the loop goes back to the top to see if 'x' is still less than 10. If it is, 'x' increments and the body of the loop is executed again.

while - This loop executes while a certain condition is true.
ex: $x = 0;
      while ($x < 10)
      {
        print "$x is less than 10";
      }
The above will output: 0 is less than 10. Be warned, however, the above is just an example to demonstrate how to use a 'while' loop. The code above will continue repeating because 'x' is always going to be less than 10. If you get caught in a loop, try hit Ctrl-C or Ctrl-U.

do-while - This loop is used similarly to the 'while' loop except that with the 'while' loop, for the body of code to be executed the condition you are testing must be true first. With the 'do-while' loop, the body of code is executed first and the test is performed last.
ex: $x = 0;
      do
      {
        print $x;
      }
      while (x < 10)

5. Comparing and Conditionals

In Perl, different operators are used to compare numbers and strings. Below are the operators for comparing numbers:
> - Greater than
< - Less than
>= - Greater than or equal to
<= - Less than or equal to
!= - Not equal to
== - Equal to (Notice that you use double equal signs if you want to know if something is equal to something else. If you were to use just one equal sign, you would        be assigning a value to something. $x == $y is not the same as $x = $y)

Here are the operators for comparing strings:

eq - Equal to
le - Less than or equal to
ge - Greater than or equal to
ne - Not equal to

Now, these comparison operators are most useful in conditional statements. Conditional statements are in the form of If statement blocks. There are three forms of the 'If' statement:

If - This is an 'If' statement that tests a condition and executes a body of code if it is true but does not provide an alternative if it is false.
ex: $x = 5;
      if ($x == 5)
      {
        print "$x is 5";
      }
Here 'x' is equal to five so the block of code in the curly braces are executed. Notice that your condition goes in the parenthesis and the block of code to be executed is contained in curly braces.

If...Else - This allows you to test for a condition and provides a block of code to execute if the condition is true and a block of code to execute if the condition is false.
ex: $x = 5;
      if ($x == 4)
      {
        print $x;
      }
      else
      {
        print "$x is not 4";
      }
As you can see, the 'else' block of code will be executed because 'x' is not equal to 4.

If..Elsif..Else - This allows you to test for multiple conditions and provides an alternative if none of the conditions are met. Please also notice that there is no 'e' in 'elsif'. That is not a typo.
ex: $x = 5;
      if ($x == 4)
      {
        print $x;
      }
      elsif ($x == 5)
      {
        print "$x is 5";
      }
      else
      {
        print "$x is not 4 or 5";
      }
Here the condition for the 'elsif' is executed because 'x' does not equal 4, but it does equal 5. If 'x' were neither 4 nor 5, then the code inside the 'else' clause would be executed.

6. User Input

Perl also allows you to obtain input from the user. The following example asks the user to input a name and stores the user's input in the variable 'name'.

#!/usr/bin/perl
print "Please enter your name: ";
$name = <STDIN>;
print "Your name is $name";

As you can see, obtaining input from the user is quite simple. There are some things to watch out for, however. When the user hits ENTER after typing in their name, a newline character can sometimes be captured along with the name. To eliminate this, you should use chomp. 'Chomp' will automatically remove the last character in a variable only if it is a newline character. Here's an example.
ex: $name = <STDIN>;
      chomp($name);

Now that you know how to obtain user input, here is an example combining some of the techniques you have learned to prompt for a user name and password:

#!/usr/bin/perl
print "Please enter your name: ";
$name = <STDIN>;
chomp($name);
if ($name eq "Bob")
{
   print "Please enter your password: ";
   $passwd = <STDIN>;
   chomp($passwd);
   if ($passwd eq "XYZ")
   {
     print "Welcome Bob!";
   }
   else
   {
     print "You are not Bob!";
   }
}
else
{
   print "You are not authorized to run this program!";
}

One important factor I should bring up is that Perl is case sensitive. In other words, if I ran this program and entered 'BOB' as the username, I would get the message: You are not authorized to run this program!

7. Files

Perl provides many ways to deal with files. Opening a file is very simple and has the format: open (FILEHANDLE, pathtofile). The 'FILEHANDLE' is the name you use to refer to the file. The path to the file can be the actual path in quotation marks or it can be a variable which holds the path to the file. For example, if I wanted to open a file called Test.txt in 'My Documents' (using a Windows box of course) I could do:

#!/usr/bin/perl
open (Test, "c:my documentstest.txt");

or:

#!/usr/bin/perl
$pathoffile = "c:my documentstest.txt";
open (Test, $pathoffile);

Notice in both cases, however, that I used double backslashes in my path. That is because backslashes are used in Perl for other special operations. So, I had to do what is called escaping. To escape a character, you must put a backslash followed by the character. So, to escape a backslash I had to do . This tells Perl I want to use the backslash as a normal character.

Whenever you open a file it is a good idea to include a die statement in case there is an error opening the file.
ex: open (Test, "c:my documentstest.txt") or die "Could not open the file";
This way if there is an error opening the file, your program will display an error message and will end without a problem. You should also note some other tools to use in Perl in case of an error with files. These tools are two more special variables in Perl. They are: $! and $ERRORNO. '$!' contains an error number and '$ERRORNO' contains the error message associated with the error number. So to get the error number you could do something like:

open (Test, $pathoffile) or die "Could not open the file: $!";

Now when you open a file like the above example, you automatically open the file for input. By doing this, you can read the contents of a file.
ex: open (Test, $pathoffile) or die "Could not open file: $!";
      while (<Test>)
      {
        print;
      }
The above reads the contents of a file and then prints it on the screen.

You can also open a file for output. When you open a file for output, several things can happen. First of all, if the file does not exist, the file will be created. Second of all, if the file contains any information, it is overwritten and replaced by what you add. Here is an example of opening a file for output and writing to it:

#!/usr/bin/perl
open (Test, ">/home/guest/test.txt") or die "Can't open $!";
print Test "Hello There!";

The code above creates a file called Test.txt and places 'Hello There!' inside of it. You can see that when you open a file for output, you add > before the file path. Also, to write to a file, you use the print statement followed by the filehandle and then what you want to put in the file.

You can also open a file for appending. This is where you add data to a file without overwritting any previous data already in the file. As with opening a file for output, if the file does not exist it is created. Here is another example:

#!/usr/bin/perl
open (Test, ">>/home/guest/test.txt") or die "Can't open $!";
print Test "Hello There!";


Very simple as you can see. You just add a >> before the filepath.

After opening a file for any type of operation, you should close it. This is done with the close statement.
ex: close (Test);

You can also delete files very easily:

$pathoffile = "/home/guest/test.txt";
unlink $pathoffile;

This deletes 'test.txt'.

Perl also has several file tests you can perform on files:

-e File exists
-d File is a directory
-s Size of file in bytes
-T File is a text file
-B File is a binary file

Here's an example of how to use them:

#!/usr/bin/perl
$pathoffile = "/home/guest/test.txt";
if (-e $pathoffile)
{
   print "File exists";
}

8. Directories

Besides working with files, Perl also allows you to work with directories. To open a directory, use the opendir function.
ex: opendir (Directory, "c:my documents") or die "Could not open directory!";
As you can see, it is identical to the open function for files.

Once the directory is open, you can read the contents of the directory into an array:

#!/usr/bin/perl
opendir (Directory, "c:my documents") or die "Cannot Open Directory";
@contents = readdir(Directory);
closedir(Directory);
foreach $content (@contents)
{
   print "$content ";
}

I should note that the ' ' is another escape character which starts a newline. But as you can see, the array '@contents' is assigned the contents of the directory by the readdir function. Also note that just like files, once you are done with them, you should close them. This is accomplished via the closedir function.

Here are some other useful functions that allow you to manipulate directories:

mkdir - Makes a directory. Has the format: mkdir (DirName, Mode). The mode argument is used to set permissions in Unix
rmdir - Removes a directory. Has the format: rmdir (DirName).
chdir - Change the current working directory. Format: chdir (DirName).
chroot - Used in Unix to change root directory for current process. Only Root can perform this. Format: chroot (DirName).

9. Hashes

Hashes are also known as associative arrays. Hashes allow you to associate scalars with one another through keys and values. Here is an example which shows how to create a hash associating keys and values.

#!/usr/bin/perl
%people = (CEO => 'Bob', Prez => 'Rich', VP => 'Tom');

You can see that there are some visible differences between hashes and arrays. First of all, you declare a hash with a % sign. Now, the keys are the values on the left of the =>. They would be CEO, Prez, VP. The values are Bob, Rich, and Tom.

Now lets say you want to access individual values of a hash. In a regular array you would do this by using the index number of the element. In hashes, you do this by referencing the keys.
ex: print $people{'CEO'};
This would print: Bob. Notice that once again, when you want one value, you use a $. Also notice that the key must be enclosed in { }.

You can also add keys and values to existing hashes:

$people{Boss} = 'John'

You can also delete keys and values:

delete $people{'Boss'}

You can also list all your keys and values by using the keys and values statements:

#!/usr/bin/perl
%people = (CEO => 'Bob', Prez => 'Rich', VP => 'Tom');
foreach $key (keys %people)
{
   print "$key ";
}
foreach $value (values %people)
{
   print "$value ";
}

In the first 'foreach' loop, we assign each key to the variable '$key' and then print it out. The next loop assigns each value to the variable '$value' and then prints it out.

Finally, Perl provides the each function which allows you to access both keys and values as the same time. The 'each' function returns a two element array consisting of a key and its value. The following code uses a 'while' loop to assign the key and value returned to two variables and then prints the results on the screen. It's worth noting that the 'each' function does not return the keys and values in any specific order.

#!/usr/bin/perl
%people = (CEO => 'Bob', Prez => 'Rich', VP => 'Tom');
while (($key,$value) = each(%people))
{
   print "$key is $value ";
}

10. Subroutines

What you have learned so far has been a way too code in a pretty much linear fashion. In Perl, just like any other programming language, you can break this cycle and jump to different segments of code by using subroutines. All subroutines are is a block of code which will be executed when called upon. Let's look at how to define a subroutine:

sub hello
{
   print "Hello!";
}

Very simple and easy. Just use the keyword sub and then create a unique name for the subroutine. Now lets see how to call a subroutine:

#!/usr/bin/perl
&hello;

sub hello
{
   print "Hello";
}

This results in the output: Hello. Notice to call a subroutine you use the name of the subroutine preceded by an &.

You can also return values from a subroutine by using the return function:

#!/usr/bin/perl
print "My program says: ", &hello();

sub hello
{
   return ("Hi There");
}

This will result in the output: My program says: Hi There.

11. External Commands

There is more than one way to run external processes in Perl. I will show you the two most useful in my opinion.

system - The system command runs an external process and then returns to your Perl program which then continues executing. The 'system' command returns a value in the special variable $? which you can use to determine if the external process was started or not. If the process was started successfully, '$?' will have a value of 0. If it is not 0, then divide the number by 256 to get the actual return value. Here is an example of using the system command:

#!/usr/bin/perl
system ("w");
print "Was the process successful: $?";

As you can see, the external program you want to run is included in parethesis and in quotations (in case you are wondering, the program I am running here is a Unix command that lists the users logged onto the system and what they are doing). Also remember that when the external process ends, your Perl program picks up where it left off.

` ` - The symbols you see to the left are called backticks. Backticks allow you to open up an external process but they return the output of the process. You can then manipulate this anyway you wish. Here's an example of using backticks and then printing out the output of the external process:

#!/usr/bin/perl
$info = `w`;
print $info;

This time instead of letting the external process print out its output to the screen, I captured the output into a variable and printed the contents of the variable.

12. Substitution and Translation

Perl gives you a lot of power in dealing with strings. Two useful features you may want to become familiar with, especially if you want to do CGI scripts, are substitution and translation. Substitution allows you to replace specified matches in a string. Here's an example:

#!/usr/bin/perl
$sentence = "Hello there. How are you doing";
$sentence =~ s/Hello/Hi/;

The line of code '$sentence =~ s/Hello/Hi/;' simply substitutes 'Hello' with 'Hi'. Now if '$sentence' contained 'HELLO' instead of 'Hello', the substitution would not have taken place. You can fix this quite simply by using this code: $sentence =~ s/Hello/Hi/i; You see, all I did was add an 'i' which means ignore case. Now lets say you want to find all occurrences of 'Hello' in the variable '$sentence' and replace them too. Just do this: $sentence =~ s/Hello/Hi/ig; The 'g' means global and it will substitute all occurrences of 'Hello' with 'Hi'

Perl also gives you the ability to perform character by character translation:

#!/usr/bin/perl
$sentence = "1234";
$sentence =~ tr/1234/5678/;

This turns '1234' into '5678'.

Conclusion

Well that concludes this tutorial for now. I hope you learned something and I hope you continue to have an interest in Perl. If you have any questions, comments, or corrections, please e-mail me at link@e-programmer.net I can't guarantee that I will be able to respond but I will do my best. Thanks and good luck.

Related Articles

Follow-up Articles

  • No relevant articles found!

Article Information

  • Date added to database: Thu 01 Jan, 1970
  • Number of times read: 5862
  • Article rating: this article has not been rated.