Great Templates

FEATURED WEB TEMPLATES

Amazon Books

Learn PHP

PHP Training
Zend Cert Training Zend Certified Engineer Zend PHP Pro

Perl: Functions In PERL

Functions in PERL

Table of Contents:

  • Arithmetic functions
  • Conversion functions
  • String functions
  • Array and list functions

Arithmetic Functions

atan2(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 $_.

Conversion functions

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.
a An ascii string, will be null padded.
c A signed char value.
C An unsigned char value.
s A signed short value.
S An unsigned short value.
i A signed integer value.
I An unsigned integer value.
l A signed long value.
L An unsigned long value.
n A short in `network\' order.
N A long in `network\' order.
f A single-precision float in the native format.
d A double-precision float in the native format.
p A pointer to a string.
v A short in `VAX\' (little-endian) order.
V A long in `VAX\' (little-endian) order.
x A null byte.
X Back up a byte.
@ Null fill to absolute position.
u A uuencoded string.
b A bit string (ascending bit order, like vec()).
B A bit string (descending bit order).
h A hex string (low nybble first).
H A hex string (high nybble first).

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);
# foo eq "ABCD"
$foo = pack("c4",65,66,67,68);
# same thing

$foo = pack("ccxxcc",65,66,67,68);
# foo eq "AB\0\0CD"

$foo = pack("s2",1,2);
# "\1\0\2\0" on little-endian
# "\0\1\0\2" on big-endian

$foo = pack("a4","abcd","x","y","z");
# "abcd"

$foo = pack("aaaa","abcd","x","y","z");
# "axyz"

$foo = pack("a14","abcdefg");
# "abcdefg\0\0\0\0\0\0\0"

$foo = pack("i9pl", gmtime);
# a real struct tm (on my system anyway)

sub bintodec {
unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

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 {
local($what,$where,$howmuch) = @_;
unpack("x$where a$howmuch", $what);
}

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 () {
$checksum += unpack("%16C*", $_);
}
$checksum %= 65536;

String Functions

Perl 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:

  • chomp(STRING) OR chomp(ARRAY) -- Uses the value of the $/ special variable to remove endings from STRING or each element of ARRAY. The line ending is only removed if it matches the current value of $/.
  • chop(STRING) OR chop(ARRAY)-- Removes the last character from a string or the last character from every element in an array. The last character chopped is returned.
  • chr(NUMBER) -- Returns the character represented by NUMBER in the ASCII table. For instance, chr(65) returns the letter A.
  • crypt(STRING1, STRING2) -- Encrypts STRING1. Unfortunately, Perl does not provide a decrypt function.
  • index(STRING, SUBSTRING, POSITION) -- Returns the position of the first occurrence of SUBSTRING in STRING at or after POSITION. If you don\'t specify POSITION, the search starts at the beginning of STRING.
  • join(STRING, ARRAY) -- Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "cc")) returns "AA>>BB>>cc".
  • lc(STRING) -- Returns a string with every letter of STRING in lowercase. For instance, lc("ABCD") returns "abcd".
  • lcfirst(STRING) -- Returns a string with the first letter of STRING in lowercase. For instance, lcfirst("ABCD") returns "aBCD".
  • length(STRING) -- Returns the length of STRING.
  • rindex(STRING, SUBSTRING, POSITION) -- Returns the position of the last occurrence of SUBSTRING in STRING at or after POSITION. If you don\'t specify POSITION, the search starts at the end of STRING.
  • split(PATTERN, STRING, LIMIT) -- Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
  • substr(STRING, OFFSET, LENGTH) -- Returns a portion of STRING as determined by the OFFSET and LENGTH parameters. If LENGTH is not specified, then everything from OFFSET to the end of STRING is returned. A negative OFFSET can be used to start from the right side of STRING.
  • uc(STRING) -- Returns a string with every letter of STRING in uppercase. For instance, uc("abcd") returns "ABCD".
  • Ucfirst(STRING) -- Returns a string with the first letter of STRING in uppercase. For instance, ucfirst("abcd") returns "Abcd".

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);

print("firstVar = $firstVar\n");

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";

substr($firstVar, 4, 3) = "AAA";

