Sie sind auf Seite 1von 27

Perl is short for Practical Extraction and Reporting Language. CGI is short for Common Gateway Interface.

CGI is the interaction between the browser and the server. It is a set of structured rules. Perl is a script language. Some Perl scripts are CGI. Some are not. Some CGI use Perl. Some CGI use a different script language. When people mention CGI, it usually means Perl/CGI. Perl may be referenced as scripting or programming depending on what source you are looking at. Personally, I like to refer to it as programming since it actually executes commands. The first part you will need to do is adjust the "permissions" of the folder that will contain your PERL scripts. That means you will "allow" a script to be "executed" from this specific place. Normally the folder permissions are set to view (read) only. You can view web pages, images, animated things, movies, etc... We've now moved into an area where a script will need to be run (executed). Many free hosing sites will probably not have this available since running a script may be viewed as a virus. The security risk is too high. But... since you have come this far, I will presume you have access to a personal cgi-bin for your site or you are able to set permissions. Permissions are set using a command called CHMOD. CHMOD stands for CHange MODe. You are giving the host computer new instructions about this file (folder). The CHMOD comes as a set of 3 numbers. Each of these 3 numbers is a sum total of 3 other numbers. So you have to add 3 numbers to get the first CHMOD number, add 3 numbers to get the second CHMOD number and add 3 numbers to get the third CHMOD number. Most PERL areas will need a CHMOD setting of 755 or 777 (depending on the script you are using). Understanding the numbers. Each digit is a number value from 0 to 7. The value specifies what capabilities are available (or not). These numbers correspond to 3 command types. Read, write and execute. Read (r) has a value of 4. It allows listing files in the directory. Write (w) has a value of 2. It allows the addition of new files to the directory. Execute (x) has a value of 1. It allows access to the files in the directory. Here are the possible combinations available using these command types : Digit 0 1 2 3 4 5 6 7 rwx ----x -w-wx r-r-x rwrwx Result no access execute write write and execute read read and execute read and write read write execute

OK... so you know each digit will be a number from 0 to 7, but what does the 3 digits stand for? The first number represents the host server. This will usually be set to 7 giving the host full permission on the files in the folder. The second number represents the group (YOU - the individual being hosted). And the third number represents the world (the visitors to the site). Normally, on free hosts, these two digits will be set to 4, allowing the reading (and displaying)

of files. Thus, no executing capabilities. Typical settings for files are 777, 755, 666 or 644. Typical settings for directories are 777 or 755. Cgi scripts 755, data files 666, and configuration files 644. How do you change the CHMOD? The easiest way (for a user) is by using an FTP program. Most FTP programs have a button or right-click menu that allows you to set the CHMOD on a specific folder. Do you have your CHMOD set? If not, go back a page and do that first otherwise the rest of this will not work. Creating a PERL file is the same as creating a text file. Open your text editor (such as Notepad) and save it with the extension of either .pl or some hosts require it to be .cgi to work. Either way, the coding is the same. The first line of code (sometimes referred to the SHEBANG line) specifies the path to the PERL interpreter on the host. This path will vary from host to host, so be sure you get the right path from your host. Many hosts have a common one such as ... #!/usr/bin/perl NOTE : There is no semicolon at the end of this command line. The next command line you need is something to tell the PERL that you are working with HTML (web pages). It sets the MIME type. #!/usr/bin/perl print "Content-type: text/html\n\n"; After those two lines, you are into the PERL coding part of it. Two very important parts to remember are comments and semi-colons. Comment lines let you document your coding. This makes it much easier for editing later on if you have a small paragraph telling what this part of the coding is doing or how. Basically, it is a "notes" type thing. Comment lines start with the # symbol. There is no semi-colon at the end of a comment line. #!/usr/bin/perl print "Content-type: text/html\n\n"; # This is a comment. The program will not see this line.

Now, you may be wondering about the very first command line. It uses the same symbol, so in theory it would comment the PERL path out too. Well... don't worry about it. It won't comment out that one first line and it will find the PERL path. That first command line is "special". The semi-colon ; is also a very important part of PERL. It states where each command ends. There are a few instances where it will not appear (such as the shebang and comment lines) but for the most part, they will appear at the end of each command line. It is a great tool to use and if you've already learned JavaScript, most of this will be easy. So trudge on and learn it all :)

Scalar data is an individual piece of data. In JavaScript it would be the same as a variable. Bascially, it is an invisible container that has a name label on it and it holds a value inside of it. Scalar data is symbolized by a $ sign. For correct processing, the $ must be followed by a letter (non-numeric) character. Scalar names are CaSe SeNsItIvE. $A is different than $a. You can use up to 255 characters for a scalar name which includes numbers, letters, and underscores. Assigning or changine values of a scalar is as easy as an equals sign. Here are some quick examples : $a=5 $b=12 $a=$b #a contains value of 5 #b contains value of 12 #a now contains value of 12

There are two types of data values. NUMBERS and STRINGS. Numbers are characters ranging from 0 to 9. No letters or other symbols. Strings are a collection of characters which my include : letters, numbers and/or symbols. Strings can be a word, sentence, or even just a number. Strings come in two varieties. CONSTANTS and VARIABLES. String constants are a set value. They do not change. print "Hello World!"; The value specified "Hello World!" will not change. It is a solid string constant. String variables are quite different. They are containers with a name label on them. The value (contents) of the container may change. The NAME of the string variable should be descriptive. You can tell a string variable as it starts with one of these symbols $ @ %. The $ represents a scalar variable, the @ represents an array, and the % represents a hash. All of these variable types have a unique function and will be discussed in detail as you go through these tutorials further. Here is a quick example though... $mymessage="Hello World!"; print $mymessage; $mymessage="Bye World!"; print $mymessage;

