Perl Programming/Function reference
String functions
editchomp
edit
Action
editRemoves the last characters from a string only if they're recognized as a record separator (e.g. a newline character)
Returns
edit?
Syntax
editchomp($String = $_);
Example
editchomp; # 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- chop - To remove the last character from a string
chop
edit
Action
editRemoves the last character from a string regardless
Returns
edit?
Syntax
editchop($String = $_);
Example
editchop; # removes the last character from $_ chop(); # (same) chop($String); # removes the last character from $String
See also
edit- 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
print chr(65); # Prints a capital A
Gets an ASCII character, given it's code
crypt
edit
# 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
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
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
$Lowercase = lc($String);
Converts a string to lower-case
lcfirst
edit
Converts the first character of a string to lowercase
length
edit
print "String is " . length($String) . " characters long\n";
Returns the length of a string
oct
edit
print oct(8); # Prints 10
Converts a number to octal
ord
edit
Converts a character to its number.
print ord("A"); # prints 65
pack
edit
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
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
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
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
editReturn 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
$Uppercase = uc($String);
Converts a string to upper-case
ucfirst
edit
Converts the first character of a string to uppercase
Numeric functions
editabs
edit
Returns the absolute (positive) value of a number
$Number = abs(-100); # Returns 100;
atan2
edit
# Converts cartesian(x,y) coordinates into an angle $Number = atan2($Y, $X);
cos
edit
# Returns the cosine of an angle (radians) $Number = cos($Angle); # Cosine = Adjacent/Hypotenuse
exp
edit
# Raises e to a specified power
$Number = exp(2); # Returns e^2
e ≈ 2.71828183 more about e
hex
edit
# Interprets a string as hexidecimal, and returns its value $Number = hex("10"); # Returns 16 $Number = hex("0xFF"); # Returns 255
int
edit
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
# 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
# Interprets a string as octal, and returns its value $Number = oct("10"); # Returns 8 $Number = oct("21"); # Returns 17
rand
edit
# 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
# Returns the sine of an angle (radians) $Number = sin($Angle); # Sine = Opposite/Hypotenuse
sqrt
edit
# 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
# 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
editpop
edit
$LastElement = pop(@MyArray);
Take the last element from an array.
push
edit
push(@MyArray, "Last element"); push(@MyArray, "several", "more", "elements");
Push a list of elements onto the end of an array.
shift
edit
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
# 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
unshift(@MyArray, "New element"); unshift(@MyArray, "several", "more", "elements");
Add a list of elements onto the beginning of an array.
List functions
editgrep
edit
# 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
# Joins the items of a list into a single string $OneItemPerLine = join( "\n", @List); $EverythingBunchedTogether = join( "", @List); $Filename = join( "/", ($Directory, $Subdirectory, $Filename));
map
edit
# 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
# 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
# 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
Unpacks a string into a list - see the templates available for the pack() function for details
Associative array functions
editdelete
edit
# 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
# Return the 'next' key/value pair (in a random order) while (($key, $value) = each (%hash)) { print "$key => $value\n"; }
exists
edit
# 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
# 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
# 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
editbinmode
edit
close
edit
# closes a filehandle when it is no longer needed close(STDERR); # hide debugging info from the user
closedir
edit
# Close a directory open by opendir closedir(DIRHANDLE);
dbmclose
edit
dbmopen
edit
die
edit
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
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
flock
edit
format
edit
getc
edit
print
edit
Prints the parameters given.
Discussed in the following sections:
printf
edit
read
edit
readdir
edit
rewinddir
edit
seek
edit
seekdir
edit
select
edit
syscall
edit
sysread
edit
sysseek
edit
syswrite
edit
tell
edit
telldir
edit
truncate
edit
warn
edit
write
edit
Functions for working with fixed length records
editpack
edit
See the entry for pack
further up the page
read
edit
# 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
# Runs a system command syscall( $Command, $Argument1, $Argument2, $Argument3);
# (maximum 14 arguments) $ReturnValue = syscall($Command);
sysread
edit
syswrite
edit
unpack
edit
# See the pack function for details (unpack does the opposite!) unpack($Template, $BinaryData);
vec
editFilesystem functions
edit-X
edit
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
chdir $Directory; chdir $Directory || die("Couldn't change directory");
chmod
edit
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
# 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
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
fcntlglob
edit
# Expands filenames, in a shell-like way my @TextFiles = glob("*.txt");
See also File::Glob
.
ioctl
edit
link
edit
# Creates a link to a file link($ExistingFile, $LinkLocation); link($ExistingFile, $LinkLocation) || die("Couldn't create link");
lstat
edit
Identical to stat(), except that if given file is symbolic link, stat link not the target.
mkdir
edit
mkdir $Filename || die("Couldn't create directory"); mkdir $Filename, 0777; # Make directory with particular file-permissions
open
edit
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
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
# Finds the value of a symbolic link $LinkTarget = readlink($LinkPosition);
rename
edit
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
rmdir $Filename || die("Couldn't remove directory");
t
edit
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
# 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
# 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
# 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
# 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
editcaller
edit
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
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
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
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
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
editdefined
edit
# 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
eval
edit
eval('$a = 30; $b = 40;'); print $a, $b;
formline
edit
local
edit
# 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
# 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
# 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
# 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
# undefines an existing variable $x = 5; undef $x; print "x = $x\n" if defined $x; # does not print
wantarray
edit
# 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
editalarm
edit
exec
edit
fork
edit
# 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
getppid
edit
getpriority
edit
kill
edit
pipe
edit
qx/STRING/
edit
setpgrp
edit
setpriority
edit
sleep
edit
system
edit
times
edit
wait
edit
waitpid
edit
Modules
editdo
edit
import
edit
no
edit
package
edit
require
edit
use
edit
Classes and objects
editSee also Perl Objects
bless
edit
dbmclose
edit
dbmopen
edit
package
edit
ref
edit
tie
edit
tied
edit
untie
edit
use
edit
Sockets
editaccept
edit
bind
edit
nect
edit
getpeername
edit
getsockname
edit
getsockopt
edit
en
edit
listen
nd
edit
setsockopt
edit
shutdown
edit
socket
edit
socketpair
edit
Login information
editendgrent
edit
endhostent
edit
endnetent
editendpwent
edit
getgrent
edit
getgrgid
edit
getgrnam
edit
getlogin
edit
getpwent
edit
getpwnam
edit
getpwuid
edit
setgrent
edit
setpwent
edit
Network information
editendprotoent
edit
endservent
edit
gethostbyaddr
edit
ame
edit
bynamegethostent
edit
getnetbyaddr
edit
getnetbyname
edit
getnetent
edit
getprotobyname
edit
number
edit
getprotoent
edit
getservbyname
edit
getservbyport
edit
getservent
edit
sethostent
edit
setnetent
edit
setprotoent
edit
setservent
edit
Time and date
editgmtime
edit
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
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
$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
@CPUTimes = times(); $UserTimeForProcess = $CPUTimes[0]; $SystemTimeForProcess = $CPUTimes[1]; $UserTimeForChildren = $CPUTimes[2]; $SystemTimeForChildren = $CPUTimes[3];
Functions that reverse each other
editSome 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:
lc()
anduc()
lcfirst()
anducfirst()
ord()
andchr()
join()
andsplit()
push()
andpop()
unshift()
andshift()