Perl Programming/Function reference

Action
Removes the last characters from a string only if they're recognized as a record separator (e.g. a newline character)

Returns
?

Syntax
chomp($String = $_);

Example
chomp; # removes the last character from $_ if it is a record separator chomp; # (same) chomp($String); # removes the last character from $String if it is a record separator

Action
Removes the last character from a string regardless

Returns
?

Syntax
chop($String = $_);

Example
chop; # removes the last character from $_ chop; # (same) chop($String); # removes the last character from $String

print chr(65); # Prints a capital A

Gets an ASCII character, given it's code

my $HashedWord = crypt($Word, $Salt);
 * 1) One-way hash function

(See also MD5 )

The salt string needs only be two characters long, and provides a way of randomising the hash, such that the same word can produce several different hashes, if used with different values of !

print hex(11); # Prints B

Converts a number to hexadecimal

Other way around - converts hex to number: print hex(11); # prints 17

you can use

print sprintf("%X",11); # Prints B

Search for one string within another (see rindex to search from end-to-start).

$Result = index($Haystack, $Needle); $Result = index($Haystack, $Needle, $StartPosition);

index("Some text", "bleh"); # Returns -1 (not found) index("Some text", "Some"); # Returns 0 (first character) index("Some text", "text"); # Returns 5 (sixth character)

The special variable  always gets added to the return value, but   is normally 0, and the manual recommends leaving it at 0.

$Lowercase = lc($String);

Converts a string to lower-case

Converts the first character of a string to lowercase

print "String is ". length($String). " characters long\n";

Returns the length of a string

print oct(8); # Prints 10

Converts a number to octal

Converts a character to its number.

print ord("A"); # prints 65

Takes a list and converts it into a string using a supplied set of rules.

my $String = pack($Template, @ListOfNumbers); my $String = pack("CCCC",65,66,67,68); # Result: "ABCD"

$Template can be made up of:

a	A string with arbitrary binary data, will be null padded. A	An ascii string, will be space padded. Z	A null terminated (asciz) string, will be null padded.

b	A bit string (ascending bit order inside each byte, like vec). B	A bit string (descending bit order inside each byte). h	A hex string (low nybble first). H	A hex string (high nybble first).

c	A signed char value. C	An unsigned char value. Only does bytes. See U for Unicode.

s	A signed short value. S	An unsigned short value. (Exactly 16 bits unless you use the ! suffix)

i	A signed integer value. I	An unsigned integer value. (At least 32 bits wide, machine-dependent)

l	A signed long value. L	An unsigned long value. (Exactly 32 bits unless you use the ! suffix)

n	An unsigned short in "network" (big-endian) order. N	An unsigned long in "network" (big-endian) order. v	An unsigned short in "VAX" (little-endian) order. V	An unsigned long in "VAX" (little-endian) order. (Exactly 16 bits and 32 bits respectively)

q	A signed quad (64-bit) value. Q	An unsigned quad value. (Only available if your system supports 64-bit integers and Perl has been compiled to support them)

f	A single-precision float in the native format. d	A double-precision float in the native format.

p	A pointer to a null-terminated string. P	A pointer to a structure (fixed-length string).

u	A uuencoded string. U	A Unicode character number. Encodes to UTF-8 internally.

w	A BER compressed integer. Its bytes represent an unsigned integer in base 128, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last.

x	A null byte. X	Back up a byte. @	Null fill to absolute position.

Each letter may optionally be followed by a number giving a repeat count.

The integer types,  ,  , and   may be immediately followed by a   suffix to signify native shorts or longs

Reverses a string (in scalar context) or a list (in list context):

my @ReversedList = reverse(@List);

foreach( reverse( sort( @List ))) { ... }
 * 1) As commonly seen in Perl programs:

my $ReversedString = reverse($String);

my @List = ("One ", "two ", "three..."); my $ReversedListAsString = reverse(@List); # Prints "...eerht owt enO"

Search for one string within another, starting at the end of the string.

$Result = rindex($Haystack, $Needle); $Result = rindex($Haystack, $Needle, $StartPosition);

rindex("Some text", "bleh"); # Returns -1 (not found) rindex("Some text", "Some"); # Returns 0 (first character) rindex("abbbbb", "b");      # Returns 5 (first "b" found, when starting at the end)