PERL documents may be a bit particular when it comes to uploading them to your host, so I figured I would include a section on this as well. Some hosts have an "easy" upload section using your browser. Most hosts these days allow you to upload (and download) files using an FTP program. FTP stands for File Transfer Protocol. It is basically a direct connection between your computer and your online file directory. Two good FTP programs to use (and free) are WS_FTP and SmartFTP. WS_FTP is a favorite to many, but prefer is the SmartFTP. You will have to look through the HELP, FAQ or email your host for the exact settings to use for connecting to your online area. Now you should have an FTP program, setup, and connected to your online space. The next part is transferring the files. This is done by highlighting and clicking on the transfer button (or drag and drop). BUT WAIT! Before you do any transferring, check the MODE the transfer is set to. There are 3 settings for mode. ASCII, BINARY, and AUTO. Different file types need to be transferred in a compatable mode otherwise it will turn into garbage at the other end. PERL

documents must be sent by ASCII mode. Most of your PERL documents are probably going to be uploaded to a special folder called cgibin. With the correct permissions set, they can work in most any folder, but this is the most common and used on the Internet. The last part of uploading is changing the CHMOD of the folder holding the PERL documents. The concept of PERL escape code is the same as HTML escape code. It is a way to enter a specific feature or character "outside" of the normal coding (usually to appear on the web page itself). For example... to show double quotes on the web page : Regular document " HTML Escape " PERL Escape \"

Quick examples : Coding input : Page output : "Hello 'World'" "Hello \'"World\"" Hello 'World' Hello "World"

Common escape sequences : \a Beep \b Backspace \c "Control" caracter. \cD = CTRL-D \e Escape \f Form feed \l Make the next letter lowercase \n New line, return. \r Carriage return. \t Tab. \u Make the next letter uppercase \x Enables hex numbers \v Vertical tab \\ Print backslash \" Print double quotes \ Escape next character if known otherwise print. Also allows octal numbers. \L Make all letters lowercase until the \E \U Make all letters uppercase until the \E \Q Add a backslash-quote to all the nonalphanumerics until the \E \E Terminates the effects of \L, \U, or \Q

The TAB and NEW LINE escapes are the most commonly used. The PRINT command in Perl is probably the most known and used. It is used to display things to the monitor screen. Print is a built in Perl function. It sends output to a specific location. The location is "STandarD OUTput" also known as STDOUT. For the rest of us common folks, that means "the monitor screen". The print command is specific to the monitor screen, so stating an actual <STDOUT> command is unnecessary.

Ready for the code? #!/usr/bin/perl print "Content-type: text/html\n\n"; print ("Hello World!");

0 The first line (shebang) tells the coding where to find the Perl translator. The second line tells the browser that this PERL is working on the Internet. The last line states to print the following message. By default, it assumes STDOUT so the message will appear on the monitor screen. The PRINT command is actually a very powerful one. It can be used to display parts of a web page using HTML coding, or even an entire web page! That circumstance is probably a bit out of the ordinary, but the possibilities are there. #!/usr/bin/perl print "Content-type: text/html\n\n"; print "<html><head><title>Test</title></head><body>\n"; print "<h1>Hello world!</h1>\n"; print "</body></html>"; Chomp is a "built-in" Perl command. It has a rather odd job. It takes off the end character of a specified string ONLY if that character is a RETURN (Enter). The return character is sometimes created from input information or by the coding itself. Either way, to parse that character off, CHOMP is the command to use. It will not affect any other characters. Note : The RETURN character is the same as the ENTER character which is also known as a NEWLINE character. It is symbolized as \n. Quick example... #!/usr/bin/perl # set the value with a return character. $input = "Test\n"; # print the current value. print "$input <br>"; # chomp the data and print the value once, twice, three times. chomp ($input); print "After one chomp the value is now $input <br>"; chomp ($input); print "After two chomps the value is now $input <br>"; chomp ($input); print "After three chomps the value is now $input";

Ok, so that isn't really the best example, but hey, it's hard to figure a way to show an invisible thing dissappear. What it does show though is that chomp did not take away any other ending characters. The next command is CHOP. This is a very similar command as CHOMP, but... it takes of the ending character of a string no matter what it is. Another quick example...

#!/usr/bin/perl # set the value for the test. $input = "Test\n"; # print the current value. print "$input <br>"; # chop the data and print the value once, twice, three times. chop ($input); print "After one chop the value is now $input <br>"; chop ($input); print "After two chops the value is now $input <br>"; chop ($input); print "After three chops the value is now $input";

There are different ways to link to a Perl script which depends on what you will have it doing or how you have your web page setup. The first method is to REGULAR link it. You can use a normal link to send the vistor to your Perl script. <a href="/cgi-bin/filename.cgi"> Click here </a> You can use this same method to pass some pre-set variables as well... <a href="cgi-bin/filename.cgi?key1=value1&key2=value2"> Click here </a> The information starting at the ? will be processed by the Perl script. That part comes later in these tutorials. Another method of information passing is by using a FORM area on your web page. The part that deals with this is the ACTION and METHOD properties of the starting form tag. <form action="/cgi-bin/filename.cgi" method="post"> The ? pre-set variable may also be added onto the end of the URI in the ACTION value as seen above in the normal linking. With forms though, this type of pre-setting can also be done by using a HIDDEN line. Need to brush up on creating forms? Click here! And yet another way of activating a Perl script is by using an SSI call. <!--#include virtual="/cgi-bin/filename.cgi" --> So those are the most common methods used to get the information into the Perl script or to activate a Perl script page. Perl environment values are very similar to SSI environment values. Two of the most common environment values used are : $ENV{'HTTP_USER_AGENT'} $ENV{'HTTP_REFERER'} Browser type/version Referral page info

