Perl Programming/Function reference

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: Concept index Index Next: Keywords

String functions[edit | edit source]

chomp[edit | edit source]

Action[edit | edit source]

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

Returns[edit | edit source]

?

Syntax[edit | edit source]

chomp($String = $_);

Example[edit | edit source]

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

See also[edit | edit source]

  • chop - To remove the last character from a string

chop[edit | edit source]

Action[edit | edit source]

Removes the last character from a string regardless

Returns[edit | edit source]

?

Syntax[edit | edit source]

chop($String = $_);

Example[edit | edit source]

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

See also[edit | edit source]

  • chomp - To remove the last character from a string if it is a record seperator

Removes the last character from a string (e.g. removes the newline characters when reading from a file)

chr[edit | edit source]

print chr(65);  # Prints a capital A

Gets an ASCII character, given it's code

crypt[edit | edit source]

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

(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 $Salt;!

hex[edit | edit source]

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

index[edit | edit source]

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.

lc[edit | edit source]

$Lowercase = lc($String);

Converts a string to lower-case

lcfirst[edit | edit source]

Converts the first character of a string to lowercase

length[edit | edit source]

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

Returns the length of a string

oct[edit | edit source]

print oct(8);  # Prints 10

Converts a number to octal

ord[edit | edit source]

Converts a character to its number.

print ord("A"); # prints 65

pack[edit | edit source]

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 s, S, l, and L may be immediately followed by a ! suffix to signify native shorts or longs

reverse[edit | edit source]

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

my @ReversedList = reverse(@List);
# As commonly seen in Perl programs:
foreach( reverse( sort( @List )))
{
...
}
my $ReversedString = reverse($String);
my @List = ("One ", "two ", "three...");
my $ReversedListAsString = reverse(@List); # Prints "...eerht owt enO"

rindex[edit | edit source]

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)

sprintf[edit | edit source]

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[edit | edit source]

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'

uc[edit | edit source]

$Uppercase = uc($String);

Converts a string to upper-case

ucfirst[edit | edit source]

Converts the first character of a string to uppercase

Numeric functions[edit | edit source]

abs[edit | edit source]

Returns the absolute (positive) value of a number

$Number = abs(-100); # Returns 100;

atan2[edit | edit source]

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

cos[edit | edit source]

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

exp[edit | edit source]

# Raises e to a specified power
$Number = exp(2); # Returns e^2
e ≈ 2.71828183 more about e

hex[edit | edit source]

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

int[edit | edit source]

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

log[edit | edit source]

# Returns the natural logarithm of a number
$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

oct[edit | edit source]

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

rand[edit | edit source]

# Gets a random number (may automatically call srand() if that's not been done)
$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

sin[edit | edit source]

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

sqrt[edit | edit source]

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

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

srand[edit | edit source]

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

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

Array functions[edit | edit source]

pop[edit | edit source]

$LastElement = pop(@MyArray);

Take the last element from an array.

push[edit | edit source]

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

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

shift[edit | edit source]

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[edit | edit source]

# Removes elements from an array, optionally replacing them with a new 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

unshift[edit | edit source]

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

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

List functions[edit | edit source]

grep[edit | edit source]

# Returns a list of elements for which an expression is true
@TextFiles = grep(/\.txt$/, @AllFiles);
$NumberOfTextFiles = grep(/\.txt$/, @AllFiles);
# Can use a block of code instead of an expression
@TextFiles = grep({return(substr($_, -3) eq "txt");}, @AllFiles);

join[edit | edit source]

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

map[edit | edit source]

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

reverse[edit | edit source]

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

sort[edit | edit source]

# Sorts the elements in a list
@AsciiSort = sort(@RandomList);
@AsciiSort = sort @RandomList;
foreach $Item (sort @RandomList)
  {...}
# Can specify a function to decide the sort order
@CaseInsensitiveSort = sort {uc($a) cmp uc($b)} @RandomList;
@NumericSort = sort {$a <=> $b} @RandomList;
@CustomSort = sort custom_function_name @RandomList;

unpack[edit | edit source]

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

Associative array functions[edit | edit source]

delete[edit | edit source]

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