print("firstVar = $firstVar\n");

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";

$position = rindex($pathName, "\\") + 1;

$fileName = substr($pathName, $position);

print("$fileName\n");

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 Functions

Arrays 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:

  • defined(VARIABLE) -- Returns true if VARIABLE has a real value and if the variable has not yet been assigned a value. This is not limited to arrays; any data type can be checked. Also see the exists function for information about associative array keys.
  • delete(KEY) -- Removes the key-value pair from the given associative array. If you delete a value from the %ENV array, the environment of the current process is changed, not that of the parent.
  • each(ASSOC_ARRAY) -- Returns a two-element list that contains a key and value pair from the given associative array. The function is mainly used so you can iterate over the associate array elements. A null list is returned when the last element has been read.
  • exists(KEY) -- Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of "Orange."
  • join(STRING, ARRAY) -- Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance, join(">>", ("AA", "BB", "cc")) returns "AA>>BB>>cc".
  • keys(ASSOC_ARRAY) -- Returns a list that holds all of the keys in a given associative array. The list is not in any particular order.
  • map(EXPRESSION, ARRAY) -- Evaluates EXPRESSION for every element of ARRAY. The special variable $ is assigned each element of ARRAY immediately before EXPRESSION is evaluated.
  • pack(STRING, ARRAY) -- Creates a binary structure, using STRING as a guide, of the elements of ARRAY. You can look in the next Chapter on References for more information.
  • pop(ARRAY) -- Returns the last value of an array. It also reduces the size of the array by one.
  • push(ARRAY1, ARRAY2) -- Appends the contents of ARRAY2 to ARRAY1. This increases the size of ARRAY1 as needed.
  • reverse(ARRAY) -- Reverses the elements of a given array when used in an array context. When used in a scalar context, the array is converted to a string, and the string is reversed.
  • scalar(ARRAY) -- Evaluates the array in a scalar context and returns the number of elements in the array.
  • shift(ARRAY) -- Returns the first value of an array. It also reduces the size of the array by one.
  • sort(ARRAY) -- Returns a list containing the elements of ARRAY in sorted order. See next Chapter 8on References for more information.
  • splice(ARRAY1, OFFSET, -- Replaces elements of ARRAY1 with elements LENGTH, ARRAY2)in ARRAY2. It returns a list holding any elements that were removed. Remember that the $[ variable may change the base array subscript when determining the OFFSET value.
  • split(PATTERN, STRING, LIMIT) -- Breaks up a string based on some delimiter. In an array context, it returns a list of the things that were found. In a scalar context, it returns the number of things found.
  • undef(VARIABLE) -- Always returns the undefined value. In addition, it undefines VARIABLE, which must be a scalar, an entire array, or a subroutine name.
  • unpack(STRING, ARRAY) -- Does the opposite of pack().
  • unshift(ARRAY1, ARRAY2) -- Adds the elements of ARRAY2 to the front of ARRAY1. Note that the added elements retain their original order. The size of the new ARRAY1 is returned.
  • values(ASSOC_ARRAY) -- Returns a list that holds all of the values in a given associative array. The list is not in any particular order.

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");



while (($key, $value) = each(%array)) {

print("$key = $value\n");

}
This program prints: 
100 = Green

200 = Orange

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");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");



while (($key, $value) = each %array) {

print("$key, $value\n");

};


sub createPair{

my($key, $value) = @_ ;


$array{$key} = $value;

};

This program prints:

100, John Coltrane

200, Keith Jarrett

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");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");

while (($key, $value) = each %array) {

print("$key, $value\n");

};


sub createPair{

my($key, $value) = @_ ;


while (defined($array{$key})) {

$key++;

}


$array{$key} = $value;

};

This program prints:

100, Miles Davis

101, John Coltrane

200, Keith Jarrett

You can see that the number for John Coltrane has been changed to 101.


 


Learn PHP | Zend Certified Engineer | Zend PHP Pro | PHP Web Apps | Web Hosting Service | Low Cost Domain Names | Great Templates | Great Books | Testimonials | Tech.Articles | TOS | AUS | Home | Linux Apache MySQL PHP