Here is an example to show how to use these two environments : #!/usr/bin/perl print "Content-type: text/html\n\n;

$browser = $ENV{'HTTP_USER_AGENT'}; $from = $ENV{'HTTP_REFERER'}; print "You are browsing this page with $browser <br>"; print "And before this webpage, you were visiting this webpage : $from"; See it in action! You may encounter a blank value for the REFERER value. This environment value will only hold a value IF the visitor clicked on a link to get to that page. If the visitor types in the URL manually, the value will be blank. There may be other occurances of a blank value, but this is the most common. The other environments available are :
$ENV{' '} Results

DOCUMENT_ROOT HTTP_COOKIE HTTP_HOST HTTPS PATH QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_PORT REMOTE_USER REQUEST_METHOD REQUEST_URI SCRIPT_FILENAME SCRIPT_NAME SERVER_ADMIN SERVER_NAME SERVER_PORT SERVER_SOFTWARE

Root directory of your server. Visitor's cookie (if set). Hostname of your server. ON if called through a secure server. Systems path your server runs under. The query data (used with GET). IP address of visitor. Hostname of visitor. Port the visitor is connected to on web server. Visitor's username. GET or POST Interpreted pathname of requested document. Full pathname of current CGI page. Interpreted pathname of current CGI (relative to root). Email address for your server's webmaster. Your server's domain name. Port number your server is listening on. Server software being used (ex. Apache 1.3)

Operators are the calculations that are possible. Adding, subtracting, comparing, etc.. Common operators are the regular math types. Add, subtract, multiply, and divide. +-*/ Here is an example. It sets 3 variables to numbers and performs some simple math to them. #!/usr/bin/perl print "Content-type: text/html\n\n; $x = 5; $y = 15.5; $z = .05; $a = $x + $y; print "a equals $a<br>"; $b = $z + 5; print "b equals $b<br>"; $c = $x / $z; print "c equals $c<br>";

$d = $x * $y; print "d equals $d<br>"; $x = $x + 2.5; print "x equals $x"; Check out that last equation. The value of $x actually changed during the calculation. On the equation side, it took the current value of $x and added 2.5 to it. The new value is then transferred into the $x variable. Kinda looks like it would put itself into an endless loop doesn't it? Well, PERL seems to be smart enough to know better and allow this. A different way of displaying this equation would be : $x += 2.5; Which translated means "Add 2.5 to the current value of $x". Here are some other examples of shorthand math : $a = ++$y; $y is increased by 1 before the value is assinged to $a. $b = $z++; $b is assinged the value of $z before the $z is increased by 1. Using two minus signs -- will have the same effect but subtract 1 instead of adding it. What about using more than one common operator in a single equation? 5 + 2 * 3 = ??? What do you think the result of this equation would be? 11 or 21? The answer is 11. PERL uses the same principles as normal math. You may have learned aboutBEDMAS in classes. This stands for : Brackets Exponents Division Multiplication Addition Subtraction. These are the rules that show what order things are done in. If the equation has anything in brackets, those will be calculated first, and exponents will be done next, division is next, and so on. So looking at the example question... the 2 mulitply 3 is performed first and then added to 5. Exponents are multiplying a number to itself many times. 3 raised to the 4th power = 34 = 3*3*3*3 = 81. Perl uses ** as the exponential operator. The above example would be seen as : $result = 3 ** 4; $result holds the value of 81. Using division will produce remainders. That is the left over amount after the "whole number". If you divide 25 by 7 the whole number is 3 and the remainder is 4. 3*7=21+4=25. Perl has a built in function to find the remainder. It uses the % symbol. (The % symbol is also used for specifying HASH data, but that comes later in the tutorial pages.) $dividend = 25; $divisor = 7;

$remainder = $dividend % $divisor; The $remainder will have the value of 4. Comparison operators are used for decision making. They let you compare one thing to another. < > == <= >= != <=> less than greater than equal to less than OR equal to greater than OR equal to not equal to comparison

Most of the above comparisons produce a true/false value except the last one. Here is a quick example to show how it works : $result = $a<=>5; $result equals 1 if $a is greater than 5. $result equals -1 if $a is less than 5. $result equals 0 if $a is equal to 5. Here is a larger example to show comparisons in action : #!/usr/bin/perl print "Content-type: text/html\n\n; $x=5; $y=15.5; $z=.05; $a=$x<6; print "a equals $a<br>"; $b=$x>6; print "b equals $b<br>"; $c=$x>=5; print "c equals $c<br>"; $d=$x>=5; print "d equals $d<br>"; $e=$x==5; print "e equals $e<br>"; $f=$x!=5; print "f equals $f<br>"; $g=$x<=>6; print "g equals $g"; Strings (values containing letters and such) also have comparison operators, they just look a bit different than the number ones above. The operator takes the first character of each string and compares them. lt gt less than greater than

eq le ge ne cmp

equal to less than or equal to greater than or equal to not equal to comparison

Some sample results : "dog" lt "cat" "345" gt "62" "dog" le "cat" "dog" ge "cat" "dog" eq "cat" "dog" ne "cat" "dog" cmp "cat" false. false. false. true. false. true. 1 c is less than d. 3 is less than 6. c is still less than d. d is greater than c. The two are not equal. They are not equal. d is greater than c.

Logical Operators are on similar ground to comparison operators. They take two items, compare them and perform based on the result. These are the OR, AND and NOT of comparisons. || OR && AND ! NOT

OR will compare two expressions and produce a true result if either expression has a true value (non-zero). The result will have the value of the first true expression value. If both expression values are zero, the result will hold a zero value. An example in action.