each[edit | edit source]

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

exists[edit | edit source]

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

keys[edit | edit source]

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

values[edit | edit source]

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

Input and output functions[edit | edit source]

binmode[edit | edit source]

close[edit | edit source]

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

closedir[edit | edit source]

# Close a directory open by opendir
closedir(DIRHANDLE);

dbmclose[edit | edit source]

dbmopen[edit | edit source]

die[edit | edit source]

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

 die "Error: $!\n" unless chdir '/';

eof[edit | edit source]

eof FILEHANDLE
eof()
eof

This function returns true, if the next read on FILEHANDLE would return end-of-file, or if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle, or a reference to a filehandle object of some sort. An eof without an argument returns the end-of-file status for the last file read. An eof() with empty parentheses () tests the ARGV filehandle (most commonly seen as the null filehandle in <>). Therefore, inside a while (<>) loop, an eof() 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:

while (<>) {
    if (eof()) {
        print "-" x 30, "\n";
    }
    print;
}

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

# reset line numbering on each input file
while (<>) {
    next if /^\s*#/;        # skip comments
    print "$.\t$_";
} continue {
    close ARGV if eof;      # Not eof()!
}

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

while (<>) {
    print if /pattern/ .. eof;
}

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 @ARGV

fileno[edit | edit source]

flock[edit | edit source]

format[edit | edit source]

getc[edit | edit source]

print[edit | edit source]

Prints the parameters given.

Discussed in the following sections:

Digression on print in Strings section

printf[edit | edit source]

read[edit | edit source]

readdir[edit | edit source]

rewinddir[edit | edit source]

seek[edit | edit source]

seekdir[edit | edit source]

select[edit | edit source]

syscall[edit | edit source]

sysread[edit | edit source]

sysseek[edit | edit source]

syswrite[edit | edit source]

tell[edit | edit source]

telldir[edit | edit source]

truncate[edit | edit source]

warn[edit | edit source]

write[edit | edit source]

Functions for working with fixed length records[edit | edit source]

pack[edit | edit source]

See the entry for pack further up the page

read[edit | edit source]

# Reads data from a file-handle
read(FILEHANDLE, $StoreDataHere, $NumberBytes);
# Returns the number of bytes read
$NumberBytesRead = read(FILEHANDLE, $StoreDataHere, $NumberBytes);
# Optional offset is applied when the data is stored (not when reading)
read(FILEHANDLE, $StoreDataHere, $NumberBytes, Offset);

syscall[edit | edit source]

# Runs a system command
syscall( $Command, $Argument1, $Argument2, $Argument3);
# (maximum 14 arguments)
$ReturnValue = syscall($Command);

sysread[edit | edit source]

syswrite[edit | edit source]

unpack[edit | edit source]

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

vec[edit | edit source]

Filesystem functions[edit | edit source]

-X[edit | edit source]

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[edit | edit source]

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

chmod[edit | edit source]

chmod 0744 $File1;
chmod 0666 $File1, $File2, $File3;
# 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[edit | edit source]

# Change the owner of a file
chown($NewUserID, $NewGroupID, $Filename);
chown($
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[edit | edit source]

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.

l[edit | edit source]

fcntlglob[edit | edit source]

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

See also File::Glob.

ioctl[edit | edit source]

link[edit | edit source]

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

lstat[edit | edit source]

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

mkdir[edit | edit source]

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

open[edit | edit source]

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[edit | edit source]

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

readlink[edit | edit source]

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

rename[edit | edit source]

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 [[File::Copy]] for more complicated file operations.

rmdir[edit | edit source]

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

t[edit | edit source]

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[edit | edit source]

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

umask[edit | edit source]

# Sets or returns the umask for the process.
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

unlink[edit | edit source]

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

utime[edit | edit source]

# Updates the modification times of a list of files
my $AccessTime = time();
my $ModificationTime = time();
utime($AccessTime, $ModificationTime, $Filename);
my $NumFilesChanged = utime($AccessTime, $ModificationTime, $File1, $File2, $File3);

Program functions[edit | edit source]

caller[edit | edit source]

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.

# !/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);
 }