Prints a formatted string:

my $Text = sprintf("%d/%d is %08.5f", 1, 3, 1/3); # Result: "10/3 is 003.33333"

sprintf("Character: %c", 65); sprintf("String %s", "Hello"); sprintf("Signed integer: %d", 15); sprintf("Unsigned integer: %u", 15); sprintf("Unsigned int (in octal): %o", 15); sprintf("Unisgned int (in hex): %x", 15);     # Use %X to get upper-case output sprintf("Binary number: %b", 15); sprintf("Scientific notation: %e", 5000);     # Use %E to get upper-case output sprintf("Floating point number: %f", 1/3);    # 0.3333333 sprintf("Floating point number: %g", 1/3);    # Decides between scientific and float. %G is uppercase sprintf("Pointer: %p", $Variable);

Use %% to get a percent-sign.

Use %n to request the number of characters written so far, and put it into the next variable in the list. You may want to check that user-supplied formatting rules don't contain this code.

sprintf("%02d", $Minutes); # Forces leading zeros to make the string two characters long sprintf("%1.5f", $Number); # Limits the number of decimal places

substr
Return part of a string (a substring)

Format: substr string start-position length


 * start-position is zero-based.
 * A negative number starts from the end of the string.

$FirstLetter  = substr($Text, 0, 1);   # First letter $First3Letters = substr($Text, 0, 3);  # First three letters $Last3Letters = substr($Text, -3);     # Last three letters

You can use substr on the left side of an assignment statement to change part of a string. This can actually shorten or lengthen the string.

$text = 'cat dog'; substr ($mystring, 3, 1) = ' and '; # $text now contains 'cat and dog'

$Uppercase = uc($String);

Converts a string to upper-case

Converts the first character of a string to uppercase

Returns the absolute (positive) value of a number $Number = abs(-100); # Returns 100;

$Number = atan2($Y, $X);
 * 1) Converts cartesian(x,y) coordinates into an angle

$Number = cos($Angle); # Cosine = Adjacent/Hypotenuse
 * 1) Returns the cosine of an angle (radians)

$Number = exp(2); # Returns
 * 1) Raises e to a specified power

e &asymp; 2.71828183 more about e

$Number = hex("10"); # Returns 16 $Number = hex("0xFF"); # Returns 255
 * 1) Interprets a string as hexidecimal, and returns its value

Rounds a number towards zero, returning an integer $Number = int(-1.6); # Returns -1 $Number = int(0.9);  # Returns 0 $Number = int(28.54); # Returns 28

$Number = log(2.71828183);  # Returns 1 $Number = exp(log($X));     # Returns $X $Number = log($X)/log(10);  # Returns log10($X). Alternately, you can use the log10 function in the POSIX module $Number = log($X)/log(15);  # Returns log to the base 15 of $X
 * 1) Returns the natural logarithm of a number

$Number = oct("10"); # Returns 8 $Number = oct("21"); # Returns 17
 * 1) Interprets a string as octal, and returns its value

$Number = rand; # Returns a random number from 0 to 1 $Number = int(rand(800)); # Returns a random integer from 0 to 799 $Number = 1 + int(rand(999)); # Returns a random integer from 1 to 999
 * 1) Gets a random number (may automatically call srand if that's not been done)

$Number = sin($Angle); # Sine = Opposite/Hypotenuse
 * 1) Returns the sine of an angle (radians)

$Number = sqrt(4);                 # Returns 2 $Number = sqrt($X ** 2 + $Y ** 2); # Returns the diagonal distance across a $X x $Y rectangle
 * 1) Returns the square-root of a number

See the  module, if you need to take roots of negative numbers.

srand;
 * 1) Seeds (sets-up) the random-number generator

Version-dependent, and older versions of Perl are not guaranteed to have a good seed value. See the  module for more possibilities. The current version of Perl uses the urandom device if it's available.

$LastElement = pop(@MyArray);

Take the last element from an array.

push(@MyArray, "Last element"); push(@MyArray, "several", "more", "elements");

Push a list of elements onto the end of an array.

