perl prog-LokeshB

Embed Size (px)

Citation preview

  • 8/3/2019 perl prog-LokeshB

    1/29

    Using a variable in Perl isn't as bad as it seems. Basically, you just define the variable and then use it.However, there are some things you need to know.First, a regular variable in Perl is always preceeded by the $ sign. So, if you want a variable namedadrevenue, you would have to write it as:

    $adrevenue

    Number Values

    Now, we need to give this variable a value. This is often done when the variable is defined. To start, letsgive it a numerical value. To do this, we need to set the variable equal to a number using the = sign, andend the statement with a semicolon:$adrevenue=100;

    You can now use the variable inside your print statement to output the value of the $adrevenue variable:

    $adrevenue=100;print "The ad revenue for my site today is $adrevenue dollars.";

    This just prints the sentence:

    The ad revenue for my site today is 100 dollars.

    String Values

    To give a variable a string value (text, text with numbers), we need to surround the value using singlequotes or double quotes. There is a difference in using the single or double quotes though. If you use

    single quotes, your string is taken as-is:

    $my_stomach='full';print 'My stomach feels $my_stomach.';

    This gives $my_stomach a value of full, but because we used single quotes with our print statement, thevalue of the $my_stomach variable is not printed:

    My stomach feels $my_stomach.

    Since we used single quotes around the printed string, Perl sees the variable name as simply part of aliteral string and prints it as-is rather than using its value.

    The use of double quotes allows you to use other variables as part of the definition of a variable. It wouldnow recognize the $ sign as setting off another variable and not as part of the string. So, now you coulduse something like this:

    $my_stomach='full';$full_sentence="My stomach feels $my_stomach.";print "$full_sentence";

  • 8/3/2019 perl prog-LokeshB

    2/29

    Now, the value of $my_stomach is used as part of the $full_sentence variable.This can be very handy at times. Now, it would print the following sentence:

    My stomach feels full.

    Use Them

    Now, your Perl script can include some vairables (though they don't serve much purpose just yet). Here isa sample script using what we have so far:#!/usr/bin/perl

    $adrevenue=100;$my_stomach='full';$full_sentence="My stomach feels $my_stomach.";

    print "Content-type: text/html\n\n";print

  • 8/3/2019 perl prog-LokeshB

    3/29

    Arithmetic Operators

    These operators are used to perform mathematical calculations on numbers. Keep in mind though, theyare not used to combine strings. There are some special string operators for this. Note that theassignment operator does work both ways, we used it to assign values to variables in the last section.Here is the list:

    Operator Function

    + Addition

    - Subtraction, Negative Numbers, Unary Negation

    * Multiplication

    / Division

    % Modulus

    ** Exponent

    To use these, you will place them in your statements like a mathematical expression. So, if you want tostore the sum of two variables in a third variable, you would write something like this:

    $adrevenue=20;$sales=10;$total_revenue=$adrevenue+$sales;

    You can use the other arithmetic operators in the same way, it is quite similar to other programminglanguages.

    Assignment Operators

    We have already used the = sign as an assignment operator to assign values to a variable. You can alsouse the = sign with another arithmetic operator to perform a special type of assignment. You can precedethe = sign with the + operator, for example:$revenue+=10;

    What this does is create a shorthand for writing out the following statement:

    $revenue=$revenue+10;

    It takes the variable $revenue and assigns it the value of $revenue (itself) plus 10. So, if you had an initial

    value for $revenue set at 5:

    $revenue=5; $revenue=$revenue+10;

    After these statements, $revenue is 15. It added 10 to the value it had before the new assignment.

    The others work the same way, but perform the various different operations. Here a list of the arithmeticoperators we used above when we place them with the assignment operator:

  • 8/3/2019 perl prog-LokeshB

    4/29

    Operator Function

    = Normal Assignment

    += Add and Assign

    -= Subtract and Assign

    *= Multiply and Assign

    /= Divide and Assign

    %= Modulus and Assign

    **= Exponent and Assign

    Remember, these are used for the sake of typing less or cutting the file size of the code. You can writethe statements out the long way if it makes it more understandable when you read your code.

    Increment/DecrementAnother shorthand method is to use the increment and decrement operators, rather than writing outsomething like this:$revenue=$revenue+1;

    You can simply write something like this:

    $revenue++;

    However, using these operators you must remember that you could also write something like this:

    ++$revenue;

    If you place the ++ before the variable name, it the variable adds one to itself before it is used orevaluated. For example, if you write:

    $revenue=5;$total= ++$revenue + 10;

    The $revenue variable is incremented before it is used in the calculation, so it is changed to 6 before 10 isadded to it. Thus, $total turns out to be 16 here.

    If you want to increment the variable after it is used, you use the ++ after the variable name:

    $revenue=5;$total= $revenue++ + 10;

    This way $total is only 15 because $revenue is used before being incremented, so it stays at 5 for thisexpression. If you use $revenue again after this, it will have a value of 6.

    With that in mind, here is the short list of the two operators:

  • 8/3/2019 perl prog-LokeshB

    5/29

    Operator Function

    ++ Increment (Add 1)

    -- Decrement (Subtract 1)

    The -- operator works the same way as ++, but it subtracts one from the value of the variable (decrementsit).

    Adding Strings

    Like I mentioned at the beginning of this section, there are different operators for strings under certainconditions. If you want to put two strings together (also called concatenate), you will want to use the dotoperator. Unlike C and JavaScript (where it is used with objects), the dot operator in Perl concatenatestwo strings.For example, if you want to place two strings together, you could do this:

    $full_string="light" . "house";

    This would make $full_string have the value of lighthouse. This is more useful if you are using variablesfor this:

    $word1="light";$word2="house";$full_string=$word1 . $word2;print "If I had a $word1 and a $word2, would I be able to make a$full_string?";

    Yes, it prints out this silly little sentence:

    If I had a light and a house, would I be able to make a lighthouse?

    This can also be used with the assignment operator to do what we did with numbers earlier. In this case,it gives the string the value of itself put together with another string:

    $word1="light";$full_string=$word1 . "house";

    Of course, we again get the value of lighthouse for the $full_string variable. Here is the list for these twostring operators:

    Operator Function

    . Concatenate Strings

    .= Concatenate and Assign

    Well, that's enough for one section. In the next section, we'll pick up with operators for comparison andmore. Let's go on toPerl Operators: Part 2.

    http://www.pageresource.com/cgirec/ptut7.htmhttp://www.pageresource.com/cgirec/ptut7.htmhttp://www.pageresource.com/cgirec/ptut7.htmhttp://www.pageresource.com/cgirec/ptut7.htm
  • 8/3/2019 perl prog-LokeshB

    6/29

    After all of that information in the last section, you might think there couldn't be any more. Well, there aremore operators but these are a little more interesting.Numeric Comparison

    These operators are used to compare two numbers, but not to compare strings. We'll get to those next.These operators are typically used in some type ofconditional statementthat executes a block of code orinitiates a loop. We'll get to the conditional statements in the next section, but to introduce this we will usethe beginning of an if () condition. Before that, let's look at the list:

    Operator Function

    == Equal to

    != Not Equal to

    > Greater than

    < Less than

    >= Greater than or Equal to

  • 8/3/2019 perl prog-LokeshB

    7/29

    gt Greater than

    lt Less than

    ge Greater than or Equal to

    le Less than or Equal to

    Strings are equal if they are exactly the same. So, "cool" and "cool" are equal, but "cool" and "coolz" arenot. Here is a string equality example:

    $i_am="cool";if ($i_am eq "cool"){....more cool code....}

    The greater-than and less-than operators compare strings using alphabetical order. Here is a sample:

    $i_am="all right";if ($i_am lt "cool"){print "You are not very cool, dude.";}

    Logical Operators

    These are often used when you need to check more than one condition. Here they are:Operator Function

    && AND

    || OR

    ! NOT

    So, if you want to see if a number is less than or equal to 10, and also greater than zero:

    $number=5;if (($number 0)){...code....}

    Notice the nested parentheses. Since we are checking for two conditions, we want to be sure thecomparison is done first. Thus, they have their own sets of parentheses within the parentheses for the if ()condition. Afterward, it checks to see if both conditions are true. Again, more on the conditionals in thenext section.

    Well, that's it for the operators for now. In the next section, we'll pick up with conditional statements. Let'sgo on toConditional Statements.

    http://www.pageresource.com/cgirec/ptut8.htmhttp://www.pageresource.com/cgirec/ptut8.htmhttp://www.pageresource.com/cgirec/ptut8.htmhttp://www.pageresource.com/cgirec/ptut8.htm
  • 8/3/2019 perl prog-LokeshB

    8/29

    The if ConditionThe if condition lets you check to see if a statement is true using a comparison operator. If the statementis true, it executes a block of code between two curly braces { }. Otherwise, it will go on to the nextcommand after the braces. Here is a sample if statement:$gas_money=5;

    if ($gas_money < 10){print "You will not get much gas for less than 10 bucks!";}

    print "Gas is expensive.";

    This checks to see if the variable $gas_money is less than 10. If this is true, it executes the statementinside the braces, and then goes on. If not, it will go straight to the print statement after the braces. So,with $gas_money being 5, it prints this result:

    You will not get much gas for less than 10 bucks!Gas is expensive.

    If the $gas_money variable were equal to 20, it would skip the code inside the braces and just print thelast line:

    Gas is expensive.

    Using else and elsif

    You can also make the script do something if the "if" condition is not true. If you have just one otheroption, simply use an else statement after the if statement, like this:if ($gas_money < 10){print "You will not get much gas for less than 10 bucks!";}else{print "You have enough money for now.";}

    print "Gas is expensive.";

    Now, if $gas_money is less than 10, the program gives you:

    You will not get much gas for less than 10 bucks!Gas is expensive.

  • 8/3/2019 perl prog-LokeshB

    9/29

    However, if $gas_money is anything greater than 10, it will bypass the statement in the first set of bracesand execute the code within the else statement braces. It would print this:

    You have enough money for now.Gas is expensive.

    If you want to check for a couple of conditions, you can use elsif to do another check and leave the elsecode as a last resort. You can have as many elsif statements as you want, but keep them between the ifand the else statements. Here is a sample:

    if (($gas_money < 10) && ($gas_money > 0)){print "You will not get much gas for less than 10 bucks!";}elsif ($gas_money

  • 8/3/2019 perl prog-LokeshB

    10/29

    unless ($gas_money == 10){print "You need exact change. 10 bucks please.";}

    This shows the message every time unless $gas_money is actually equal to 10. It's a handy shortcut for a

    longer if/else statement under the right conditions.

    Well, that's it for now. Let's go on to:Using Loops.

    ow it is time to get into some more fun this section is on using arrays. An array is basically a way tostore a whole bunch of values under one name. These values usually have something in common, andthe array makes the values easier to access and manipulate especially if you are using loops.Define an Array

    Let's take a look at how an array is defined in Perl:

    @arrayname = ("element1", "element2");

    Notice that an array name begins with an "@" symbol. This is how Perl knows it is an array and notsomething else. You can have as many elements as you need, I just listed two above to keep fromrunning on. The elements can be numbers or strings depending on what you need. If you use plainnumbers, the string quotes wouldn't be needed. For example:

    @one_two_three = (1, 2, 3);

    This would define an array named @one_two_three with three elements: the numbers 1, 2, and 3. Sincethe elements are only numbers, they need no quotes around them. On the other hand, if you wanted anarray of string values, you'll need the quotes so the interpreter sees the elements as strings:

    @browser = ("NS", "IE", "Opera");

    This time we have an array named @browser with three string elements: NS, IE and Opera. The questionnow is how do we make use of these elements later?

    How to Access Array Elements

    Suppose we wanted to grab the element "IE" out of the browser array above. You'll notice "IE" is thesecond element in the array, but look at the code we will use to get it carefully:$browser[1]

    You'll see that we get the element by using a regular variable (the $ sign) with the same name as thearray (browser). Then we use brackets with a number to get to a certain element within the array. Eacharray is ordered, but not starting at the number one like we would like. Arrays instead begin ordering atthe number zero! So, the first element of an array is always accessed using:

    $arrayname[0]

    http://www.pageresource.com/cgirec/ptut9.htmhttp://www.pageresource.com/cgirec/ptut9.htmhttp://www.pageresource.com/cgirec/ptut9.htmhttp://www.pageresource.com/cgirec/ptut9.htm
  • 8/3/2019 perl prog-LokeshB

    11/29

    So, this is why we used $browser[1] to get "IE" above. It is the second element, but its list number is 1.So, be sure to remember this when working with arrays. They start the number list at zero, so be carefulwhen you try to get an element or you might have a hard time figuring out where things went wrong inyour script (believe me, I have done this a few times).

    In a similar way, we can get the other elements for the array and use them. Let's say we wanted to write a

    little sentence about the browsers. We could use the array elements as part of the sentence:

    print "I like to use $browser[0], $browser[1], and sometimes $browser[2].";

    Yes, a pretty simple sentence indeed but here is the result:

    I like to use NS, IE, and sometimes Opera.

    Great, but not much more useful to us than 3 variables. But if you use a loop, an array can be very usefuleither to save typing or to manipulate a set of similar values.

    Arrays and Loops

    This is where an array can be more powerful, if you want to print the three browser names you could nowuse a loop rather than a separate print line with variable names. This is really handy if the list is a longone, but to keep things short we'll stick to our three element browser array. The following could be used toprint the three browser names, one per line:@browser = ("NS", "IE", "Opera");

    print "My Favorite Browsers List:\n\n";

    foreach $browser (@browser){print "$browser\n";

    }

    Notice how we used the foreach loop we looked at in the last section. As you can see, it is very handywith arrays. It loops through enough times to grab each element in @browser and print it. Also, using theforeach loop, we didn't have to add the brackets to access the array element. You'll notice we just used$browser inside the loop. This is because the foreach loop knows which elements to grab all of them.So it gives back the next element in order each time.

    In the next section, we'll have even more fun with arrays. Until then, enjoy creating your own arrays!

    Well, that's it for now. Let's go on to:Manipulating Arrays.

    Now that you have seen the basics of arrays, you'll want to see how to change and manipulate an arrayor the elements of an array. The first thing we will look at is changing and adding elements.Changing & Adding Elements

    To change an array element, you can just access it with its list number and assign it a new value:

    http://www.pageresource.com/cgirec/ptut11.htmhttp://www.pageresource.com/cgirec/ptut11.htmhttp://www.pageresource.com/cgirec/ptut11.htmhttp://www.pageresource.com/cgirec/ptut11.htm
  • 8/3/2019 perl prog-LokeshB

    12/29

    @browser = ("NS", "IE", "Opera");$browser[2]="Mosaic";

    This changes the value of the element with the list number two (remember, arrays start counting at zero-so the element with the list number two is actually the third element). So, we changed "Opera" to"Mosaic", thus the array now contains "NS", "IE", and "Mosaic".

    Now, suppose we want to add a new element to the array. We can add a new element in the last positionby just assigning the next position a value. If it doesn't exist, it is added on to the end:

    @browser = ("NS", "IE", "Opera");$browser[3]="Mosaic";

    Now, the array has four elements: "NS", "IE", "Opera", and "Mosaic".

    Splice Function

    Using the splice function, you can delete or replace elements within the array. For instance, if you simply

    want to delete an element, you could write:@browser = ("NS", "IE", "Opera");splice(@browser, 1, 1);

    You'll see three arguments inside the () of the splice function above. The first one is just the name of thearray you want to splice. The second is the list number of the element where you wish to start the splice(starts counting at zero). The third is the number of elements you wish to splice. In this case, we just wantto splice one element. The code above deletes the element at list number 1, which is "IE" (NS is zero, IEis 1, Opera is 2). So now the array has only "NS" and "Opera".

    If you want to delete more than one element, change that third number to the number of elements youwish to delete. Let's say we want to get rid of both "NS" and "IE". We could write:

    @browser = ("NS", "IE", "Opera");splice(@browser, 0, 2);

    Now, it starts splicing at list number zero, and continues until it splices two elements in a row. Now all thatwill be left in the array is "Opera".

    You can also use splice to replace elements. You just need to list your replacement elements after yourother three arguments within the splice function. So, if we wanted to replace "IE" and "Opera" with"NeoPlanet" and "Mosaic", we would write it this way:

    @browser = ("NS", "IE", "Opera");

    splice(@browser, 1, 2, "NeoPlanet", "Mosaic");

    Now the array contains the elements "NS", "NeoPlanet", and "Mosaic". As you can see, the splicefunction can come in handy if you need to make large deletions or replacements.

    Unshift/Shift

  • 8/3/2019 perl prog-LokeshB

    13/29

    If you want to simply add or delete an element from the left side of an array (element zero), you can usethe unshift and shift functions. To add an element to the left side, you would use the unshift function andwrite something like this:@browser = ("NS", "IE", "Opera");unshift(@browser, "Mosaic");

    As you can see, the first argument tells you which array to operate on, and the second lets you specify anelement to be added to the array. So, "Mosaic" takes over position zero and the array now has the fourelements "Mosaic", "NS", "IE", and "Opera".

    To delete an element from the left side, you would use the shift function. All you have to do here is givethe array name as an argument, and the element on the left side is deleted:

    @browser = ("NS", "IE", "Opera");shift(@browser);

    Now, the array has only two elements: "IE" and "Opera".

    You can keep the value you deleted from the array by assigning the shift function to a variable:

    @browser = ("NS", "IE", "Opera");$old_first_element= shift(@browser);

    Now the array has only "IE" and "Opera", but you have the variable $old_first_element with the value of"NS" so you can make use of it after taking it from the array.

    Push/Pop

    These two functions are just like unshift and shift, except they add or delete from the right side of an array

    (the last position). So, if you want to add an element to the end of an array, you would use the pushfunction:@browser = ("NS", "IE", "Opera");push(@browser, "Mosaic");

    Now, you have an array with "NS", "IE", "Opera", and Mosaic".

    To delete from the right side, you would use the pop function:

    @browser = ("NS", "IE", "Opera");pop(@browser);

    Now you have an array with just "NS" and "IE".

    You can keep the value you deleted from the array by assigning the pop function to a variable:

    @browser = ("NS", "IE", "Opera");$last_element= pop(@browser);

  • 8/3/2019 perl prog-LokeshB

    14/29

    Now the array has only "NS" and "IE", but you have the variable $last_element with the value of "Opera"so you can make use of it after taking it from the array.

    Chop & Chomp

    If you want to take the last character of each element in an array and "chop it off", or delete it, you canuse the chop function. It would look something like this:@browser = ("NS4", "IE5", "Opera3");chop(@browser);

    This code would take the numbers off the end of each element, so we would be left with "NS", "IE" and"Opera".

    If you want to remove newline characters from the end of each array element, you can use the chompfunction. This comes in handy later when we are reading from a file, where we would need to chomp thenew line (\n) character from each line in a file. Here is a more simplified example for now:

    @browser = ("NS4\n", "IE5\n", "Opera3\n");chomp(@browser);

    This code takes off the \n characters from the end of each element, leaving us with NS4, IE5, andOpera3.

    Sort

    If you want to sort the elements of an array, this can come in handy. You can sort in ascending ordescending order with numbers or strings. Numbers will go by the size of the number, strings will go inalphabetical order.@browser = ("NS", "IE", "Opera");sort (ascend @browser);

    sub ascend{$a $b;}

    The sub from above is a subroutine, much like what is called a "function" in other languages. We willexplain that in more detail later. As you can see, the code above would sort in ascending order, so itwould sort our array in alphabetical order. So, we have: "IE", "NS", and "Opera" as the new order. If youwant it in reverse alphabetical order, you would use $b $a in place of the $a $b above. Youcould change the name of the subroutine to whatever you wish, just be sure you call the subroutine with

    the same name. This will make a bit more sense after we get to the section on subroutines and readingfrom files.

    Reverse

    You can reverse the order of the array elements with the reverse function. You would just write:

  • 8/3/2019 perl prog-LokeshB

    15/29

    @browser = ("NS", "IE", "Opera");reverse(@browser);

    Now, the order changes to "Opera", "IE", and "NS".

    Join

    You can create a flat file database from your array with the join function. Again, this is more useful if youare reading and writing form files. For now, what you will want to know is that it allows you to use adelimiter (a character of your choice) to separate array elements. The function creates a variable for eachelement, joined by your delimiter. So, if you want to place a colon (:) between each element, you wouldwrite:@browser = ("NS", "IE", "Opera");join(":", @browser);

    This would create something like this:

    NS:IE:Opera

    Split

    The split function is very handy when dealing with strings. It allows you to create an array of elements bysplitting a string every time a certain delimiter (a character of your choice) shows up within the string.Suppose we had the string:

    NS:IE:Opera

    Using the split function, we could create an array with the elements "NS", "IE", and "Opera" by splittingthe string on the colon delimiter (:). We could write:

    $browser_list="NS:IE:Opera";@browser= split(/:/, $browser_list);

    Notice in the split function that you place your delimiter between two forward slashes. You then place thestring you want to split as the second argument, in this case the string was the value of the $browser_listvariable. Setting it equal to @browser creates the @browser array from the split.

    Well, that should be enough to keep us all busy for a while. You can do a whole bunch of things witharrays, and we'll be using them extensively in later sections. So, have fun with what we have so far, we'llbe moving on soon!

    Well, that's it for now. Let's go on to:Associative Arrays.

    Associative arrays are yet another way to store variables in a group. Unlike a regular array, however, youget to use your own text strings to access elements in the array. Associative arrays are created with a setof key/value pairs. A key is a text string of your choice that will help you remember the value later. Thevalue, then, is the value of the variable you want to store.Define an Associative Array

    http://www.pageresource.com/cgirec/ptut12.htmhttp://www.pageresource.com/cgirec/ptut12.htmhttp://www.pageresource.com/cgirec/ptut12.htmhttp://www.pageresource.com/cgirec/ptut12.htm
  • 8/3/2019 perl prog-LokeshB

    16/29

    Let's take a look at how an associative array is created in Perl:

    %array_name = ('key1', 'value1', 'key2', 'value2');

    Of course, you can make it longer or shorter depending on your needs. Notice the percent (%) sign at thebeginning in front of the array name. This indicates that what follows is an associative array, so the

    interpreter knows to use the keys and values, rather than assign index numbers to each string. Let's takea look at an example:

    %our_friends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe');

    Here, you have a list of friends associated with keys for remembering them when you access the arraylater. So, your 'best' friend would be Don, you would have a 'good' friend named Robert, and your 'worst'friend is Joe (poor Joe).

    Access Your Elements

    To access an element, you use your key string in place of a number. Otherwise, it is like using a normal

    array. You define a plain variable with the array name followed by its key. So if we wanted to get thename of our 'good' friend, we would use:$our_friends{'good'}

    Notice the key string 'good', which will give us back our good friend Robert. These are often used bysetting the value to another variable, like this:

    $good_friend = $our_friends{'good'};print "I have a good friend named $good_friend.\n";

    Adding to the Array

    Like a regular array, you can add a value to an associative array by simply defining a new value in yourscript. In this case, you would define it using a new key string and a value:%our_friends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe');$our_friends{'cool'} = "Karen";

    This adds the key/value pair of 'cool' and 'Karen' to the %our_friends array.

    Deleting from the Array

    You can also delete a key/value pair from an associative array using the delete function, which is a littledifferent than the regular array. However, it is a fairly easy command to use, look at the example below:%our_friends = ('best', 'Don', 'good', 'Robert', 'worst', 'Joe');delete ($our_friends{'worst'});

    Now, your 'worst' friend Joe is deleted from the associative array. Again, poor Joe.

  • 8/3/2019 perl prog-LokeshB

    17/29

    Associative arrays are very handy when you are trying to get input from forms on a web page. Mostscripts that do this read the form values in as key/value pairs to an associative array, thus making it easyto use the values you need. We'll do a little more with this later when we discuss form input.

    Well, that's it for now. Let's go on to:Chop, Chomp, Length, and Substrings.

    There are a few functions to manipulate strings that we haven't covered yet, so this will cover these asthey may be useful later when we deal with strings even more. Let's take a look at the chop, chomp,length, and substring functions and see what they do.Chop & Chomp

    The chop function is used to "chop off" the last character of a string variable. It will remove that lastcharacter no matter what it is, so it should be used with caution. For example:

    memyselfyou

    If you had read the "me" line in and assigned it to a variable, say $who_am _I, the value you have for itshould be:

    me\n

    The chop command would look like this (assuming we assigned "me\n" to a variable named $who_am_I):

    chop ($who_am_I);

    Using the chop function in this case will remove the \n character. However, suppose we use it on the lastof the three:

    memyselfyou

    The "you" is the last piece of text in the file, and could be missing the newline \n character if it was, forinstance, typed into the file manually and the "Enter" key was not pressed afterward. If the chopcommand is used in such a case, it will remove the "u", which was not intended! So code such as:

    chop ($who_are_you);print "You are $who_are_you!";

    This would result in the viewer seeing "You are yo!" rather than the expected result. Thus, we will look at

    the chomp function.

    The chomp function will remove the last character of a string, but only if that character is an input recordseparator (the current value of $/ in Perl), which defaults to the newline (\n) character. This is often usedto remove the \n character when reading from a file. The chomp function is much safer than the chopfunction for this, as it will not remove the last character if it is not \n.

    Now if we run the chomp command on that last line instead, it won't remove the "u".

    http://www.pageresource.com/cgirec/ptut13.htmhttp://www.pageresource.com/cgirec/ptut13.htmhttp://www.pageresource.com/cgirec/ptut13.htmhttp://www.pageresource.com/cgirec/ptut13.htm
  • 8/3/2019 perl prog-LokeshB

    18/29

    chomp ($who_are_you);print "You are $who_are_you!";

    Now the viewer will see "You are you!" even if there was no \n character at the end of the "you" line.

    Remembering these commands later will be very helpful when you read from files and need a specific

    string value.

    Length

    The length function simply gives you back the number of characters in a string variable. This is handywhen you don't know the value of the variable but would like to know the number of characters it has. It isuseful with arrays, conditional statements, loops, and such things.So, if you had a variable named $ice and its value was the string "cold", you could get the length of thestring "cold" with the length function:

    $ice="cold";

    $length_ice = length ($ice);

    Since the string "cold" has 4 characters, the value of the $length_ice variable will be 4, and you can use itfor other calculations or conditions.

    Substring (substr)

    The substring function is a way to get a portion of a string value, rather than using the entire value. Thevalue can then be used in a loop or a conditional statement, or just for its own purposes. For this one, youwill probably want the general form of the function first. The function is usually set to a variable so that thevariable contains the value of the substring:$portion = substr($string_variable, start number, length);

    Your $string_variable will be the variable from which you wish to create the substring. The start number isthe character within the string from which you want to start your substring. Remember, though- the firstnumber in a string here is zero rather than 1, so be careful when you make the count. The length above isthe amount of characters you wish to take out of the string.

    So, if we had a variable named $ice with a value of "cold", but we wanted to get the last three charactersrather than the full string, we would write something like this:

    $ice="cold";$age = substr($ice, 1, 3);

    print "It sure is $ice out here today.";print "I wonder if I am $age enough to play in the snow?";

    Yes, the substring turns out to be "old". It starts at the second character (which is 1 since the string startswith zero), and uses the next 3 characters. This function can be quite handy when you are trying to getpart of a string later.

    Well, that's it for now. Let's go on to:Reading from Files.

    http://www.pageresource.com/cgirec/ptut14.htmhttp://www.pageresource.com/cgirec/ptut14.htmhttp://www.pageresource.com/cgirec/ptut14.htmhttp://www.pageresource.com/cgirec/ptut14.htm
  • 8/3/2019 perl prog-LokeshB

    19/29

    Reading from a file in Perl gives us a way to create "flat text file" databases. These can be useful, and arefairly easy to set up. The downside is that you need to deal with file permissions, and there is thepossibility of data being overwritten. However, as we get into it further we will try to discuss those issuesin more detail. First, let's take a look at how to get started.To Begin: Create a File

    Our first step is to create a file so we have something to read. Suppose we want to store a few prowrestler's names and some other data about them, like their crowd reaction and favorite moves. For this,we could put each wrestler on a line, and separate the wrestler's information using a separator character(delimiter). One that is often used for separation is the pipe symbol ( | ). We will use it here to separateour data. Here is what we want to store:

    Wrestler Name Crowd Reaction Favorite Move

    The Rock Cheer Rock Bottom

    Triple H Boo Pedigree

    Stone Cold Cheer Stone Cold Stunner

    Now, we can take this data and put it in a file in a similar way. We won't use the headings, just thewrestlers and their information:

    The Rock|Cheer|Rock BottomTriple H|Boo|PedigreeStone Cold|Cheer|Stone Cold Stunner

    Each wrestler has a new line for his information, and the information on each line is separated with thepipe symbol.

    Once it is ready, we can save it as some type of text file. We can use lots of extensions, such as .txt, .dat,

    or other things. However, if someone stumbles onto the file in their browser, they can easily read thecontents. One thing that helps a little is to give it the same extension as your executable CGI scripts. Thisway, the server tries to execute the file if it is called from a browser, and should return a permission erroror an internal server error. If your server executes files with the .cgi extension (ask your host, some use.pl or others instead), then save the file with that extension, like:

    wrestledata.cgi

    Once it is saved, be sure the file has the permissions set so it is readable (755 should be OK here, seetheCHMOD pagefor more). Once that is done, we need to make a script which will use it. For ease ofwriting and of having the right location for the file, we will assume the data file and script will be in thesame directory. If you choose to use separate directories, be sure to make those changes.

    Opening the File

    Within our script, we will want to read the data into our script. In order to do so, we must first open the file.We do this with a command like this:open(HANDLE, "FileName/Location");

    http://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htm
  • 8/3/2019 perl prog-LokeshB

    20/29

    The HANDLE above is something you will use to reference the file when you read from it and when youclose it. The FileName/Location is the actual location of the file. Since we will have them in the samedirectory, we can just use the filename. If you have it in another directory, use the server path to the file.Here is how we can open our file:

    open(DAT, "wrestledata.cgi");

    Of course, you may want to assign the filename to a variable, so you could change it later more easily ifyou need to:

    $data_file="wrestledata.cgi";open(DAT, $data_file);

    One last bit on the opening of the file. You may want to have an option to show an error if the file cannotbe opened. So, we can add the "die" option to print the error to standard output. What we will do is usethe open command, give the "or" option (two pipe symbols) and use the "die" routine as the option:

    $data_file="wrestledata.cgi";open(DAT, $data_file) || die("Could not open file!");

    Reading the File

    Now we are able to read from the open file. The easiest way to do this is to just assign the contents of thefile to an array:$data_file="wrestledata.cgi";open(DAT, $data_file) || die("Could not open file!");@raw_data=;

    This will take everything from the file and toss it into the @raw_data array. Notice the use of the DAThandle for reading, with the < and > around it. We can then use the array to grab the information later, sothat we can go ahead and close the file.

    Close the File!

    We have to be sure to remember to close the file when we are done with it, so we close it with the closecommand:close(DAT);

    Again, the DAT handle is used to reference the file and close it. So now we have:

    $data_file="wrestledata.cgi";open(DAT, $data_file) || die("Could not open file!");@raw_data=;close(DAT);

    This is enough to read in the data, but if we want to make use of it we will want to pull it out of the arrayand do something with it. For that, we should head on to the second part of this tutorial.

    Well, let's go on to:Reading Files 2: Using the Data.

    http://www.pageresource.com/cgirec/ptut14_1.htmhttp://www.pageresource.com/cgirec/ptut14_1.htmhttp://www.pageresource.com/cgirec/ptut14_1.htmhttp://www.pageresource.com/cgirec/ptut14_1.htm
  • 8/3/2019 perl prog-LokeshB

    21/29

    Create a File

    When you append a file, you simply add an extra line (or more) at the end of the file, after everything thatwas already in there. This is useful if you want to add information to a file but not delete other informationin it. Before you try this on any important information, you should create a test file to make sure thesecommands work properly. We will make a test file here which holds some web site information. Supposewe had a file that looked like this, let's call it "websites.cgi":PageResource|http://www.pageresource.com|TutorialsJavaScript City|http://www.javascriptcity.com|Scripts

    Appending

    Now suppose we want to add another site to the list. We can do that by appending the websites.cgi file.First, we open the file, like we did when we read from it:$sitedata="websites.cgi";open(DAT,">>$sitedata") || die("Cannot Open File");

    Notice that we have quotes around the command after the comma, plus we have the two greater thancharacters (>>) before the file to open variable. Having two of these indicates we want to append the file,rather than read or overwrite it.

    Now to append it, we basically send data to the file with the print command:

    print DAT "Mysite\|http://www.mysite.com\|My website\n";

    Notice that we follow print with the file handle DAT, then we include what to print between the quotemarks, just like a regular print command. Here, we want the information in the same format as the rest ofour file, so we put it in the same order. Also, we place the pipe symbols to separate the information, but

    we have to be sure to escape them with \ characters or it will make a mess. So, between each item wehave \| to make it print the pipe character. At the end, we also need to remember to place the \n characterat the end so that we have a new line set and added in.

    When we are done, we can close the file and it should now have the new information:

    $sitedata="websites.cgi";open(DAT,">>$sitedata") || die("Cannot Open File");print DAT "Mysite\|http://www.mysite.com\|My website\n";close(DAT);

    Of course, you can use variables in place of the straight data. The variable method is more useful if youhave read in data from elsewhere though. Here we don't gain much by it, other than it would be a littleclearer if we wanted to change the values of the variables later:

    $sitename="Mysite";$siteurl="http://www.mysite.com";$description="My website";$sitedata="websites.cgi";

    open(DAT,">>$sitedata") || die("Cannot Open File");

  • 8/3/2019 perl prog-LokeshB

    22/29

    print DAT "$sitename\|$siteurl\|$description\n";close(DAT);

    File Locking

    One thing that should be done for scripts that will have more than one user writing to them is toincorporate file locking so that only one person may write to the file at a time. Perl offers the flockcommand to do this (note that flock will not work with all file systems, so another method may need to beused to lock a file on such systems). To use flock, you will need to have a "use" statement in your code totell Perl to use the Fcntl module:use Fcntl;

    To make sure you can use the constants that go with the flock command, you will also want to add the:flock tag to the "use" statement:

    use Fcntl qw(:flock);

    Use of the flock command would look like this:

    flock(HANDLE, CONSTANT);

    The constants for the flock command are listed below:

    Value Purpose

    LOCK_SH Shared Lock - typically used when reading from a file

    LOCK_EX Exclusive Lock - typically used when writing to a file

    LOCK_NB

    Non-Blocking Lock - used if you do not want the script to stall if a

    lock is not obtained

    LOCK_UN Unlock - unlocks the file: can lead to data loss (see below)

    We will be using the LOCK_EX in this tutorial, as we are going to be writing to the file to add informationto the end of it.

    Unlocking the file with LOCK_UN is not usually recommended as the file will be unlocked automaticallywhen you close the file using the normal close() command. Unlocking the file before closing it couldpotentially lead to data loss, which is something we want to avoid!

    It should also be noted that flock only locks files from others trying to access it using flock. If you have

    another script writing to it in another way, it won't be locked out. Just be sure that if you write to the filethat all your scripts trying to access it also use the flock command.

    For our purposes, we will lock the file using LOCK_EX. The example below shows how this would beimplemented:

    use Fcntl qw(:flock);

    $sitename="Mysite";

  • 8/3/2019 perl prog-LokeshB

    23/29

    $siteurl="http://www.mysite.com";$description="My website";$sitedata="websites.cgi";

    open(DAT,">>$sitedata") || die("Cannot Open File");flock(DAT, LOCK_EX);print DAT "$sitename\|$siteurl\|$description\n";close(DAT);

    This locks the file right after it is opened. Once we have written to the data file, we close the data fileand this will also unlock the file.

    One other piece you may wish to add is the seek command. This is used in case the flock command waswaiting for someone else to write to the file, which may cause your data not be written in its intendedplace in the file. To use the seek command, you need to add the :seek tag to the "use" statement inaddition to the :flock tag.

    use Fcntl qw(:flock :seek);

    The seek command is used in the following manner:

    seek(HANDLE, OFFSET, LOCATION);

    The location can be set with one of these constants:

    Value Location

    SEEK_SET Beginning of the file

    SEEK_CUR Current position in the file

    SEEK_END End of the file

    The location can also be set with numbers: 0 for the beginning of the file, 1 for the current position in thefile, or 2 for the end of the file.

    The offset allows you to specify how many bytes from the location you would like to move. If you want tomove to the very beginning or end of the file, you would leave the offset at 0.

    For our purposes, we need to go to the end of the file for the append. Thus, we will use SEEK_END asour location with the offset at 0:

    use Fcntl qw(:flock :seek);

    $sitename="Mysite";$siteurl="http://www.mysite.com";$description="My website";$sitedata="websites.cgi";

    open(DAT,">>$sitedata") || die("Cannot Open File");flock(DAT, LOCK_EX);seek(DAT, 0, SEEK_END);print DAT "$sitename\|$siteurl\|$description\n";close(DAT);

  • 8/3/2019 perl prog-LokeshB

    24/29

    Now we open the file, lock the file, seek the end of the file, write to the file, and close the file... which willalso unlock it.

    Well, that's all for now, let's go on to:Writing to Files.

    The FileWriting to a file erases everything that was in the file previously and writes the new informationover it. Before you try this on any important information, you should create a test file to make surethese commands work properly. Also, back up your data first just in case. In the last section, we added a line to our "websites.cgi" file by appending the file. So now our file wouldhave three lines:

    PageResource|http://www.pageresource.com|TutorialsJavaScript City|http://www.javascriptcity.com|ScriptsMysite|http://www.mysite.com|My website

    So, what if we decided that we didn't want those sites anymore, but wanted to replace them with a newsite we found (ouch!). We could do it by opening the file for writing, which will overwrite the file contentswith whatever we put into it.

    Writing (Overwriting)

    We open the file for writing much like we have before, but this time we use just one > symbol before thefile variable, rather than the two we used for appending:open(DAT,">$sitedata") || die("Cannot Open File");

    After that, we just write in our new file contents and close the file (For information on the file lockingportion, see theprevious tutorial. You may also need to adjust the file permissions so that you can writeto the file. See theCHMOD pagefor more on that):

    use Fcntl qw(:flock :seek);

    $sitename="Supersite";$siteurl="http://www.supersite.com";$description="A Super Duper Site";$sitedata="websites.cgi";

    open(DAT,">$sitedata") || die("Cannot Open File");flock(DAT, LOCK_EX);seek(DAT, 0, SEEK_SET);

    print DAT "$sitename\|$siteurl\|$description\n";close(DAT);

    Now, the file would have only our new contents in it, and none of the old contents will remain:

    Supersite|http://www.supersite.com|A Super Duper Site

    Nice, but what if we just wanted to delete one of the lines from the file? We will still have to overwrite it,but with a little twist.

    http://www.pageresource.com/cgirec/ptut16.htmhttp://www.pageresource.com/cgirec/ptut16.htmhttp://www.pageresource.com/cgirec/ptut16.htmhttp://www.pageresource.com/cgirec/ptut15.htm#lockinghttp://www.pageresource.com/cgirec/ptut15.htm#lockinghttp://www.pageresource.com/cgirec/ptut15.htm#lockinghttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/chmod.htmhttp://www.pageresource.com/cgirec/ptut15.htm#lockinghttp://www.pageresource.com/cgirec/ptut16.htm
  • 8/3/2019 perl prog-LokeshB

    25/29

    Deleting One Line

    Deleting one line is a little more difficult, since there is no command for it directly. What we have to do isread the contents of the file to an array, splice the line we want to delete from the array, and write thecontents of the array back to the file. If we go back to our 3-line file at the beginning of this section, thiswill overwrite what we had (3 lines) with what we send back (2 lines). So, if we want to delete the secondline in the file, here is the code:use Fcntl qw(:flock :seek);

    $sitedata="websites.cgi";

    open(DAT, $sitedata) || die("Cannot Open File");@raw_data=;close(DAT);

    splice(@raw_data,1,1);

    open(DAT,">$sitedata") || die("Cannot Open File");

    flock(DAT, LOCK_EX);seek(DAT, 0, SEEK_SET);print DAT @raw_data;close(DAT);

    The first part you will remember from the reading files section, we read the file into an array. Then you willsee thesplicecommand. It says to take out the line with the array number of 1, and to do this for oneelement (line) in the array. Remember, an array starts counting at zero, so the first line of the file is zero,the second is 1, and the third line is 2. Since we wanted to remove the second line, we chose 1. The lastsection opens the file for writing and writes the contents of the array into the file, which overwrites it withonly our two remaining links.

    After that, the file should look like this:

    PageResource|http://www.pageresource.com|TutorialsMysite|http://www.mysite.com|My website

    Now that we have that, let's see how to just get rid of the file entirely:

    Deleting the File

    If we want to just delete a file for good and make it no longer exist, we can do that with a short command:unlink("file_location");

    We replace that with a filename to delete:

    unlink("filename.cgi");

    In the case of our file, we assigned the filename to a variable, so we can use the variable instead:

    $sitedata="websites.cgi";unlink($sitedata);

    http://www.pageresource.com/cgirec/ptut11.htm#splicehttp://www.pageresource.com/cgirec/ptut11.htm#splicehttp://www.pageresource.com/cgirec/ptut11.htm#splicehttp://www.pageresource.com/cgirec/ptut11.htm#splice
  • 8/3/2019 perl prog-LokeshB

    26/29

    Just remember, the file is gone afterward, so you might want to keep a backup if you write a script fordata you may need again.

    So, that takes care of that, just remember to be careful with these as they overwrite or delete data andfiles entirely. Better to keep some backups and be on the safe side than to lose data you need (I've doneit a few times, and wasn't a happy camper!).

    Well, that's all for now, let's go on to:File Checks.

    There are some short expressions in Perl that allow you to test files, which is handy if you want to checkwhat a file allows before using it, or if it exists at all. We'll look at a few of the common tests in thissection.Existence

    To see if a file exists before using it, we can use:

    if (-e "filename.cgi")

    {#proceed with your code}

    The -e part is the existence test. After that we have a space, followed by the file we want to test. As in theother sections, we could also use a variable to hold the file name:

    $neededfile="myfile.cgi";if (-e $neededfile){#proceed with your code}

    Now, you can do something based on whether or not the file is there. If it is not, you can give an errorpage or move on to something else.

    Two other existence tests you can use may help if you need to know whether or not the file has anythingin it:

    File exists, has a size of zero: -zFile exists, has non-zero size: -s

    Readable, Writable, or Executable

    To see if the file is allowed to be read, written to, or executed we can use these:

    Readable: -rWritable: -wExecutable: -x

    So, if we want to check whether we can read a file before we try to open it, we could do this:

    http://www.pageresource.com/cgirec/ptut17.htmhttp://www.pageresource.com/cgirec/ptut17.htmhttp://www.pageresource.com/cgirec/ptut17.htmhttp://www.pageresource.com/cgirec/ptut17.htm
  • 8/3/2019 perl prog-LokeshB

    27/29

    $readfile="myfile.cgi";if (-r $readfile){#proceed with your code}

    The same goes for the writable and executable tests. These can be a handy way to keep from trying towrite to files that don't have write permissions, and various other things.

    Text or Binary

    You can test the file to see if it is text or if it is binary using these:Text File: -TBinary File: -B

    They work the same way as the others as well.

    Multiple Tests

    You can test for two or more things at a time using the "and" (&&) or the "or" ( || ) operators. So, if youwant to know if a file exists and is readable before opening it, you could do this:$readfile="myfile.cgi";if ( (-e $readfile) && (-r $readfile) ){#proceed with your code}

    File tests are helpful in applications that make use of files often in the code. Using these can help avoid

    errors, or alert you to an error that needs to be fixed (a required file not able to be read, for instance).Well, have fun testing those files!

    Well, that's all for now, let's go on to:Reading Directories.

    Now that we have made use of files in various ways, seeing how to open and read the contents of adirectory is the next step. Let's begin by seeing how to open a directory:Open a Directory

    Opening a directory is very much like opening a file. Suppose you want to open the "images" directory,which on your server has the path "/home/yourname/www/images/". You would do it like this:opendir(IMD, "/home/yourname/www/images/") || die("Cannot open directory");

    Like a file, we use a handle for the directory for later use. Then we call the path to the directory. As inother sections, we can make that path a variable and use it instead:

    $dirtoget="/home/yourname/www/images/";opendir(IMD, $dirtoget) || die("Cannot open directory");

    http://www.pageresource.com/cgirec/ptut18.htmhttp://www.pageresource.com/cgirec/ptut18.htmhttp://www.pageresource.com/cgirec/ptut18.htmhttp://www.pageresource.com/cgirec/ptut18.htm
  • 8/3/2019 perl prog-LokeshB

    28/29

    Now that it is open, we will want to read in the contents.

    Read the Contents

    The contents of the directory will be the file name of each file in the directory, including "." and ".." in the

    list. You'll want to toss those two out if you want just the files themselves. To read the directory, we canread the contents into an array and use the array:@thefiles= readdir(IMD);

    Use the handle you assigned to your directory in the readdir command. In our case, it is IMD. Now thecontents of the images directory are in the @thefiles array.

    Close the Directory

    Again, pretty much the same, just use closedir with the directory handle:closedir(IMD);

    The whole bit from open to close looks like this:

    $dirtoget="/home/yourname/www/images/";opendir(IMD, $dirtoget) || die("Cannot open directory");@thefiles= readdir(IMD);closedir(IMD);

    You can use this to list the files in a directory, for example. So, suppose we want to list all the image filesin the images directory. We could write something like this:

    #!/usr/bin/perl

    $dirtoget="/home/yourname/www/images/";opendir(IMD, $dirtoget) || die("Cannot open directory");@thefiles= readdir(IMD);closedir(IMD);

    print "Content-type: text/html\n\n";print "";

    foreach $f (@thefiles){unless ( ($f eq ".") || ($f eq "..") ){

    print "$f
    ";}}

    print "";

    Of course, the unless statement isn't the most elegant way to pull out the "." and ".." values, but we'll savethat for some sections on regular expressions. The rest is just printing each file name on a line. Theoutput would be something like this, though the number of file names could be more or less:

  • 8/3/2019 perl prog-LokeshB

    29/29

    logo.gifbutton.gifbanner.gifmypic.jpgbackground.jpg

    Of course, you can do more useful things with it, this can be a great way to grab the file names and makeuse of them for dispaly, if you wanted to display everything in your images directory without writing abunch of HTML code (handy if the list is long).

    Well, that's all for now, let's go on to:Using Environment Variables

    Another way to get input is through the use of environment variables. These are set outside the program,but can be read in pretty easily. For example, let's say we want to read the value of the Query String inthe URL (the part after the ?). Let's say the URL was:http://yoursite.com/cgi-bin/testenv.cgi?cool

    You could grab the "cool" bit off the URL and assign it to a variable like this:

    $iscool= $ENV{QUERY_STRING};

    Using the $ENV{NAME} command, we can do the same to get other environment variables. We justreplace the NAME with what we want to get, so:

    $userip= $ENV{REMOTE_ADDR};

    This will get the IP address of the user, which is useful in tracking a count for your unique visitors. Someother useful environment variables are listed below:

    Name What it Gets

    CONTENT_LENGTHNumber of characters submitted from a POSTcommand

    HTTP_REFERER URL user came from, if available.

    HTTP_USER_AGENT Type of Browser viewer is using, if available.

    QUERY_STRING String in URL after the ? character

    REMOTE_ADDR Remote user's IP address

    REMOTE_HOST Name of user's host, if available.

    SERVER_NAME Name of the local server, like: www.yoursite.com

    For more on environment variables, visitCGI 101, Chapter 3for an excellent listing and tutorial.

    Well, that's all for now, see you when I write the next section!

    http://www.pageresource.com/cgirec/ptut19.htmhttp://www.pageresource.com/cgirec/ptut19.htmhttp://www.pageresource.com/cgirec/ptut19.htmhttp://www.cgi101.com/book/ch3/text.htmlhttp://www.cgi101.com/book/ch3/text.htmlhttp://www.cgi101.com/book/ch3/text.htmlhttp://www.cgi101.com/book/ch3/text.htmlhttp://www.pageresource.com/cgirec/ptut19.htm