import[edit | edit source]

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.

package[edit | edit source]

Declares all lines that follow (until EOF or the next package statement) to belong to the given package's namespace.

# !/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

require[edit | edit source]

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 '.pm' extention is added, and :: is replaced with the current operating system's path seperator:

require Foo::Bar;
# identical to:
require 'Foo/Bar.pm';

use[edit | edit source]

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/;
}

Misc functions[edit | edit source]

defined[edit | edit source]

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

dump[edit | edit source]

eval[edit | edit source]

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

formline[edit | edit source]

local[edit | edit source]

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

my[edit | edit source]

# creates new lexical (ie, not global) variable
$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

reset[edit | edit source]

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

scalar[edit | edit source]

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

undef[edit | edit source]

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

wantarray[edit | edit source]

# returns 'true', 'false', or undef if function that called it was called in list, scalar, or void context, respectively.
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";
   }
}

Processes[edit | edit source]

alarm[edit | edit source]

exec[edit | edit source]

fork[edit | edit source]

# clones the current process, returning 0 if clone, and the process id of the clone if the parent
my $pid = fork();
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";
}

getpgrp[edit | edit source]

getppid[edit | edit source]

getpriority[edit | edit source]

kill[edit | edit source]

pipe[edit | edit source]

qx/STRING/[edit | edit source]

setpgrp[edit | edit source]

setpriority[edit | edit source]

sleep[edit | edit source]

system[edit | edit source]

times[edit | edit source]

wait[edit | edit source]

waitpid[edit | edit source]

Modules[edit | edit source]

do[edit | edit source]

import[edit | edit source]

no[edit | edit source]

package[edit | edit source]

require[edit | edit source]

use[edit | edit source]

Classes and objects[edit | edit source]

See also Perl Objects

bless[edit | edit source]

dbmclose[edit | edit source]

dbmopen[edit | edit source]

package[edit | edit source]

ref[edit | edit source]

tie[edit | edit source]

tied[edit | edit source]

untie[edit | edit source]

use[edit | edit source]

Sockets[edit | edit source]

accept[edit | edit source]

bind[edit | edit source]

nect[edit | edit source]

getpeername[edit | edit source]

getsockname[edit | edit source]

getsockopt[edit | edit source]

en[edit | edit source]

listennd[edit | edit source]

setsockopt[edit | edit source]

shutdown[edit | edit source]

socket[edit | edit source]

socketpair[edit | edit source]

Login information[edit | edit source]

endgrent[edit | edit source]

endhostent[edit | edit source]

endnetent[edit | edit source]

endpwent[edit | edit source]

getgrent[edit | edit source]

getgrgid[edit | edit source]

getgrnam[edit | edit source]

getlogin[edit | edit source]

getpwent[edit | edit source]

getpwnam[edit | edit source]

getpwuid[edit | edit source]

setgrent[edit | edit source]

setpwent[edit | edit source]

Network information[edit | edit source]

endprotoent[edit | edit source]

endservent[edit | edit source]

gethostbyaddr[edit | edit source]

ame[edit | edit source]

bynamegethostent[edit | edit source]

getnetbyaddr[edit | edit source]

getnetbyname[edit | edit source]

getnetent[edit | edit source]

getprotobyname[edit | edit source]

number[edit | edit source]

getprotoent[edit | edit source]

getservbyname[edit | edit source]

getservbyport[edit | edit source]

getservent[edit | edit source]

sethostent[edit | edit source]

setnetent[edit | edit source]

setprotoent[edit | edit source]

setservent[edit | edit source]

Time and date[edit | edit source]

gmtime[edit | edit source]

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

localtime[edit | edit source]

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[edit | edit source]

$Time = time();

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

See also Time::Hires

times[edit | edit source]

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

Functions that reverse each other[edit | edit source]

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 1 to standard output,

ord() will convert a character to its number in the character set, while chr() will convert a number to its corresponding character, therefore

in the same way that and in Mathematics (assuming x is non-negative), ord(chr(1)) = 1 and chr(ord(1)) = 1 in Perl.

List of functions that reverse each other:


Previous: Concept index Index Next: Keywords