shift(@MyArray); # Delete the first element $FirstElement = shift(@MyArray); # Delete the first element, load it into $FirstElement instead

Take the first element out of an array.

splice(@Array); # Removes all elements from array splice(@Array, 10); # Removes from element 10 to the end of the array splice(@Array, -10); # Removes the last 10 elements of the array splice(@Array, 0, 10); # Removes the first 10 elements of the array @NewArray = splice(@Array, 0, 10); # Removes the first 10 elements of the array and returns those 10 items splice(@Array, 0, 10, @Array2); # Replaces the first 10 elements of the array with Array2
 * 1) Removes elements from an array, optionally replacing them with a new array

unshift(@MyArray, "New element"); unshift(@MyArray, "several", "more", "elements");

Add a list of elements onto the beginning of an array.

@TextFiles = grep(/\.txt$/, @AllFiles); $NumberOfTextFiles = grep(/\.txt$/, @AllFiles);
 * 1) Returns a list of elements for which an expression is true

@TextFiles = grep({return(substr($_, -3) eq "txt");}, @AllFiles);
 * 1) Can use a block of code instead of an expression

$OneItemPerLine = join( "\n", @List); $EverythingBunchedTogether = join( "", @List); $Filename = join( "/", ($Directory, $Subdirectory, $Filename));
 * 1) Joins the items of a list into a single string

@UppercaseList = map(uc, @List); @Numbers = map {"Number $_"} 1..100;
 * 1) Evaluates a block of code for each item in a list, and returns
 * 2) a list of the results

@ReversedList = reverse(@List); $ReversedString = reverse('foo','bar','baz'); # gives 'zabraboof'
 * 1) Reverses the order of a list
 * 1) In scalar context, concatenates the list and then reverses the string

@AsciiSort = sort(@RandomList); @AsciiSort = sort @RandomList; foreach $Item (sort @RandomList) {...}
 * 1) Sorts the elements in a list

@CaseInsensitiveSort = sort {uc($a) cmp uc($b)} @RandomList; @NumericSort = sort {$a <=> $b} @RandomList; @CustomSort = sort custom_function_name @RandomList;
 * 1) Can specify a function to decide the sort order

Unpacks a string into a list - see the templates available for the pack function for details

%h = ('a'=>1, 'cow'=>'moo', 'b'=>2); delete $h{cow};
 * 1) Remove an element from a hash
 * 1) %h now contains ('a'=>1, 'b'=>2)

while (($key, $value) = each (%hash)) { print "$key => $value\n"; }
 * 1) Return the 'next' key/value pair (in a random order)

# Tests whether or not a key exists in a hash (even if the value for that key is undef) if (exists $hash{$key}) { print "\%hash contains a value for key '$key'\n"; }

# Returns a list of all keys from the hash, in same 'random' order as each foreach $key (keys %hash) { print "$key => $hash{$key}\n"; }

# Returns a list of all values from the hash, in same 'random' order as keys foreach $value (values %hash) { print "\%hash contains a value '$value'\n"; }

close(STDERR); # hide debugging info from the user
 * 1) closes a filehandle when it is no longer needed

closedir(DIRHANDLE);
 * 1) Close a directory open by opendir

Exits the program, printing to "STDERR" the first parameter and the current file and line. Used to trap errors.

This function returns, if the next read on   would return end-of-file, or if   is not open. may be an expression whose value gives the real filehandle, or a reference to a filehandle object of some sort. An  without an argument returns the end-of-file status for the last file read. An  with empty parentheses   tests the   filehandle (most commonly seen as the null filehandle in  ). Therefore, inside a while loop, an   with parentheses will detect the end of only the last of a group of files. Use eof (without the parentheses) to test each file in a while loop. For example, the following code inserts dashes just before the last line of the last file:

On the other hand, this script resets line numbering on each input file:

Like " " in a sed program, eof tends to show up in line number ranges. Here's a script that prints lines from  to end of each input file:

Here, the flip-flop operator evaluates the pattern match for each line. Until the pattern matches, the operator returns false. When it finally matches, the operator starts returning true, causing the lines to be printed. When the eof operator finally returns true (at the end of the file being examined), the flip-flop operator resets, and starts returning false again for the next file in

Prints the parameters given.

