06-22-2008, 05:24 PM
Viral Titan's Beginner Guide to Perl
Table of Contents
I. Overview
II. Format and Print
III. Scalar Variables
IV. Logic, Math, Conditions
V. Arrays
VI. Loops
VII. Manipulating Files
VIII. Manipulating Directories
IX. Links
I. Overview
Perl is a programming language that was originally created by Larry Wall and released in 1987, as a Unix programming language that borrows things from other languages like C and Shell. A plus side is that it does not need to be compiled, but since it does not need to be compiled, you do need an interpreter installed in order to run the programs. Even though it has been around for some time, most computers do not have a perl interpreter on them by default. To get started, you will need to download ActivePerl (See Links) and install it. To make a perl program, you simply write the script in Notepad or I prefer Notepad++ (See Links), which supports a variety of programming languages and helps organize them. In order to run a perl program, you just write the program in the Notepad and then save it with a .pl extension. Then to run it, you need to go into the command prompt and type the directory you saved the program in, then type programname.pl to run it.
So if I saved a program called "First" in My Documents, you would type this in command prompt:
Then the program would run. Since most computers do not have perl interpreters installed on them, if you want to create a program that will work on other programs too, you need to get a perl converter like Perl2Exe (See Links). It will make an .exe program that works universally on all operating systems regardless if it has an interpreter.
II. Format and Print
Lets make our first perl program. We are going to use the "print" command to make the program print text onto the screen. Once you have ActivePerl installed, open notepad and type this program:
Save this as "perl.pl" and run it through command prompt. Then the command prompt returns the text "Hello". Notice how the line ends with a semicolon (;), every command should end in a semicolon. Also notice the \n in the after Hello, this character is used to signify a new line, it is the equivalent of hitting enter in a word document. Also, note the # with words after it. The # is perl's comment symbol, any text written after a # on the same line will not be read by the program, and is just to note things in development. Now try the following code.
Save and run this now. The quotation marks were changed from double quotes to single quotes, but when you run this program, the output is "Hello\n". This is because the double quotes tell the program to print the value of "Hello\n" which is just "Hello", while single quotes tell it to print whatever is contained in the quotes, that being "Hello\n".
III. Scalar Variables
Now I'll show you how to make your programs a little more interactive, we're going to put variables into them. Perl's scalar variable, unlike variables found in other programming languages, can hold any type of data. They can contain strings, integers, and characters all within the same variable type called a scalar. To declare a scalar, the syntax is $name. Try the following code.
This code simply declares the scalar "var1", then sets it equal to 'Hello\n'. Then the program prints the value of $var1, so the final output should be "Hello". Back to the double and single quotes, if were to change the second line from having double to single quotes, the program would output "$var1" on the screen instead. Next lest try a different program.
You may notice in this code, we did not give $name a value, but we set it equal to <>. The brackets are actually calling for another program but I will explain that in File Manipulation. If you set a scalar equal to <>, it will ask for the user's input and will set $name equal to whatever the user types followed by enter. So if I run the program it should look like:
Now take a look at this code below:
This code simply asks for your first name and then your last name, then outputs them together once you enter, and here is what it looks like:
Notice how they appeared on separate lines. Well we don't want this, we want it to just say "ViralTitan". To do this, we use the Chomp or Chop command.
What the chomp command does is remove the last character of a value if and only if it is a new line character (\n), unlike the Chop command that deletes the last character no matter what it is. But wait, we never had a new line character in our program, why does it do this? When the program asks for user input from the user, it records everything the user types until they press the enter key, including the enter key. So when I typed in my response, I actually was typing "Viral\n", since the enter key is the \n character. So the output of this program should be "ViralTitan". Look at the next code.
This code simply asks for a verb, then when one is typed, adds on "ing" to the end using the concatenation operator. By using this operator (.), you are able to add things onto scalars, so if I entered "jump" into the program, the output would be "jumping". There is a shorthand to this though. The shorthand is:
This line of code is the exact same thing as $verb= $verb . 'ing' and will return the same results. Look at the next line of code.
This code is pretty easy to understand, it is similar to the concatenation operator, except the output from this program will simply be "jumpjumpjump". I basically prints the scalar three times since you told it to with the "$verb x 3". There is shorthand to this operator as well:
This bit of code has the same effect as the code $verb= $verb x 3 except its easier to write. Using shorthands can make long programs look better and be more efficient.
IV. Logic and Math
Now I've taught you to generate and receive data, now I'll teach you to manipulate it. The most basic way of manipulating data is through simple math. These are the basic math operators.
Add: +
Subtract: -
Multiply: *
Divide: /
Percent: %
Exponent: **
So basically if I want to ask a number, multiply it by 3, and output the result, the program would look like this.
It's pretty self-explanatory how these work, the only confusing one may be the exponent, for which the syntax is $number ** $power, so 2 ** 3 would be 8.
Other operators you can use are the unary operators, they act buy very simply addition and subtraction. Here are the unary operators:
Make Positive: +$var
Make Negative: -$var
Add 1: ++$var
Subtract 1: --$var
Read the following code.
When run, the answer will be 6. It first takes and declares two scalars, equal to 4 and 10. Then it changes the 4 to -4. Then it adds -4 to 10 getting 6.
This code simply asks for a number, then once it receives it, it chomps the new line character off and then adds 1 to it using the ++ operator and outputs the results.
Now we know how to do math, lets take a look at logical statements. Here is a list of logic operators:
$var1 < $var2 This statement is true if $var1 is less than $var2.
$var1 > $var2 This statement is true if $var1 is greater than $var2.
$var1 >= $var2 This statement is true if $var1 is greater than or equal to $var2.
$var1 <= $var2 This statement is true if $var1 is less than or equal to $var2.
$var1 == $var2 This statement is true only if $var1 is equal to $var2.
It is pretty self explanatory, just remember when using ==, be sure to use a double equal sign since using a single one would set $var1 equal to $var2 instead of checking if it is already equal to it. This will be used a lot in conditional statements and loops, which I will cover later. Now you know the logical operators for numbers, but those will not work for characters and strings. Here are the logical operators for alphanumeric characters.
$var1 lt $var2 This statement is true if $var1 comes before $var2 in alphabetical order.
$var1 gt $var2 This statement is true if $var1 comes after $var2 in alphabetical order.
$var1 le $var2 This statement is true if $var1 comes before or is the same as $var2.
$var1 ge $var2 This statement is true if $var1 comes after or is the same as $var2.
$var1 eq $var2 This statement is true if $var1 is the same as $var2.
Some of these operations may take a long time to type out, but there is a shorthand version to these. Here are the shorthand to these operators.
$var += 2 is the same as $var= $var + 2
$var -= 2 is the same as $var= $var - 2
$var *= 2 is the same as $var= $var * 2
$var /= 2 is the same as $var= $var / 2
Using this logic is something you will have to use often in your programming. Look at the code below.
This is your first if statement. The basic syntax of an if statement is "if (condition) {action}". You simply start the line with if, then in parenthesis the conditional statement, in this case if the password entered is 'Admin', then a { to contain the body that has the action if the conditional statement is met. The next line or lines contains the action that will be executed, then the line below that contains another } to seal the body of the statement. But what if the person were to input a wrong password? For this we add an else to the statement.
When ran, this program will ask for the password, and if the password is 'Admin', it will tell you your authorized. If anything else is entered, it will tell you your unauthorized. If statements are essential in programming, make sure you understand them before moving on.
V. Arrays
Now scalars may be ideal for carrying single pieces of information, but when many variables are needed to store many pieces of information each, it may be tedious work to make and manage many scalars in a same program. For this we use arrays. An array can is like a long series of scalars all grouped together each with its own index as one single easy-to-manage variable. Arrays are declared with the @ symbol, such as @array.
This is an example of an array. This array contains three individual indices of information. Unlike other programming languages, the array may contain all types of information like characters, integers, and strings. Pieces of info in an array are called by their number in the array starting at "0". Look at the following code.
The output of this program would be:
The values are called and printed in this program. The value of $array[0] is equal to "one" since that is the first index of the array, and so on. Notice how the array is called with the @ symbol, but the individual parts of it are still called with the $ scalar symbol since they themselves are not arrays, but individual pieces of information that are still scalars. Indices can be called with negative integers as well. Look at the following code.
This program will return "three3" since that is the last value of the array. When labeling indices of an array, -1 is the last index, -2 is second to last, and so on.
Now you know how to create arrays and how their information works, but now I'll show you how to manipulate it. There are several functions to use to manipulate arrays.
push() This functions adds data onto the end of an array.
This will remove "C" from the array, so that the array will only contain "A" and "B".
unshift() This function adds on indices to the beginning of the array instead of push() which adds them to the end.
shift() This function removes the first index of the array.
splice() The splice function is used to add and delete indices from the middle of an array. The basic format of the array is splice(@array, start, length, additions). This may be difficult to understand at first but I will explain it.
When this is run, the array printed is 1XY45. When we told it to splice the array this is what happens. It sees @array and knows which array to splice. Then it sees 1 and knows to start splicing at position 1 (the second number since it starts at 0), and then it sees 2 and knows to delete two characters starting at 1, so the numbers 2 and 3 are deleted. Then it sees X and Y and puts them in that spot. If you just wanted to add indices to the middle of the array without deleting, you would set the length to "0", then it would not delete anything, it would just add whatever you told it to.
You know you can make your own array by just declaring it, but there is one important default array that is automatically in perl that will come in use. This default array is @ARGV. This array is automatically made of the arguments given when a perl program is run. Take a look at this simple program.
Now when you run this program, after the name add several arguments like C:\Location\program.pl 1 X B. Then when the program runs and prints the array, the output is 1XB. This @ARGV is a nice tool to have for simpler programs, but when compiled into an .exe, will have no use since it will not accept arguments at that point.
VI. Loops
When programming, you may find instances where you need to use the same bit of programming over and over again. If you were typing this all by hand, it may become very tedious work. For this we use loops. There are different types of loops to suit you various needs. The first one is the while loop.
What does this code do? It sets a scalar equal to 1, then it makes the loop. The while loops is set by simply printing while, then after goes the condition in () followed by the body in {}. The loop will keep executing the body so long as the condition remains true. So the loop will keep running as long as the value of $var is less than 5. The important part of the loops is that part $var++ which adds 1 to $var every time the loops repeats, therefore it will eventually be equal to 5 and the condition will no longer be true and the loop will stop. If this was not in here, we would have an infinite loop that would print "Viral is Awesome" on the screen infinitely. If you accidentally make an infinite loop, you can escape it by pressing Ctrl+C.
The next type of loop is the for loop. The basic syntax is "for (begin; condition; action) {body}". The loop begins by executing the "begin", then will execute the body, then checks to see if the condition is still true, if it is it will then execute the action, then body, and will continue this cycle until the condition is false. This program will print all the numbers 1 through 9.
The output is "123456789". It begins by printing 1, then it sees that $num is still less than 10 so it then executes $num++ and prints that, checks it, and keeps repeating that until $num is eventually equal to 10 and no longer less than it and then stops.
There’s also a loop called a foreach loop that you can use to move through arrays. Here is an example.
This will simply print "1ThreeToo4our" on the screen. You may think "Well why can't I just print @array?", well you can but this is to show you how to move through an array when performing more complex functions other than printing them. There is a shorthand to this thought.
This particular piece of code will give the same results as the previous bit. Whenever you program, make sure you use loops to make programs more efficient in doing their job.
VII. Manipulating Files
One very important thing to know how to do when programming in perl is how to access and manipulate other files on the computer. To start doing this, you'll need to learn about filehandles. Filehandles use the < > brackets. You already used these back when getting user input, and you were calling another program. You were actually calling the command prompt for the user input that you used. There are 3 basic filehandles you use. STDIN calls for user input, STDOUT is program output, and STDERR is error messages. Earlier when you made programs earlier containing $var= <>, you were using STDIN. Even though you did not type STDIN, perl automatically put that in the brackets when ran. Using $var= <STDIN> would have the same effect. In other cases, it automatically calls for the @ARGV variable instead of STDIN, you'll see those soon.
To use other files, you need to know how to open them. This is the basic opening command.
This bit of code opens the file "list.txt" and connects it to the filehandle "LIST". To read the contents of this file line by line you can simply use this code.
This program simply opens the list.txt file and uses a shorthand while loop to read the file line by line. There are also different ways to open files. By default it opens files as read only, but by adding operators into the program, we can open the files in different ways.
This is pretty self-explanatory, it just opens files in different modes depending on what you want the user of the program to be able to do with the open file. Closing a file is just as simple as opening it. Just type close(FILEHANDLE).
When opening files, sometimes a the program or a user will try to open a file that does not exist, or there is a problem with it. You need to add error messages into your program. The basic custom error message command is die().
This program attempts to open the file list.txt, but if it cannot find it, it gives an error message saying it does not exist. Now to enhance your error messages, you use the $! variable. Saying "print $!" will print the last error message, and saying "$ERRORNO" prints the error message that goes with the number. The basic error message numbers are:
2 No Such File
5 Data Error
13 Permission Denied
17 File Already Exists
28 Disk Drive is Full
This code will display "Does Not Exist: 2" if list.txt cannot be found. Another type of error message you can use is the warn() command. It is the same thing as the die() command, except it does not stop the program all together, it just tells the user something is wrong.
Once you've opened files, sometimes you need to move around in them. This is done with the seek command. The syntax is "seek(FILE, Bytes, Start). The FILE is the filehandle you want to move around in, Bytes is how many bytes you want to move forward, and start is where you want to start moving from. 0 starts at the beginning of the file, 1 starts at your current location of the file, and 2 starts at the end of the file. To check your current position in a file, use the tell command; "print tell(FILEHANDLE)" will tell your current location in an opened file.
The seek program will place you at a certain point in the file, but the sysread command will allow you to begin reading from a certain point in a file, measured in bytes, and then copy them to a variable. The syntax is sysread(FILE, Variable, Amount, Start).
This program opens list.txt, then copies 100 bytes of information starting at byte number 10 and assigns them to $list to print them on the screen. To read characters one by one in a file you use the getc(FILE) command. This will just read the next character in FILE.
To make your programs smarter, you will want to know how to test files. To test a file is -TESTNUMBER FILE. Here are the tests you can use on a file.
-B if file is binary
-d if file is directory
-e if file exists
-f if file is plain text
-r if file is readable
-s the size of file
-T if file is a text file
-w if file is write-able
-x if file is executable
-z if file is empty
A file test will evaluate to be true, if the file passes the test, otherwise it will return false.
This program just tests to see if the file list.txt exists. If it does it says File Exists, if not is says Could Not Find File. In addition to testing basic properties of a file, you can also test a variety of things about a file with the stat command. The syntax is (stat(FILE))[Index].
0 Device
1 Inode Number
2 File's Mode
3 Number of Links to File
4 File's Owner
5 File's Group ID
6 Device Identifier (Only Certain Files)
7 File Size
8 Last Time File was Used
9 Last Time File was Modified
10 Last Time File Status was Changed
11 Block Size of System
12 Number of Blocks the File is Using
This program basically opens list.txt and tells that last time it was modified. Another way to manipulate files is, of course, deleting them. If you do not want to delete the entire file, you can truncate it. Truncating deletes a certain number of bytes from the end of a file. Its pretty self-explanatory. The syntax is truncate(FILE, NumOfByte).
This program basically shortens the file LIST to 450 bytes. The only thing you need to remember is that the number you enter is how small you shorten it to, not how many you subtract off the end. To delete an entire file you simply use the unlink command.
This program is self-explanatory, it deletes list.txt. Using combinations of these file manipulations tools, you can accomplish many tasks you want to do with a single program.
VIII. Manipulating Directories
This is a relatively short section, but if you want to effectively manipulate files, you should know how to manipulate directories. The commands are pretty similar to file commands, but directories have a few commands exclusive to them. Since all the commands are pretty self explanatory, I am just going to list them below.
The last thing you should know to do is read a directory. It gives you a list of files in a directory in the form of an array.
This program will simply output all the files in the directory. Being able to manipulate directories and files is vital to making program that is smart.
IX. Links
1. ActivePerl
This program is needed to run .pl files on your computer. Download the standard distribution, install it, and you can then run perl programs through the command prompt.
2. Perl2Exe
This program is used to convert you perl programs into .exe files. It makes perl programs into executable files that can run on computers that do not have perl interpreters on them.
3. Notepad++
This is a personal favorite program of mine. It is similar to notepad but has many more features and benefits and supports many types of programming languages. Since perl doesn't have its on writing software, it makes your perl programs more organized as you write them.
-Viral Titan-
Table of Contents
I. Overview
II. Format and Print
III. Scalar Variables
IV. Logic, Math, Conditions
V. Arrays
VI. Loops
VII. Manipulating Files
VIII. Manipulating Directories
IX. Links
I. Overview
Perl is a programming language that was originally created by Larry Wall and released in 1987, as a Unix programming language that borrows things from other languages like C and Shell. A plus side is that it does not need to be compiled, but since it does not need to be compiled, you do need an interpreter installed in order to run the programs. Even though it has been around for some time, most computers do not have a perl interpreter on them by default. To get started, you will need to download ActivePerl (See Links) and install it. To make a perl program, you simply write the script in Notepad or I prefer Notepad++ (See Links), which supports a variety of programming languages and helps organize them. In order to run a perl program, you just write the program in the Notepad and then save it with a .pl extension. Then to run it, you need to go into the command prompt and type the directory you saved the program in, then type programname.pl to run it.
So if I saved a program called "First" in My Documents, you would type this in command prompt:
Code:
cd\Documents and Settings\%username%\My Documents\ <enter>
First.pl <enter>II. Format and Print
Lets make our first perl program. We are going to use the "print" command to make the program print text onto the screen. Once you have ActivePerl installed, open notepad and type this program:
Code:
print "Hello\n" ; #You can put whatever words you wish in place of HelloCode:
print 'Hello\n' ;III. Scalar Variables
Now I'll show you how to make your programs a little more interactive, we're going to put variables into them. Perl's scalar variable, unlike variables found in other programming languages, can hold any type of data. They can contain strings, integers, and characters all within the same variable type called a scalar. To declare a scalar, the syntax is $name. Try the following code.
Code:
$var1= 'Hello\n' ;
print "$var1" ;Code:
print 'What is your name?' ;
$name= <> ;
print "Hello $name" ;Code:
What is your name? Viral
Hello ViralCode:
print "Enter your first name: " ;
$first= <> ;
print "Enter your last name: " ;
$last= <> ;
print "$first" ;
print "$last" ;Code:
Enter your first name: Viral
Enter your last name: Titan
Viral
TitanCode:
print "Enter your first name: " ;
$first= <> ;
chomp($first)
print "Enter your last name: " ;
$last= <> ;
chomp($name)
print "$first" ;
print "$last" ;Code:
print "Please enter a verb: " ;
$verb= <> ;
$verb = $verb . 'ing';
print "$verb" ;Code:
$verb .= 'ing' ;Code:
print "Please enter a verb: " ;
$verb= <> ;
$verb = $verb x 3;
print $verb;Code:
$verb x= 3;IV. Logic and Math
Now I've taught you to generate and receive data, now I'll teach you to manipulate it. The most basic way of manipulating data is through simple math. These are the basic math operators.
Add: +
Subtract: -
Multiply: *
Divide: /
Percent: %
Exponent: **
So basically if I want to ask a number, multiply it by 3, and output the result, the program would look like this.
Code:
print "Enter a number: " ;
$var= <> ;
$var1= $var * 3;
print $var1;Other operators you can use are the unary operators, they act buy very simply addition and subtraction. Here are the unary operators:
Make Positive: +$var
Make Negative: -$var
Add 1: ++$var
Subtract 1: --$var
Read the following code.
Code:
$var1= 4;
$var2= 10;
$var3= -"$var";
$var4= $var2 + $var3;
print $var4;Code:
print "Enter a number: ";
$number= <> ;
chomp($number);
$number= ++$number;
print "This is your number plus 1: ";
print "$number";Now we know how to do math, lets take a look at logical statements. Here is a list of logic operators:
$var1 < $var2 This statement is true if $var1 is less than $var2.
$var1 > $var2 This statement is true if $var1 is greater than $var2.
$var1 >= $var2 This statement is true if $var1 is greater than or equal to $var2.
$var1 <= $var2 This statement is true if $var1 is less than or equal to $var2.
$var1 == $var2 This statement is true only if $var1 is equal to $var2.
It is pretty self explanatory, just remember when using ==, be sure to use a double equal sign since using a single one would set $var1 equal to $var2 instead of checking if it is already equal to it. This will be used a lot in conditional statements and loops, which I will cover later. Now you know the logical operators for numbers, but those will not work for characters and strings. Here are the logical operators for alphanumeric characters.
$var1 lt $var2 This statement is true if $var1 comes before $var2 in alphabetical order.
$var1 gt $var2 This statement is true if $var1 comes after $var2 in alphabetical order.
$var1 le $var2 This statement is true if $var1 comes before or is the same as $var2.
$var1 ge $var2 This statement is true if $var1 comes after or is the same as $var2.
$var1 eq $var2 This statement is true if $var1 is the same as $var2.
Some of these operations may take a long time to type out, but there is a shorthand version to these. Here are the shorthand to these operators.
$var += 2 is the same as $var= $var + 2
$var -= 2 is the same as $var= $var - 2
$var *= 2 is the same as $var= $var * 2
$var /= 2 is the same as $var= $var / 2
Using this logic is something you will have to use often in your programming. Look at the code below.
Code:
print "Password: ";
$pass= <> ;
chomp($pass);
if ( $pass eq 'Admin' ) {
print "Authorized\n";
}Code:
$pass= <> ;
chomp($pass);
if ( $pass eq 'Admin' ) {
print "Authorized\n";
}
else {
print "Incorrect Password" ;
}V. Arrays
Now scalars may be ideal for carrying single pieces of information, but when many variables are needed to store many pieces of information each, it may be tedious work to make and manage many scalars in a same program. For this we use arrays. An array can is like a long series of scalars all grouped together each with its own index as one single easy-to-manage variable. Arrays are declared with the @ symbol, such as @array.
Code:
@array=('one', '2', 'three3');Code:
@array=('one', '2', 'three3');
print $array[0];
print $array[1];
print $array[2];Code:
one2three3Code:
@array=('one', '2', 'three3');
print $array[-1];Now you know how to create arrays and how their information works, but now I'll show you how to manipulate it. There are several functions to use to manipulate arrays.
push() This functions adds data onto the end of an array.
Code:
@array=('A', 'B', 'C');
push( @array1, 'D' , 'E')
[code]
This will add "D" and "E" to the array in indices 3 and 4.
pop() This function removes the last index of the array.
[code]
@array=('A', 'B', 'C');
pop(@array);unshift() This function adds on indices to the beginning of the array instead of push() which adds them to the end.
shift() This function removes the first index of the array.
splice() The splice function is used to add and delete indices from the middle of an array. The basic format of the array is splice(@array, start, length, additions). This may be difficult to understand at first but I will explain it.
Code:
@array=('1','2','3','4','5');
splice(@array,1,2,'X','Y');
print @array;You know you can make your own array by just declaring it, but there is one important default array that is automatically in perl that will come in use. This default array is @ARGV. This array is automatically made of the arguments given when a perl program is run. Take a look at this simple program.
Code:
print @ARGV;VI. Loops
When programming, you may find instances where you need to use the same bit of programming over and over again. If you were typing this all by hand, it may become very tedious work. For this we use loops. There are different types of loops to suit you various needs. The first one is the while loop.
Code:
$var='1';
while ($var < 5) {
print "Viral is Awesome\n";
$var++ ;
}The next type of loop is the for loop. The basic syntax is "for (begin; condition; action) {body}". The loop begins by executing the "begin", then will execute the body, then checks to see if the condition is still true, if it is it will then execute the action, then body, and will continue this cycle until the condition is false. This program will print all the numbers 1 through 9.
Code:
for($num= '1' ; $num < 10 ; $num++) {
print $num;
}There’s also a loop called a foreach loop that you can use to move through arrays. Here is an example.
Code:
@array= ('1','Three','Too','4our');
foreach $array(@array) {
print $array;
}Code:
@array= ('1','Three','Too','4our');
foreach(@array){print;}VII. Manipulating Files
One very important thing to know how to do when programming in perl is how to access and manipulate other files on the computer. To start doing this, you'll need to learn about filehandles. Filehandles use the < > brackets. You already used these back when getting user input, and you were calling another program. You were actually calling the command prompt for the user input that you used. There are 3 basic filehandles you use. STDIN calls for user input, STDOUT is program output, and STDERR is error messages. Earlier when you made programs earlier containing $var= <>, you were using STDIN. Even though you did not type STDIN, perl automatically put that in the brackets when ran. Using $var= <STDIN> would have the same effect. In other cases, it automatically calls for the @ARGV variable instead of STDIN, you'll see those soon.
To use other files, you need to know how to open them. This is the basic opening command.
Code:
open(LIST, "list.txt");Code:
open(LIST, "list.txt");
while (<LISTS>) {
print;
}Code:
Operators are added right before the file name inside the quotes like this : open (LIST, ">>list.txt"). Here are a list of operators.
< File is read only.
> File is opend for writing only.
>> File is opened for appending only.
+> File is opened for reading and writing.
- Stand for STDIN
>- Stand for STDOUTCode:
open(LIST, "list.txt");
close(LIST);Code:
open (LIST, "list.txt") or die "Does not exist."2 No Such File
5 Data Error
13 Permission Denied
17 File Already Exists
28 Disk Drive is Full
Code:
open (LIST, "list.txt") or die "Does Not Exist: $!"This code will display "Does Not Exist: 2" if list.txt cannot be found. Another type of error message you can use is the warn() command. It is the same thing as the die() command, except it does not stop the program all together, it just tells the user something is wrong.
Once you've opened files, sometimes you need to move around in them. This is done with the seek command. The syntax is "seek(FILE, Bytes, Start). The FILE is the filehandle you want to move around in, Bytes is how many bytes you want to move forward, and start is where you want to start moving from. 0 starts at the beginning of the file, 1 starts at your current location of the file, and 2 starts at the end of the file. To check your current position in a file, use the tell command; "print tell(FILEHANDLE)" will tell your current location in an opened file.
The seek program will place you at a certain point in the file, but the sysread command will allow you to begin reading from a certain point in a file, measured in bytes, and then copy them to a variable. The syntax is sysread(FILE, Variable, Amount, Start).
Code:
open (LIST, "list.txt") or die "Does Not Exist: $!"
sysread(LIST, $list, 100, 10);
print $list;To make your programs smarter, you will want to know how to test files. To test a file is -TESTNUMBER FILE. Here are the tests you can use on a file.
-B if file is binary
-d if file is directory
-e if file exists
-f if file is plain text
-r if file is readable
-s the size of file
-T if file is a text file
-w if file is write-able
-x if file is executable
-z if file is empty
A file test will evaluate to be true, if the file passes the test, otherwise it will return false.
Code:
if (-e "list.txt") {
print "File Exists";
}
else {
print "Could Not Find File";
}0 Device
1 Inode Number
2 File's Mode
3 Number of Links to File
4 File's Owner
5 File's Group ID
6 Device Identifier (Only Certain Files)
7 File Size
8 Last Time File was Used
9 Last Time File was Modified
10 Last Time File Status was Changed
11 Block Size of System
12 Number of Blocks the File is Using
Code:
open (LIST, "list.txt") or die "File Not Found";
$stat= (stat(LIST))[9];
print $stat;Code:
truncate(LIST, 450);Code:
unlink "list.txt";VIII. Manipulating Directories
This is a relatively short section, but if you want to effectively manipulate files, you should know how to manipulate directories. The commands are pretty similar to file commands, but directories have a few commands exclusive to them. Since all the commands are pretty self explanatory, I am just going to list them below.
Code:
opendir(HANDLE, NAME) - This opens a directory and then gives it a handle.
closedir(HANDLE) - This closes a directory.
chdir(DIR) - Moves to a directory.
chroot(DIR) - Changes the root directory.
mkdir(DIR) - Makes a directory.
rmdir(DIR) - Deletes a directory.
telldir(HANDLE) - Tells the location of a directory handle.
seekdir(HANDLE, POSITION) - Reads from a certiant point in a directory.
rewinddir(HANDLE) - Puts you at the top of the directory.Code:
open(DIR, "/Documents") or die "Directory does not exist: $!";
@files= readdir(DIR);
closedir(DIR);
foreach $file(@files) {
print "$file";
}IX. Links
1. ActivePerl
This program is needed to run .pl files on your computer. Download the standard distribution, install it, and you can then run perl programs through the command prompt.
2. Perl2Exe
This program is used to convert you perl programs into .exe files. It makes perl programs into executable files that can run on computers that do not have perl interpreters on them.
3. Notepad++
This is a personal favorite program of mine. It is similar to notepad but has many more features and benefits and supports many types of programming languages. Since perl doesn't have its on writing software, it makes your perl programs more organized as you write them.
-Viral Titan-


