|
Perl: Functions In PERLFunctions in PERL
Table of Contents: Arithmetic Functionsatan2(Y,X)Returns the arctangent of Y/X in the range -PI to PI. cos(EXPR)cos EXPRReturns the cosine of EXPR (expressed in radians). If EXPR is omitted takes cosine of $_. exp(EXPR)exp EXPRReturns e to the power of EXPR. If EXPR is omitted, gives exp($_).int(EXPR)int EXPRReturns the integer portion of EXPR. If EXPR is omitted, uses $_. log(EXPR)log EXPRReturns logarithm (base e) of EXPR. If EXPR is omitted, returns log of $_. rand(EXPR)rand EXPR randReturns a random fractional number between 0 and the value of EXPR. (EXPR should be positive.) If EXPR is omitted, returns a value between 0 and 1. See also srand(). sin(EXPR)sin EXPRReturns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of $_. Takes an array or list of values and packs it into a binary structure, returning the string containing the structure. The TEMPLATE is a sequence of characters that give the order and type of values, as follows: A An ascii string, will be space padded. Each letter may optionally be followed by a number which gives a repeat count. With all types except `a\', `A\', `b\', `B\', `h\', and `H\', the pack function will gobble up that many values from the LIST. A `*\' for the repeat count means to use however many items are left. The `a\' and `A\' types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as necessary. (When unpacking, `A\' strips trailing spaces and nulls, but `a\' does not.) Likewise, the `b\' and `B\' fields pack a string that many bits long. The `h\' and `H\' fields pack a string that many nybbles long. Real numbers (floats and doubles) are in the native machine format only; due to the multiplicity of floating formats around, and the lack of a standard "network" representation, no facility for interchange has been made. This means that packed floating point data written on one machine may not be readable on another - even if both use IEEE floating point arithmetic (as the endian-ness of the memory representation is not part of the IEEE spec). Note that perl uses doubles internally for all numeric calculation, and converting from double to float back to double will lose precision (i.e. `unpack("f", pack("f", $foo))\' will not in general equal `$foo\'). Examples:
$foo = pack("cccc",65,66,67,68);
The same template may generally also be used in the unpack function. unpack(TEMPLATE,EXPR) unpack does the reverse of pack: it takes a string representing a structure and expands it out into an array value, returning the array value. (In a scalar context, it merely returns the first value produced.) The TEMPLATE has the same format as in the pack function. Here\'s a subroutine that does substring: sub substr {
and then there\'s sub ord { unpack("c",$_[0]); }
In addition, you may prefix a field with a `%\' to indicate that you want a -bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. For example, the following computes the same number as the System V sum program: while () {
String FunctionsPerl provides a very useful set of string handling functions: The first set of functions that we\'ll look at are those that deal with strings. These functions let you determine a string\'s length, search for a sub-string, and change the case of the characters in the string, among other things. Here are Perl\'s string functions:
Note As a general rule, if Perl sees a number where it expects a string, the number is quietly converted to a string without your needing to do anything. Note Some of these functions use the special variable $_ as the default string to work with. More information about $_ can be found in Chapter on Files, and the Chapter Special Variables. The next few sections demonstrate some of these functions. After seeing some of them work, you\'ll be able to use the rest of them. Example: Changing a String\'s Value Frequently, I find that I need to change part of a string\'s value, usually somewhere in the middle of the string. When this need arises, I turn to the substr() function. Normally, the substr() function returns a sub-string based on three parameters: the string to use, the position to start at, and the length of the string to return. $firstVar = substr("0123BBB789", 4, 3);
This program prints: firstVar = BBB The substr() function starts at the fifth position and returns the next three characters. The returned string can be printed like in the above example, as an array element, for string concatention, or any of a hundred other options. Things become more interesting when you put the substr() function on the left-hand side of the assignment statement. Then, you actually can assign a value to the string that substr() returns. $firstVar = "0123BBB789"; This program prints: firstVar = 0123AAA789 Example: Searching a String Another useful thing you can do with strings is search them to see if they have a given sub-string. For example if you have a full path name such as "C:\\WINDOWS\TEMP\WSREWE.DAT", you might need to extract the file name at the end of the path. You might do this by searching for the last backslash and then using substr() to return the sub-string. Note The path name string has double backslashes to indicate to Perl that we really want a backslash in the string and not some other escape sequence, search.pl $pathName = "C:\\WINDOWS\\TEMP\\WSREWE.DAT"; This program prints: WSREWE.DAT If the third parameter-the length-is not supplied to substr(), it simply returns the sub-string that starts at the position specified by the second parameter and continues until the end of the string specified by the first parameter. Arrays and List FunctionsArrays are also a big part of the Perl language and Perl has a lot of functions to help you work with them. Some of the actions arrays perform include deleting elements, checking for the existence of an element, reversing all of the the elements in an array, and sorting the elements. Here are the functions you can use with arrays:
As with the string functions, only a few of these functions will be explored. Example: Printing an Associative Array The each() function returns key, value pairs of an associative array one-by-one in a list. This is called iterating over the elements of the array. Iteration is a synonym for looping. So, you also could say that the each() function starts at the beginning of an array and loops through each element until the end of the array is reached. This ability lets you work with key, value pairs in a quick easy manner. The each() function does not loop by itself. It needs a little help from some Perl control statements. For this example, we\'ll use the while loop to print an associative array. The while (CONDITION) {} control statement continues to execute any program code surrounded by the curly braces until the CONDITION turns false, assoc.pl. %array = ( "100", "Green", "200", "Orange"); This program prints: 100 = Green The each() function returns false when the end of the array is reached. Therefore, you can use it as the basis of the while\'s condition. When the end of the array is reached, the program continues execution after the closing curly brace. In this example, the program simply ends. Example: Checking the Existence of an Element You can use the defined() function to check if an array element exists before you assign a value to it. This ability is very handy if you are reading values from a disk file and don\'t want to overlay values already in memory. For instance, suppose you have a disk file of Jazz Artist addresses and you would like to know if any of them are duplicates. You check for duplicates by reading the information one address at a time and assigning the address to an associative array using the Jazz Artist name as the key value. If the Jazz Artist name already exists as a key value, then that address should be flagged for follow up.
Because we haven\'t talked about disk files yet, we\'ll need to emulate a disk file with an associative array. And, instead of using Jazz Artist\'s address, we\'ll use Jazz Artist number and Jazz Artist name pairs. First, we see what happens when an associative array is created and two values have the same keys, element1.pl. createPair("100", "Miles Davis");
This program prints: 100, John Coltrane This example takes advantages of the global nature of variables. Even though the %array element is set in the createPair() function, the array is still accessible by the main program. Notice that the first key, value pair (100 and Miles Davis) are overwritten when the third key, value pair is encountered. You can see that it is a good idea to be able to determine when an associative array element is already defined so that duplicate entries can be handled. The next program does this, element2.pl. createPair("100", "Miles Davis");
This program prints: 100, Miles Davis You can see that the number for John Coltrane has been changed to 101.
|