Perl Functions References
Perl - Core Functions Reference
Section titled “Perl - Core Functions Reference”This section provides a reference to important built-in functions in Perl. Modern Perl development often leverages comprehensive modules from CPAN for specialized tasks, but understanding these core functions is fundamental.
Note: For many traditional functions (e.g., low-level socket operations, DBM access), dedicated CPAN modules often provide more robust and feature-rich alternatives. Always check CPAN for modern best practices for specific problem domains.
Below is a list of significant functions supported by Perl. Descriptions have been updated for clarity and modern context.
- abs - Returns the absolute value of its argument.
- accept - Accepts an incoming socket connection. See also
IO::SocketorMojo::IOLoopfor higher-level networking. - alarm - Schedules a SIGALRM signal. Useful for timeouts, but consider modules like
Sys::SigActionfor robust signal handling. - atan2 - Arctangent of Y/X in the range -PI to PI.
- bind - Binds an address to a socket. See also
IO::Socket. - binmode - Prepares a filehandle for binary I/O, crucial on systems like Windows.
- bless - Turns a reference into an object by associating it with a class name.
- caller - Returns the context of the current subroutine call, useful for debugging and creating call stacks.
- chdir - Changes the current working directory.
- chmod - Changes the permissions on a list of files.
- chomp - Removes a trailing newline (or record separator as defined by
$/) from a string. - chop - Removes the last character from a string (generally,
chompis preferred). - chown - Changes the ownership (user and group) on a list of files.
- chr - Returns the character represented by a number in the character set.
- chroot - Makes a directory the new root for path lookups (requires superuser privileges).
- close - Closes a filehandle, pipe, or socket.
- closedir - Closes a directory handle opened by
opendir. - connect - Connects to a remote socket. See also
IO::Socket. - continue - Defines an optional trailing block in a
whileorforeachloop, executed before the condition is re-evaluated. - cos - Returns the cosine of an angle (in radians).
- crypt - One-way encryption, typically for password hashing. Modern applications should use modules like
Authen::Passphrasefor stronger hashing algorithms. - dbmclose - Closes a DBM file. Largely superseded by modules like
DB_FileorBerkeleyDB. - dbmopen - Opens a DBM file. Largely superseded by modules like
DB_FileorBerkeleyDB. - defined - Tests whether a value, variable, or function is defined (not
undef). - delete - Deletes a key-value pair from a hash, or an element from an array slice.
- die - Raises an exception or terminates the program with an error message.
- do - Executes a block or a file.
do FILEis similar torequirebut doesn’t do error checking or import symbols. - dump - Creates an immediate core dump (rarely used, platform-dependent).
- each - Iterates over a hash, returning key-value pairs. Note: iteration order is not guaranteed. Consider
keysand a loop for predictable order. - endgrent - Cleans up after processing group file entries.
- endhostent - Cleans up after processing hosts file entries.
- endnetent - Cleans up after processing networks file entries.
- endprotoent - Cleans up after processing protocols file entries.
- endpwent - Cleans up after processing passwd file entries.
- endservent - Cleans up after processing services file entries.
- eof - Tests if the end of a filehandle has been reached.
- eval - Executes a string as Perl code (
eval STRING) or traps exceptions from a block (eval BLOCK). Essential for error handling. - exec - Replaces the current program with another program.
- exists - Tests whether a hash key exists (even if its value is
undef). - exit - Terminates the program with a specified exit status.
- exp - Returns e (Euler’s number) raised to a power.
- fcntl - Provides file control system calls (low-level).
- fileno - Returns the file descriptor for a filehandle.
- flock - Applies or removes an advisory lock on an open file.
- fork - Creates a child process (on Unix-like systems).
- format - Declares a picture format for use with
write(). Rarely used in modern Perl; see templating engines like Template Toolkit. - formline - Internal function used by
format(rarely called directly). - getc - Gets the next character from a filehandle.
- getgrent - Gets the next group record from the group file.
- getgrgid - Gets a group record by group ID (GID).
- getgrnam - Gets a group record by group name.
- gethostbyaddr - Gets a host record by its network address.
- gethostbyname - Gets a host record by its name.
- gethostent - Gets the next hosts record.
- getlogin - Returns the current login name.
- getnetbyaddr - Gets a network record by its address.
- getnetbyname - Gets a network record by its name.
- getnetent - Gets the next networks record.
- getpeername - Gets the socket address of the other end of a socket connection.
- getpgrp - Gets the process group ID.
- getppid - Gets the parent process ID.
- getpriority - Gets the current process priority (nice value).
- getprotobyname - Gets a protocol record by name.
- getprotobynumber - Gets a protocol record by number.
- getprotoent - Gets the next protocols record.
- getpwent - Gets the next passwd record.
- getpwnam - Gets a passwd record by username.
- getpwuid - Gets a passwd record by user ID (UID).
- getservbyname - Gets a services record by name.
- getservbyport - Gets a services record by port number.
- getservent - Gets the next services record.
- getsockname - Gets the socket address for a given socket.
- getsockopt - Gets socket options.
- glob - Expands a pattern into a list of filenames (filename globbing).
- gmtime - Converts a Unix timestamp into a list of time components (year, month, day, etc.) for GMT/UTC.
- goto - Transfers control to a labeled statement. Its use is strongly discouraged in modern programming.
- grep - Filters elements from a list for which a given code block or expression evaluates to true.
- hex - Converts a hexadecimal string to a decimal number.
- import - Imports symbols from a module into the current package’s namespace.
- index - Finds the position of the first occurrence of a substring within a string.
- int - Returns the integer portion of a number (truncates towards zero).
- ioctl - Performs I/O control system calls (low-level, system-dependent).
- join - Joins elements of a list into a single string using a separator.
- keys - Returns a list of all keys from a hash.
- kill - Sends a signal to a list of processes.
- last - Exits the innermost loop prematurely (similar to
breakin other languages). - lc - Returns a lowercased version of a string.
- lcfirst - Returns a string with its first character lowercased.
- length - Returns the length (in bytes by default, characters if
use utf8oruse feature 'unicode_strings'is in effect for strings with Unicode properties) of a string. - link - Creates a hard link between two filenames.
- listen - Listens for incoming connections on a socket. See also
IO::Socket. - local - Creates a temporary, dynamically scoped value for a global (package) variable.
myis generally preferred for lexical scoping. - localtime - Converts a Unix timestamp into a list of time components for the local timezone.
- lock - Gets a thread lock on a variable, subroutine, or method (used with
threadsandthreads::shared). - log - Returns the natural logarithm (base e) of a number.
- lstat - Like
stat, but stats a symbolic link itself rather than the file it points to. - m// - The match operator, used for regular expression matching. Can also be written as
//. - map - Transforms a list by applying a code block or expression to each element.
- mkdir - Creates a directory.
- msgctl, msgget, msgrcv, msgsnd - System V IPC message queue functions. Low-level; consider higher-level IPC mechanisms like sockets or message queuing systems (e.g., Redis, RabbitMQ) via CPAN modules.
- my - Declares lexically scoped variables. This is the standard way to declare variables in modern Perl.
- next - Skips to the next iteration of the current loop (similar to
continuein other languages). - no - Unimports symbols or disables pragmas at compile time (e.g.,
no strict). - oct - Converts an octal string (or hex if prefixed with
0x) to a decimal number. - open - Opens a file, pipe, or process for I/O. Modern Perl often uses the three-argument form with lexical filehandles (e.g.,
open my $fh, '<', $filename). - opendir - Opens a directory for reading with
readdir. - ord - Returns the numeric value (ordinal) of the first character in a string.
- our - Declares package variables that are lexically scoped but accessible via their fully qualified name.
- pack - Converts a list of values into a binary string representation according to a template.
- package - Declares a namespace (package).
- pipe - Creates a pair of connected filehandles (an inter-process communication channel).
- pop - Removes and returns the last element from an array.
- pos - Finds or sets the current match offset for a string when using
m//g. - print - Outputs a list of strings to a filehandle (STDOUT by default).
- printf - Outputs a formatted string to a filehandle.
- prototype - Returns the prototype of a subroutine (rarely needed by application programmers).
- push - Appends one or more elements to the end of an array.
- q// - Single-quotes a string, performing minimal interpolation.
- qq// - Double-quotes a string, performing interpolation of variables and escape sequences.
- qr// - Compiles a regular expression, returning a regex object.
- quotemeta - Quotes (escapes) all non-alphanumeric characters in a string for safe use in a regex.
- qw// - Quote Words: splits a string by whitespace into a list of words, treating each as single-quoted.
- qx// - Executes a command in a subshell and returns its standard output (same as backticks “).
- rand - Returns a pseudorandom floating-point number between 0 and its argument (or 1 if no argument).
- read - Reads a specified number of bytes from a filehandle into a buffer.
- readdir - Reads directory entries from a directory handle opened by
opendir. - readline - Reads a line from a filehandle (often used implicitly with the
<FILEHANDLE>operator). - readlink - Returns the value of a symbolic link.
- readpipe - Executes a system command and returns its standard output (same as
qx//or backticks). - recv - Receives a message over a socket.
- redo - Restarts the current loop iteration without re-evaluating the condition or executing
continueblock. - ref - Returns the type of the referenced value (e.g., ‘ARRAY’, ‘HASH’, ‘SCALAR’, or the class name for a blessed reference).
- rename - Renames a file.
- require - Loads a module or file at runtime if not already loaded. Ensures code is compiled only once.
- reset - Resets variables in the current package (rarely used).
- return - Exits a subroutine, optionally returning a value.
- reverse - Reverses the order of elements in a list, or the characters in a string (in list or scalar context, respectively).
- rewinddir - Resets the current position of a directory handle opened by
opendirto the beginning. - rindex - Finds the position of the last occurrence of a substring within a string.
- rmdir - Removes an empty directory.
- s/// - The substitution operator, for regex search and replace.
- scalar - Forces an expression to be evaluated in scalar context.
- seek - Repositions the file pointer for a filehandle (for random access I/O).
- seekdir - Repositions a directory handle opened by
opendir. - select - Sets the default filehandle for output, or performs I/O multiplexing (with a bitmask of filehandles).
- semctl, semget, semop - System V semaphore functions. Low-level; see
IPC::SysVor consider higher-level synchronization primitives. - send - Sends a message over a socket.
- setgrent, sethostent, setnetent, setprotoent, setpwent, setservent - Prepare for iterating through system database files (group, hosts, etc.).
- setpgrp - Sets the process group of a process.
- setpriority - Sets a process’s priority (nice value).
- setsockopt - Sets socket options.
- shift - Removes and returns the first element from an array, or from
@_within a subroutine if no array is specified. - shmctl, shmget, shmread, shmwrite - System V shared memory functions. Low-level; see
IPC::SysVorIPC::Shareable. - shutdown - Disables reads, writes, or both on a socket connection.
- sin - Returns the sine of an angle (in radians).
- sleep - Pauses execution for a specified number of seconds.
- socket - Creates a socket. See also
IO::Socket. - socketpair - Creates a pair of connected (unnamed) sockets.
- sort - Sorts a list of values. Can take a custom comparison subroutine or block.
- splice - Adds or removes elements from an array at a specified offset.
- split - Splits a string into a list of substrings based on a regex delimiter.
- sprintf - Returns a formatted string (similar to
printfbut returns the string instead of printing it). - sqrt - Returns the square root of a number.
- srand - Seeds the pseudorandom number generator (
rand). Automatic seeding usually makes explicit calls unnecessary. - stat - Returns status information for a file (mode, size, timestamps, etc.).
- study - Analyzes a string to optimize subsequent regex matches on it. Rarely beneficial on modern Perl due to regex engine improvements.
- sub - Declares a subroutine (function), possibly anonymously.
- substr - Extracts or replaces a portion of a string.
- symlink - Creates a symbolic link to a file.
- syscall - Executes an arbitrary system call (very low-level, platform-dependent).
- sysopen - Opens a filehandle using system-level open flags.
- sysread - Reads from a filehandle without using Perl’s I/O buffering.
- sysseek - Repositions the I/O pointer for a filehandle used with
sysreadandsyswrite. - system - Executes a system command. Returns the exit status of the command.
- syswrite - Writes to a filehandle without using Perl’s I/O buffering.
- tell - Returns the current position (offset) of a filehandle.
- telldir - Returns the current position of a directory handle opened by
opendir. - tie - Binds a variable to an object class, allowing method calls to be triggered by operations on the variable.
- tied - Returns a reference to the object underlying a tied variable.
- time - Returns the number of seconds since the Unix epoch (January 1, 1970, UTC).
- times - Returns elapsed CPU time for the current process and its children.
- tr/// - The transliteration (character replacement) operator. Can also be written as
y///. - truncate - Shortens a file to a specified length.
- uc - Returns an uppercased version of a string.
- ucfirst - Returns a string with its first character uppercased.
- umask - Sets or gets the file creation mode mask.
- undef - Undefines a variable or function, making its value
undef. - unlink - Deletes one or more files (removes links to files).
- unpack - Converts a binary string into a list of values according to a template.
- unshift - Prepends one or more elements to the beginning of an array.
- untie - Breaks the binding between a variable and its tied object class.
- use - Loads a module at compile time, importing symbols and running its
importmethod. - utime - Sets a file’s last access and modification times.
- values - Returns a list of all values from a hash.
- vec - Treats a string as a bit vector and allows testing or setting individual bits.
- wait - Waits for any child process to terminate.
- waitpid - Waits for a specific child process to terminate.
- wantarray - Returns true if the current subroutine call is in list context, false in scalar context, and
undefin void context. - warn - Prints a warning message to STDERR.
- write - Writes a formatted record to a filehandle using a declared
format. Rarely used; see templating engines. - -X (File Tests) - A set of unary operators that test file attributes (e.g.,
-rfor readable,-xfor executable,-ffor plain file). - y/// - An alias for the
tr///(transliteration) operator.