Perl Programming/Function Reference

Previous: Humour Index Next: Useful modules

String functionsEdit

chompEdit

ActionEdit

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

ReturnsEdit

?

SyntaxEdit

chomp($String = $_);

ExampleEdit

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 AlsoEdit

  • chop - To remove the last character from a string

chopEdit

ActionEdit

Removes the last character from a string regardless

ReturnsEdit

?

SyntaxEdit

chop($String = $_);

ExampleEdit

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

See AlsoEdit

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

chrEdit

print chr(65);  # Prints a capital A

Gets an ASCII character, given it's code

cryptEdit

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

(See also MD5 )

The salt string needs only be 2 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;!

hexEdit

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

indexEdit

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.

lcEdit

$Lowercase = lc($String);

Converts a string to lower-case

lcfirstEdit

Converts the first character of a string to lowercase

lengthEdit

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

Returns the length of a string

octEdit

print oct(8);  # Prints 10

Converts a number to octal

ordEdit

Converts a character to its number.

print ord("A"); # prints 65

packEdit

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

reverseEdit

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"

rindexEdit

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)

sprintfEdit

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 2 characters long
sprintf("%1.5f", $Number);  # Limits the number of decimal places

substrEdit

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'

ucEdit

$Uppercase = uc($String);

Converts a string to upper-case

ucfirstEdit

Converts the first character of a string to uppercase

Numeric functionsEdit

absEdit

Returns the absolute(positive) value of a number

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

atan2Edit

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

cosEdit

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

expEdit

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

hexEdit

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

intEdit

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

logEdit

# 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

octEdit

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

randEdit

# 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

sinEdit

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

sqrtEdit

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

srandEdit

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

Version-dependant, 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 functionsEdit

popEdit

$LastElement = pop(@MyArray);

Take the last element from an array

pushEdit

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

Push a list of elements onto the end of an array

shiftEdit

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

spliceEdit

# 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

unshiftEdit

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

Add a list of elements onto the beginning of an array

List functionsEdit

grepEdit

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

joinEdit

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

mapEdit

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

reverseEdit

# 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'

sortEdit

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

unpackEdit

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

Associative array functionsEdit

deleteEdit

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

eachEdit

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

existsEdit

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

keysEdit

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

valuesEdit

 #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 functionsEdit

binmodeEdit

closeEdit

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

closedirEdit

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

dbmcloseEdit

dbmopenEdit

dieEdit

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

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

eofEdit

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

filenoEdit

flockEdit

formatEdit

getcEdit

printEdit

Prints the parameters given.

Discussed in the following sections:

Digression on print in Strings section

printfEdit

readEdit

readdirEdit

rewinddirEdit

seekEdit

seekdirEdit

selectEdit

syscallEdit

sysreadEdit

sysseekEdit

syswriteEdit

tellEdit

telldirEdit

truncateEdit

warnEdit

writeEdit

Functions for working with fixed length recordsEdit

packEdit

See the entry for pack further up the page

readEdit

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


syscallEdit

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


sysreadEdit

syswriteEdit

unpackEdit

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

vecEdit

Filesystem functionsEdit

-XEdit

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.  

chdirEdit

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

chmodEdit

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

chownEdit

# Change the owner of a file
chown($NewUserID, $NewGroupID, $Filename);
chown($NewUserID, $NewGroupID, $File1, $File2, $File3);
chown($NewUserID, -1, $Filename); # Leave group unchanged
chown(-1, $NewGroupID, $Filename); # Leave user unchanged

chrootEdit

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.

fcntlEdit

globEdit

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

See also File::Glob

ioctlEdit

linkEdit

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

lstatEdit

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

mkdirEdit

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

openEdit

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(my $fp, "| $Program");     # Write to the input of another program
open(my $fp, "<", "-");         # Read from standard input
open(my $fp, ">", "-");         # Write to standard output


opendirEdit

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

readlinkEdit

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

renameEdit

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.

rmdirEdit

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

statEdit

@FileStatistics = stat($Filename); 
$DeviceNum    = $FileStatistics[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];

symlinkEdit

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

umaskEdit

# 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

unlinkEdit

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

utimeEdit

# 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 functionsEdit

callerEdit

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

importEdit

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

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

packageEdit

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

requireEdit

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

useEdit

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 functionsEdit

definedEdit

#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

dumpEdit

evalEdit

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

formlineEdit

localEdit

#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

myEdit

#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

resetEdit

#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.

scalarEdit

#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

undefEdit

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

wantarrayEdit

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

ProcessesEdit

alarmEdit

execEdit

forkEdit

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

getpgrpEdit

getppidEdit

getpriorityEdit

killEdit

pipeEdit

qx/STRING/Edit

setpgrpEdit

setpriorityEdit

sleepEdit

systemEdit

timesEdit

waitEdit

waitpidEdit

ModulesEdit

doEdit

importEdit

noEdit

packageEdit

requireEdit

useEdit

Classes and objectsEdit

See also Perl Objects

blessEdit

dbmcloseEdit

dbmopenEdit

packageEdit

refEdit

tieEdit

tiedEdit

untieEdit

useEdit

SocketsEdit

acceptEdit

bindEdit

connectEdit

getpeernameEdit

getsocknameEdit

getsockoptEdit

listenEdit

recvEdit

sendEdit

setsockoptEdit

shutdownEdit

socketEdit

socketpairEdit

Login informationEdit

endgrentEdit

endhostentEdit

endnetentEdit

endpwentEdit

getgrentEdit

getgrgidEdit

getgrnamEdit

getloginEdit

getpwentEdit

getpwnamEdit

getpwuidEdit

setgrentEdit

setpwentEdit

Network informationEdit

endprotoentEdit

endserventEdit

gethostbyaddrEdit

gethostbynameEdit

gethostentEdit

getnetbyaddrEdit

getnetbynameEdit

getnetentEdit

getprotobynameEdit

getprotobynumberEdit

getprotoentEdit

getservbynameEdit

getservbyportEdit

getserventEdit

sethostentEdit

setnetentEdit

setprotoentEdit

setserventEdit

Time and dateEdit

gmtimeEdit

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

localtimeEdit

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

timeEdit

$Time = time();

Returns number of seconds since an epoch (which is system-dependant, but may be Jan 1 1970)

See also Time::Hires

timesEdit

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

Functions that reverse each otherEdit

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 \sqrt{x^2} = x and \sqrt{x}^2 = x 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: Humour Index Next: Useful modules
Last modified on 1 December 2012, at 15:30