AND will compare two expressions and produce a true result if both expression values have a true value (non-zero). The result will have the value of the last true expression value. If one or both expression values are false (zero), then the result will hold a zero value. An example in action.

NOT will evaluate one expression. If the expression is zero, the result will be true and hold a value of 1. If the expression is non-zero, the result will be false and hold a value of null. null is not zero. It is an empty space. This is kindof a backwards way of finding a result conidering it is looking for the "non" values. It does come in handy though when that is the desired result you are looking for though. Datalist The best way to describe a list in Perl/CGI is a group of data. It is a sequence of values inclosed in parentheses. (1,2,3,4,5) Lists are not limited to numbers. Strings may also be included ... (1,2,"hello",7,9,"world",42) Scalar variables may also be used ... (1,$name,5,34) Whatever value $name holds will be placed in its spot when the list is being used.

A string continaing a scalar variable may also be used ... (1,2,"Hello $name",78) A list may be defined as an "empty list" ... () Lists may also hold expressions ... (2+3,"hello",$value1*$value2,21) Shortcuts may be used in lists by using two periods. (1..10) Represents (1,2,3,4,5,6,7,8,9,10) (1,5,7..10) Represents (1,5,7,8,9,10) (2.5 .. 5.5) Represents (2.5,3.5,4.5,5.5) (-2.5 .. 1.9) Represents (-2.5,-1.5,-0.5,1.5) Notice only the starting decimal factor is used. (a..e) Represents (a,b,c,d,e) (a..e,1..5) Represents (a,b,c,d,e,1,2,3,4,5) Lists may be used as arrays. @numbers = (1..10); Arrays are groups of data stored in a single spot. While scalar data (single pieces of data) use the $ sign, arrays use the @ symbol. For an example, you could make an array using the days of the week : @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); Notice we used a LIST for entering the data into an array area. Arrays are normally entered between the "shebang" line and the MIME line; Similar to specifying things in the HEAD section of HTML. This is not a solid rule though. #!/usr/bin/perl @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); print "Content-type: text/html\n\n"; print "These are the days of the week: "; print "@days"; See it in action! Using the double quotes, the script parsed the information and the contents of the array were printed out with a space between each data entry. A shortcut for eliminating the quotes in a list area is qw. The above example would have the array line changed to : @days = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday); This method only works when you are dealing with one word selections though. qw symbolizes aquoted comma deliminated list. Arrays are able to contiain regular data (as seen above), other arrays, scalar data, hashes, and/or expressions. Arrays are pretty flexible when it comes to data.

Similar to JavaScript, PERL array items are numbered from 0 instead of 1. These numbers are

referred as the array index. Using the week days example, to print Thursday the code would be : print "The value for the fourth array item is $days[3]"; Hold it! Is that an error? Why is the symbol a $ instead of @? An array is a group of data. Scalar items are single data elements. We are wanting to display a single data item, thus a scalar symbol is used. What about that [3] part? Isn't Thursday the 4th day? The coding will find the 4th data value in the named array. Remember that the array index starts at zero so spot #3 holds the 4th data item. Here is the days array broken down into its parts and values visually : $days[0] $days[1] $days[2] $days[3] $days[4] $days[5] $days[6] = = = = = = = "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday"; "Sunday";

You could actually assign the values into the array like that too, but doesn't the LIST way look a lot smaller and easier? Now try adding this to the example coding... print "The mystery value is $days[-4]"; Before you run your script, what do you think the result will be? Highlight the area below to find the answer! THURSDAY Negative numbers can be used to find information starting at the end of an array list. The last value is -1, the second to last value is -2, and so forth (or back as the case may be). Besides regular and negative numbers, scalar data and expressions may also be used as the index value.

Now lets work with arrays a bit. The most part about working with arrays is what you want to do with the information. You've seen how to set array data using a LIST above. Here are some other commonly used situations : If you want to assign the first value of an array into a scalar, the script would be : ($result)=@array; Since a scalar variable can only hold one piece of data, it will take the first element of the array automatically. This does not change the array values at all. To assign the first two elements of an array into scalar values : ($result1,$result2)=@array; Using the round brackets for the above examples are important. Without them, the script will

pass the length of the array (the number of elements the array is holding) into the scalar variable. $result=@array; If that was the weekdays array, the result scalar variable would have a value of 7. A similar idea is to find the last index number in an array. Add in a $ and it will provide : $result = $@array; But that really isn't the true length of the array considering the array index starts at zero. So to find the number of elements, the amount will have to be adjusted by one. $result = $@array+1; To copy one array to a new (second) array : @array1 = @array2 To add an new value to the beginning of an array, the UNSHIFT command is used : unshift(@array,newelement); or the same effect can be done without the UNSHIFT : @array=(newelement,@array); To add a new value to the end of an array also has two options : (@array,newelement); or the slightly longer version : @array=(@array,newelement); Next is combining two arrays into a new array : @newarray=(@firstarray,@secondarray); After all of that adding, it's time for a bit of subtraction. To remove the first value of an array the SHIFT command is used : shift(@array); You can store that removed value into a scalar at the same time too : $result=shift(@array); To remove the last element of an array : pop(@array); To remove the last element of an array and store it in a scalar : $result=pop(@array); To replace a specific element in an array : $array[number]=$newelement;

Now we can go into a different aspect of working with arrays. The following will display various sorting or arranging techniques. The contents of the array are not changed or harmed unless you save the result into a new array or back into the same array. To sort an array in ASCII (Alphabetical) order :