Discussed in the following sections:
 * Digression on print in Strings section

See the entry for   further up the page

read(FILEHANDLE, $StoreDataHere, $NumberBytes);
 * 1) Reads data from a file-handle

$NumberBytesRead = read(FILEHANDLE, $StoreDataHere, $NumberBytes);
 * 1) Returns the number of bytes read

read(FILEHANDLE, $StoreDataHere, $NumberBytes, Offset);
 * 1) Optional offset is applied when the data is stored (not when reading)

syscall( $Command, $Argument1, $Argument2, $Argument3);
 * 1) Runs a system command

$ReturnValue = syscall($Command);
 * 1) (maximum 14 arguments)

unpack($Template, $BinaryData);
 * 1) See the pack function for details (unpack does the opposite!)

if (-r	$FullFilename) // File is readable by effective uid/gid. if (-w	$FullFilename) // File is writable by effective uid/gid. if (-x	$FullFilename) // File is executable by effective uid/gid. if (-o	$FullFilename) // File is owned by effective uid.

if (-R	$FullFilename) // File is readable by real uid/gid. if (-W	$FullFilename) // File is writable by real uid/gid. if (-X	$FullFilename) // File is executable by real uid/gid. if (-O	$FullFilename) // File is owned by real uid.

if (-e	$FullFilename) // File exists. if (-z	$FullFilename) // File has zero size. if (-s	$FullFilename) // File has nonzero size (returns size).

if (-f	$FullFilename) // File is a plain file. if (-d	$FullFilename) // File is a directory. if (-l	$FullFilename) // File is a symbolic link. if (-p	$FullFilename) // File is a named pipe (FIFO), or Filehandle is a pipe. if (-S	$FullFilename) // File is a socket. if (-b	$FullFilename) // File is a block special file. if (-c	$FullFilename) // File is a character special file. if (-t	$FullFilename) // Filehandle is opened to a tty.

if (-u	$FullFilename) // File has setuid bit set. if (-g	$FullFilename) // File has setgid bit set. if (-k	$FullFilename) // File has sticky bit set.

if (-T	$FullFilename) // File is an ASCII text file. if (-B	$FullFilename) // File is a "binary" file (opposite of -T).

$Age = -M $FullFilename; // Age of file in days when script started. $Age = -A $FullFilename; // Same for access time. $Age = -C $FullFilename; // Same for inode change time.

chdir $Directory; chdir $Directory || die("Couldn't change directory");

chmod 0744 $File1; chmod 0666 $File1, $File2, $File3;
 * 1) 0 for octal, at the beginning of a number

| Owner | Group | Others | Execute |  4   |   4   |   4    | Write  |   2   |   2   |   2    | Read   |   1   |   1   |   1    | ======--+======-+======-+======--+ Total  |       |       |        |

chown($NewUserID, $NewGroupID, $Filename); chown($
 * 1) Change the owner of a file

NewUserID $NewGroupID, $File1, $File2, $File3); NewUserID, $NewGroupID, $File1, $File2, $File3);

chown($NewUserID, -1, $Filename); # Leave group unchanged chown(-1, $NewGroupID, $Filename); # Leave user unchanged

chroot $NewRootDirectory;

Sets the root directory for the program, such that the " " location refers to the specified directory.

Program must be running as root for this to succeed.

my @TextFiles = glob("*.txt");
 * 1) Expands filenames, in a shell-like way

See also.

link($ExistingFile, $LinkLocation); link($ExistingFile, $LinkLocation) || die("Couldn't create link");
 * 1) Creates a link to a file

Identical to stat, except that if given file is symbolic link, stat link not the target.

mkdir $Filename || die("Couldn't create directory"); mkdir $Filename, 0777; # Make directory with particular file-permissions

open(my $FileHandle, $Filename) || die("Couldn't open file"); open(my $fp, "<", $Filename);  # Read from file open(my $fp, ">", $Filename);  # Write to file open(my $fp, ">>", $Filename); # Append to file

open(my $fp, "<$Filename");    # Read from file open(my $fp, ">$Filename");    # Write to file open(my $fp, ">>$Filename");   # Append to file

open(my $fp, "<", "./  filename with whitespace   \0"); open(my $fp, "<", "./->filename with reserved characters\0");