sort(@array); Example of storing a sort result back into the same array : @array = sort (@array); To sort an array in reverse ASCII (Alphabetical) order : sort {$b cmp $a} (@array); To sort an array in numeric ascending order : sort {$a <=> $b} (@array); To sort an array in numeric decending order : sort {$b <=> $a} (@array); To print a sorted array but not alter the original : print sort(@array); To reverse the value elements in an array : reverse (@array);

Array slices : two or more elements of an array being accessed at the same time. We have seen how to find a single entry from an array previously on this page. Now it's time to find muliple entries. @values = @array[0,3,4]; The first part to notice is the stored result is going into an array. When we were dealing with only one value, using a scalar variable was OK, but we are moving into multiple values, so an array is the choice. The second part shows comma deliminated numbers. The script will go into the array at those specificarray index points, retrieve the values, and store them into the new array. Let's bring in our weekdays example : @values = @days[0,3,4]; After the above command gets executed, the contents of the @values array would be : $values[0]="Monday"; $values[1]="Thursday"; $values[2]="Friday"; Notice that the new array used its normal numbering instead of 0 3 4. That's because the 0 3 4 was a reference into the array being looked at, not into the new array. If you wanted to get the same index numbers, then the code would have to be changed to this : @values[0,3,4] = @days[0,3,4]; As like all other examples, the numbers specified for the index reference can be scalar variables, expressions, etc.. The value assignment can work backwards too (or forwards depending on your view on things). If you want to assign specific values to specific array spots :

@array[0,3,4] = ("Hello","Out","There");

Hashes are very similar to an arrays. A hash is an array of pairs. It is often called an "associative array". Some differences between a hash and array : - A hash uses the % symbol instead of the @ symbol. - Arrays use 0 to whatever number as an index. Hashes are keys and value pairs. key, element, key, element, and so on... - Hashes use the curly brackets {} instead of the square brackets [] to find individual elements. Here is a quick example of what a hash may do : %chores = ("Monday", "dishes", "Tuesday", "vacuum", "Wednesday", "garbage"); $value = $chores{Wednesday}; print "$value"; The example has 3 days and 3 chores values. The data is setup in "key","value" pairs. The script will know this is a hash instead of an array because of the % symbol. We are using a scalar variable to find the result since we are looking for a single piece of data. The script searches for the specified {key} and assigns the corresponding value of that key to the scalar variable. The output of the example script is : garbage See it in action! Hashes are very adaptable when it comes to data holding just like arrays. They are able to contiain regular data (as seen above), scalar variables, other hashes, arrays, and so on... Printing hash data is different from printing array data. Actually it takes an array to help print a hash. Take this line for example : print "%chores"; Now if that was an array, you would be expecting all of the data to be printed out. Well, this is a hash so all it will print out is the actual word... %chores. PERL does not consider the hash to be an actual variable, so it displays the result as normal text. So to print out all of the elements contained in a hash, keys and values, they will have to be put into an array first. @array=%chores; print "All of the elements stored in %chores are @array \n"; It probably won't be often when you want all of the elements in a hash to be printed. Here are some examples of other ways to work with hashes. To find the KEY elements in a hash and store them in an array : @array = keys(%chores); The word keys above is actually the word... keys. It is not special for the example like the array name. The array in most of these examples can be called whatever you like. To find all of the VALUE elements in a hash and store them in an array : @array = values(%chores); The word values above is actually the word... values.

To find EACH of the key/value pairs in a hash : %hash1=(a,1,b,2,c,3,d,4); while (@temp=each(%hash1)){ print "The key value pair is @temp <br>"; } - The hash1 is set with values. - While the value remains true, keep looping. - @temp is used to temporarily hold two values. - The EACH command pulls out two pairs of values in each loop and goes to the next two upon the next loop. - The PRINT command displays the information stored in the temp array during each loop. To delete a specific key and corresponding value : delete $hash{$key};

Conditional statements are different ways of checking an expression to see if it is true (or not) and then react based on the results. IF will execute a statement block upon a true expression value. if (expression) {do this statement block only if the expression is true;} If the expression had a false value, then that statement block would not be executed and the script would go onto the next line of code. What about the times when you want a different statement block to be executed during a false value and THEN go onto the next line of code? That is where the ELSE addon comes in. if (expression) {do this statement block only if the expression is true;} else {do this statement block if the expression is false;} Quick example : $a=25; if ($a=10) {print "a is equal to 10.";} else {print "a is not equal to 10.";} Result : a is not equal to 10. ELSIF statements can be used when you have more than one expression to evaluate and to select the correct statement block to execute. When any statement block within the control structure is executed, the control is taken out of the IF area and continues onto the next line of code. The balance of the IF area is ignored. You can have as many elsif statements in an control structure as required. *NOTE* : be sure to spell ELSIF correctly! There is no E in the middle as in ELSEIF. if (expression) {do this statement block only if the expression is true;} elsif (expression) {do this statement block only if the elsif expression is true;}

else {do this statement block if the expression is false;} If the IF expression is true, it will execute the first statement block. If the IF expression is false, it will test the ELSIF expression. If the ELSIF expression is true, it will execute it's statement block. If the ELSIF expression is false, the control continues to the next ELSIF, or ELSE, or end the control structure (whatever is next after the ELSIF).

The IF command is mostly used to find a TRUE expression. The UNLESS command is used to find a FALSE expression. You can actually find a false expression using the IF command as well, but that's another story. unless (expression) {do this statement block only if the expression is false;} The ELSE command can also be used with UNLESS command and will react like it did on the IF command. unless (expression) {do this statement block only if the expression is false;} else {do this statement block if the expression is true;}

The WHILE conditional statement lets you repeat a statement block as many times as you need. It works in a similar way as the IF ELSE. WHILE will run its statement block if an expression value is TRUE. while (expression) {do this statement block as long as the expression has a true value} WHILE creates a loop effect, so a scalar can be used to control the number of loops like a counter. $counter=15; while ($counter < 25) {print "$counter is less than 25. <br>"; $counter++;} While the value of $counter is less than 25, a sentence is printed. The value of $counter is increased by one and the expression is re-evaluated. The loop (re-evaluation) will continue until a FALSE result breaks it. UNTIL is the opposite of WHILE, but the end result is very similar. It will repeat a statement block "until" the expression is true. $counter=15; until ($counter > 25) {print "counter has a value of $counter. <br>"; $counter++;} Compare the WHILE and UNTIL examples. If you test them out, you will notice that the WHILE did 10 loops and UNTIL did 11 loops. The choice of which one to use will depend on your specific application and the result you are looking for.

The DO WHILE conditional statement allows you to execute a statement block at least one time

and continue its loop as long as the expression remains true. The expression is evaluated at the end of the loop instead of at the start. $counter=15; do {print "The value of counter is $counter. <br>"; $x++;} while ($counter < 25); The DO WHILE comes in handy if you want a specific block executed at least once no matter what the value holds. Change the last line to while ($counter<10); and see what happens. Notice there is a semicolon added at the end of the WHILE line. This shows it belongs to a DO WHILE loop instead of a regular WHILE loop. The FOR conditional provides a shorthand method of specifying how many times a statement block is to be executed. It follows a different layout than the above conditional statements : for (initial; expression; iterator) {statment block coding here} The looping control is all kept in the expression area instead of within the statement block area. Nice, tidy and in control. Don't let those foo words spoil the fun. Initial is just where you want the loop to start. Expression is just like you've seen in all the other examples. Iterator is the counter part. for ($counter=15; $counter<25; $counter++) {print "The value of counter is $counter. <br>";} During each loop, the conditional statement is re-evaluated, the iterator re-increases, and so forth until the conditional statement is false.

FOREACH is often used to find values within an array structure. The control will go to each value within a specified array, assign that value to a temporary scalar, and use the value for whatever purpose. $x = 10; print "The value of x before the loop is $x. <br>"; @y = (1,8,6,5,7); foreach $x (@y) {print "The value of x inside the loop is $x. <br>";} print "The value of x after the loop is $x";

So the original value of $x was not altered. The $x in the FOREACH loop is a separate $x of the main script even though it holds the same name. This is known as a local variable. The outer $x is called aglobal variable. For an easier approach, you can take out the scalar variable and an implied variable will be used. @y = (1,8,6,5,7); foreach (@y) {print; print "<br>";}

The first print assumes there is a variable holding a value and will print it. Perl automatically

knows you are referring to an "implied" variable when you don't give the print command any variables. The second print statement is just entering a line break for easier output viewing. Perl provides 3 control statements which can be used inside a loop to override its normal behavior. NEXT, LAST, and REDO. NEXT can be used inside a loop to skip the rest of the statment block during a specific occurance then continue until normal loop termination. $counter = 15; while ($counter < 25) { $counter++; next if ($counter == 20); print "counter has a value of $counter which is less than 25. <br>"; } print "end of script.";

When the value of $counter equalled 20, the NEXT command took the program control back to the start of the loop, ignoring the remainder of the statement block. The print function thus did not output the line "counter has a value of 20 which is less than 25.". LAST is similar to NEXT except it terminates the loop upon execution instead of returning to the start of the loop. $counter = 15; while ($counter < 25) { $counter++; last if ($counter == 20); print "counter has a value of $counter which is less than 25. <br>"; } print "end of script.";

Once the counter value equalled 20, the loop was terminated. REDO repeats a loop beyond its normal behavoir. $counter = 15; while ($counter < 25) { $counter++; print "counter has a value of $counter which is less than 25. <br>"; redo if ($counter == 25); } print "end of script.";

The last line output has 26 in the value which is obviously not less than 25. This example is a simple print output. The redo forced the loop to happen once more, the value was increased by one, and the print command did it's simple purpose. A nested loop refers to a loop inside of another loop. This type of programming is allowed, but be cautious... make sure each loop has it's own ending and purpose. Just like nested tables or regular html tags themselves, overlapping and non-endings can create a problem web page.

$counter1 = 0; while ($counter1 < 5) { $counter1++; print "The value for counter1 is $counter1. <br>"; $counter2 = 1; while ($counter2 < 5) { $result = $counter1 * $counter2; print "$counter multiply by $counter2 equals $result. <br>"; $counter2++; } } print "end of script.";

The inside loop (counter2) is being executed during each single outside loop (counter1). Time to re-examine strings. From an earlier tutorial page, its been noted that a string is simply a piece of data that contains letters and may contain numbers as well. Basically though, it is a non-fully-numeric piece of data. This page will show some different abilities you can do with strings. Connecting or combining strings. JavaScript uses the + (plus) symbol to connect strings. Perl uses the . (period) symbol. $firstname = "John"; $lastname = "Smith"; $fullname1 = $firstname . $lastname; $fullname2 = $firstname . " " . $lastname; $fullname1 has the value of "JohnSmith". The script literally combined the two scalar variables together. The second combining script line shows how to put a space in there. $fullname2 has the value of "John Smith".

Strings can have a repetition operator. That is the one string may be repeated (copied and combined) onto itself. $result = "Dave" x 4; The $result will contain the value "DaveDaveDaveDave"

Case operators control the CaSe LeTtErInG. Case Op Escape Equivalent lc lcfirst uc ucfirst $name1="Jack"; $name2="Jill"; \L \l \U \u Result All letters in the string are converted to lower case. Only the first letter in the string is converted to lowercase. All letters in the string are converted to upper case. Only the first letter in the string id converted to uppercase.