open(my $fp, "$Program |");    # Read from the output of another program open(m myy $fp, "| $Program");    # Write to the input of another program

open(my $fp, "<", "-");        # Read from standard input open(my $fp, ">", "-");        # Write to standard output

opendir(my $DirHandle, $Directory) || die("Couldn't open directory");

while (my $Filename = readdir $DirHandle) { # Do something with $Filename in $Directory } closedir($DirHandle);

opendir(DIR, $Directory) || die("Couldn't open directory");

foreach(readdir(DIR)) { # Do something with $_ in $Directory } closedir(DIR);

$LinkTarget = readlink($LinkPosition);
 * 1) Finds the value of a symbolic link

rename $OldFile, $NewFile or die("Couldn't move file");

May work differently on non-*nix operating systems, and possibly not at all when moving between different filesystems. See for more complicated file operations.

rmdir $Filename || die("Couldn't remove directory");

stat

$DeviceNum   = $FileStatistics[0]; # device number of filesystemcs[0]; # device number of filesystem $Inode       = $FileStatistics[1]; # inode number $FileMode    = $FileStatistics[2]; # (type and permissions) $NumHardLinks = $FileStatistics[3]; # number of (hard) links to the file $UserID      = $FileStatistics[4]; # numeric user ID $GroupID      = $FileStatistics[5]; # numeric group ID $DeviceIdent  = $FileStatistics[6]; # Device identifier (special files only) $SizeBytes   = $FileStatistics[7]; $AccessTime  = $FileStatistics[8]; # seconds since the epoch $ModifyTime  = $FileStatistics[9]; $ChangeTime  = $FileStatistics[10]; $BlockSize   = $FileStatistics[11]; $NumBlocks   = $FileStatistics[12];

symlink($OldFilename, $NewFilename); symlink($OldFilename, $NewFilename) || die("Couldn't create symlink"); eval(symlink($OldFilename, $NewFilename));
 * 1) Creates a new filename symbolically linked to the old filename

my $UMask = umask; umask(0000); # This process can create any type of files umask(0001); # This process can't create world-readable files umask(0444); # This process can't create executable files
 * 1) Sets or returns the umask for the process.

unlink $Filename; unlink $Filename || die("Couldn't delete file"); unlink $File1, $File2, $File3; (unlink($File1, $File2, $File3) == 3) || die("Couldn't delete files");
 * 1) Deletes a file

my $AccessTime = time; my $ModificationTime = time;
 * 1) Updates the modification times of a list of files

utime($AccessTime, $ModificationTime, $Filename); my $NumFilesChanged = utime($AccessTime, $ModificationTime, $File1, $File2, $File3);

Returns information about the current function call stack. In scalar context, returns only the name of the package from where the current subroutine was called. In list context, returns the package, filename, and line number. In list context with a numeric argument passed, returns several pieces of information (see below). The argument represents how many levels in the call stack to go back.


 * 1) !/usr/bin/perl

foo; sub foo { $package = caller; # returns 'main' ($package, $filename, $line) = caller; # returns 'main', the file name, and 3 # Line below returns all 10 pieces of info. (Descriptions self-explanatory from variable names) ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(0); }

There is no actual 'import' function. Rather, it is a convention when writing a module to create a subroutine named 'import' that populates the current namespace with that module's needed variables or methods.

The standard 'Exporter' module provides an import method, if your class has it as a base class.

Declares all lines that follow (until EOF or the next package statement) to belong to the given package's namespace.
 * 1) !/usr/bin/perl

$x = 5; # sets $main::x

package Foo; $x = 5; # sets $Foo::x sub bar { # defines &Foo::bar print "hello world"; }

package Temp; $x = 5; # sets $Temp::x

includes the specified module's code into the current program. The module can be specified either with an absolute or relative path, or with a bareword. If a bareword is given, a ' ' extention is added, and  is replaced with the current operating system's path seperator:

require Foo::Bar; require 'Foo/Bar.pm';
 * 1) identical to:

Requires and imports the given module or pragma, at compile time. The line

use Foo qw/bar baz/;

is identical to

BEGIN { require Foo; import Foo qw/bar baz/; }