$newname1= lc $name1; $newname2= uc $name2; print "name1 is $name1. <br>"; print "name2 is $name2. <br>"; print "newname1 is $newname1. <br>"; print "newname2 is $newname2."; HTML, JavaScript, and SSI all have comment tags. PERL follows the trend and also allows you to enter comment areas. This is great considering some scripts can become rather indepth. Having a couple comment lines greatly helps during editing and documenting. To comment a line out in PERL, the # symbol is used. # This line is commented out. # We can describe what the next part of the script does. # And so forth and so on. The reason behind using comments is usually to help in future editing. It's best to enter in descriptive comments rather than general unclear ones. Good : # calculate a cost-of-living adjustement and # raise the emplyee's salrary by that amount: $salary += $salary * $col_percentage; Bad : # Increment salary by salary times col_percentage: $salary += $salary * $col_percentage;

A regular expression is a group of characters you want to search for in a string. A pattern is a specific sequence of character(s) you may be searching for in a string. MATCH operators will test a string of information to see if the specified regular expression is present. If true, the statement returns a true (non-zero) value. If no match, it returns a zero or false value. The match is symbolized by an equals and tilde. =~ To test for the opposite result (having the true bring a false value) you can use an exclamation point and tilde. It isn't a common practice, but it may come in handy to know someday. !~

Normally (I say that because there are situations where it may be different, but normally) the following will hold true : To specify a regular expression (a piece of data to use in some way), it can be entered within two forward slashes. /somthing here/ Now that you have a regular expression, we can start comparing (matching) it to a string. $mystring =~ /today/; This will take the word today and look through the value of $mystring. If the match finds the

word it will produce a true result. The item to search for doesn't have to be an actual word. It can be a variable as well such as... $search_for = "today"; $mystring =~ /$search_for/;

There are a number of "special" characters to use when it comes to matching, searching, etc.. The first one to cover is the plus + option. This is used inside the regular expression area and is used to specify that the character before it may occur one or more times and still satisfy the search parameters. $mystring =~ /to+day/; Now the search will look for the word today which may contain one or more of the o character. So that means it will be true for today, tooday, toooooooday, and so forth.

The asterisk * option specifies that zero or more of the previous character can be present to make the match true. This is similar to the plus character, except the asterisks don't require one of the charcters to be present. $mystring =~ /to*day/; The search will look for the word today and will hold a true value even if the o is missing. So it will be true for today, tooday, toooooooday, and tday as well now. The plus feature mentioned earlier stated there must be at least one occurance. The asterisk takes it one step further and allows a non-occurance.

The question mark ? option specifies that zero or one of the previous character can be present to make the match true. $mystring =~ /to?day/; This time, the only true value will appear for the word today and tday. It is matching for exactly one or none of the previous character.

What if you want to specify the number of times a character is found? This is done using the curly bracket {} characters. They pre-specify how many times a certain character should appear in an expresssion. $mystring =~ /to{3,6}day/; There will be a true result if the o is repeated 3 to 6 times only. So that is toooday, tooooday, toooooday, tooooooday. To specify only a maximum number of characters, a zero can be entered for the first digit. $mystring =~ /to{0,6}day/; To specify only a minimum number of characters, leave the second digit area blank. $mystring =~ /to{3,}day/;

Or to specify an exact number of characters, enter only one number. $mystring =~ /to{2}day/;

The period . option specifies that any character (other than newline \n) will match true. $mystring =~ /a.t/; This example will produce a true value if it contains the letters "a" and "t" with almost any character in-between. Some examples that would produce a true result is if $mystring was : a1t, act, a!t, factor, author. Now using the information you have seen so far, here is a small quiz. How would you find a word that starts with the capital "T" and ends with the lower case "e" in the $mystring variable? Highlight the below space to find the answer! $mystring =~ /T.+e/; Note : If there is more than one "e" in the string after the "T" then the last "e" found in the string would be the one used in the search parameters.

There may come a time when you want to use one of the above "special" characters as part of the search pattern. How are you going to ask the script to search for a question mark when it is being used for a special command? By using a backslash \ character. This is known as an escape character. It states the next character is not really a separate command, but normal instead. $mystring =~ /hello\?/; So now the search will be able to look for "hello?".

PATTERNS What if you are looking for "eat" specifically but keep getting a true value from a word such as "feature"? Anchoring predetermines exactly where you want the pattern to be for it to match. There are 4 different ANCHOR types. b B ^ $

\b tells the regular expression that the next batch of characters must be on a word boundary. That is... the beginning or the end of a word. Here is an example showing how to search for the letters "eat" at the beginning of a word : $string =~ /\beat/; The above expression will be TRUE if the variable $string holds a value such as eating, eat, eaten, eat@joes, and so on. The expression will be FALSE with values such as feature, Eating, and Beat. The string "feature" does contian "eat" but not at the beginning of the word. The string "Eating" contains "Eat" at the begining of a word but the E character is in uppercase and regualur expressions are case sensitive by default. Here is an example showing how to search for the letters "eat" at the end of a word :

$string=~ /eat\b/; An example of a TRUE result could be "Beat it, get out of here!". The search goes through each word of the string individually and checks for the letters "eat" on the ending of each word. In addition to being able to search for a string and the beginning or the end of a word, you can search for a string at the beginning AND the end of the word. This is normally used to find a single specific word within a string and return a TRUE value. $string=~ /\beat\b/; The search looks for the word "eat" by itself, not within another word in the value of the $string variable.

\B is the opposite of the above. It will search for a string but it must be within a word, not on the start or ending of a string. $string =~ /\Beat/; An example of a TRUE result could be meat or feature. An example of a FALSE result would be eating or eatery. One or more characters MUST appear before the search element. To do a search where one or more characters must be AFTER the search element : $string =~ /eat\B/; And to do a search where one or more characters must be showing before AND after the search element : $string =~ /\Beat\B/;

The b and B searches look at each word within a string. Using ^ will do a search at only the start of a string as a whole, not as individual words. $string =~ /^if/; A true result would happen if $string holds a value such as "if this is true.". A false result would happen for a value such as "If this is true." and also "Only if it happens" The first false statement has a capital as the first letter. The second false statement has the search word not at the start of the string value.

The opposite to ^ is $. This will search at the ending of a string value. $string =~ /if$/; A true result would happen if $string holds a value such as "Only if". A false result would happen for a value such as "Only If" and also "Only if it happens" The first false statement has a capital as the first letter. The second false statement has the search word not at the end of the string value.

Be careful about capital letters, lowercase letters and punctuations at the start and endings of strings when you are working with the ^ and $ patterns. To find a one and only specific string, you can combine these two search anchors : $string =~ /^if$/;

Now that search will only be true IF the value of $string is the single word "if". Square brackets [] are used to group together a series of characters. A dash - is used to symbolize a "between" set of numbers or letters. The up ^ symbol represents "not". Here are some examples on what may be seen and what they mean.
Brackets Description Alternative

[0-9] [^0-9] [_a-zA-Z0-9] [^_a-zA-Z0-9] [\r\t\n\s] [^\r\t\n\s]

All digits 0 to 9 No digits 0 to 9 All characters, letters and numbers No characters, letters or numbers All returns, tabs, newlines, spaces No returns, tabs, newlines, spaces

\d \D \w \W \s \S

The square bracket [ ] option is used to single out a list of options that will match. Think of an OR being in between each character inside the square brackets. $mystring =~ /The year is 200[0123456789]/; A true result will be found if the $mystring a value of "The year is 2000" up to "The year is 2009". $mystring =~ /I am yelling[.!]/; A true result will be found only if the sentence "I am yelling" is matched in the $mystring and it ends with either a period OR an exclamation mark. Now if you're truly lazy like me, typing in a bunch of numbers or letters can get rather tiring. Lukily, Perl has given us a shortcut method! [0123456789] equals [0-9] And it works for letters too : [abcdefghijklmnopqrstuvwxyz] equals [a-z]

How's that for a sweet deal ?!? You don't have to use all the characters or numbers either. Say you just want c to t it would look like [c-t] and so on.

As seen above, EXCLUSION is combining the ^ and square brackets [] to select all the characters you do not want to be part of a pattern. $string =~ /200[^1-9]/; This above example will return TRUE as long as the number value of $string does NOT end with a number from 1 to 9. In other words, the only TRUE result is if $string holds the number 2000. We excluded all the other numbers.

The letter alternatives become useful when we are doing a more general search. $string1="The year is 2000 and it is going to be over soon."; $string2="Next year will be 2001."; print "String 1 contains a value of $string1 \n"; print "String 2 contains a value of $string2 \n"; print "We are searching for four digits followed by a space character \n"; if ($string1 =~ /\d\d\d\d\s/){ print "I made a match in string 1\n";} else{ print "No match in string1\n"; } if ($string2 =~ /\d\d\d\d\s/){ print "I made a match in string 2\n";} else{ print "No match in string2\n"; } See the example Looks kinda scary and complicated doesn't it? It's not really. The first part declared a couple variable values. The second part printed them out to the monitor. You've seen the IF ELSE statements before so that just leaves the actual search pattern part. \d\d\d\d\s The IF statement checks to see if the next statement holds a true or false value. A true value would print out the first IF part, a false value will print out the ELSE part. The statement is trying to find a match to... digit digit digit digit space. The first string holds true having the number 2000 within it. The second string holds false considering there is a period after the number (not a space).

Brackets can also hold the exact characters allowed as a bundle. $string =~ /[Hh]ello [Ww]orld/; The above example will allow either a capital or lowercase letter for the beginnings of the words to hold a true value. Hello World, Hello world, hello world, hello World. That works for individual characters, but if you need to check for an EITHER OR of a full number or word, it's time to use the pipe | character. $string1="Next year will be 2001"; $string2="2002 will be here before you know it"; print "$string1\n"; print "$string2\n"; print "Searching for 2000 or 2001 in the strings. \n"; if ($result = $string1 =~ /2000|2001/){print "match in string1\n";} else {print "no match in string1\n";} if ($result = $string2 =~ /2000|2001/){print "match in string2\n";} else {print "no match in string2\n";}

The examples thus far have shown matches that are case sensitive. That is, it matters if there is a capital or lower case letter. To turn off case sensitivity, add an i after the last forward slash of the expression. The i stands for insensitive. $string =~ /test/i; Now the expression will hold true for test, Test, TEST, TesT, etc..

Normally a match search is ended after the first occurance is found. There may be times when you want to find all occurances of an element within a string. Using g and a loop, this can be done. The g stands for global. Another feature to bring in is the $&. This is a special built-in variable that holds the value of the last triggered match. $string1="This is an example string that will trigger several matches."; print "String1 contains $string1 \n"; while ($string1 =~ /[a-z]+/gi){ print "A match was made with $& \n"; } The while block executes as long as there is a match in $string1. The print line uses the built-in variable which always contains the string that triggered the most recent match. Here is the same script using an array instead of a loop. $string1="This is an example string that will trigger several matches."; @results = $string1 =~ /[a-z]+/gi; print "@results \n";

Das könnte Ihnen auch gefallen