$x = 0; print "X defined\n" if defined $x; # prints print "Y defined\n" if defined $y; # does not print
 * 1) returns true, if argument is not undef

eval('$a = 30; $b = 40;'); print $a, $b;

$x = 5; print "x = $x\n"; # 5 {  local $x = 10; print "x = $x\n"; # 10 } print "x = $x\n"; # 5
 * 1) assigns temporary value to global variable for duration of lexical scope

$x = 5; # refers to $main::x {  my $x = 10; print "x = $x\n"; # the lexical - 10 print "main's x = $main::x\n" # the global - 5 } print "x = $x\n"; # the global, because no lexical in scope - 5
 * 1) creates new lexical (ie, not global) variable

while ($k, $v = each %h) { print "$k = $v\n"; last if ($i++ == 2); } reset %h
 * 1) resets hash's internal pointer, to affect lists returned by each
 * 1) if another each done here, $k,$v will pick up where they left off.
 * 1) now each will restart from the beginning.

@sizes = (scalar @foo, scalar @bar);
 * 1) forces scalar context on an array
 * 1) creates a list of the sizes of @foo and @bar, rather than the elements in @foo and @bar

$x = 5; undef $x; print "x = $x\n" if defined $x; # does not print
 * 1) undefines an existing variable

sub fctn { my @vals = (5..10); if (wantarray) { return @vals; } elsif (defined wantarray) { return $vals[0]; } else { warn "Warning! fctn called in void context!\n"; } }
 * 1) returns 'true', 'false', or undef if function that called it was called in list, scalar, or void context, respectively.

my $pid = fork;
 * 1) clones the current process, returning 0 if clone, and the process id of the clone if the parent

if ($pid == 0) { print "I am a copy of the original\n"; } elsif ($pid == -1) { print "I can't create a clone for some reason!\n"; } else { print "I am the original, my clone has a process id of $pid\n"; }

Classes and objects
See also Perl Objects

Converts a timestamp to GMT.

@TimeParts = gmtime; @TimeParts = gmtime($Time);

$Seconds   = $TimeParts[0]; # 0-59 $Minutes   = $TimeParts[1]; # 0-59 $Hours     = $TimeParts[2]; # 0-23 $DayOfMonth = $TimeParts[3]; # 1-31 $Month     = $TimeParts[4]; # 0-11 $Year      = $TimeParts[5]; # Years since 1900 $DayOfWeek = $TimeParts[6]; # 0:Sun 1:Mon 2:Tue 3:Wed 4:Thu 5:Fri 6:Sat $DayOfYear = $TimeParts[7]; # 1-366

Converts a timestamp to local time.

@TimeParts = localtime; @TimeParts = localtime($Time);

$Seconds   = $TimeParts[0]; # 0-59 $Minutes   = $TimeParts[1]; # 0-59 $Hours     = $TimeParts[2]; # 0-23 $DayOfMonth = $TimeParts[3]; # 1-31 $Month     = $TimeParts[4]; # 0-11 $Year      = $TimeParts[5]; # Years since 1900 $DayOfWeek = $TimeParts[6]; # 0:Sun 1:Mon 2:Tue 3:Wed 4:Thu 5:Fri 6:Sat $DayOfYear = $TimeParts[7]; # 1-366

$Time = time;

Returns number of seconds since an epoch (that is system-dependent, but may be 1970-01-01).

See also ../Time::Hires/

@CPUTimes = times; $UserTimeForProcess   = $CPUTimes[0]; $SystemTimeForProcess = $CPUTimes[1]; $UserTimeForChildren  = $CPUTimes[2]; $SystemTimeForChildren = $CPUTimes[3];

Functions that reverse each other
Some functions in perl reverse or otherwise cancel the effect of each other, so running a string through both of them will produce the same output as the input, for example

print ord(chr(1));

will echo  to standard output,

will convert a character to its number in the character set, while  will convert a number to its corresponding character, therefore

in the same way that $$\sqrt{x^2} = x$$ and $$\sqrt{x}^2 = x$$ in Mathematics (assuming x is non-negative),  and   in Perl.

List of functions that reverse each other:


 * and
 * and
 * and
 * and
 * and
 * and