a A string with arbitrary binary data, will be null padded. A A text (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 (8-bit) value. C An unsigned char (octet) value. W An unsigned char value (can be greater than 255). s A signed short (16-bit) value. S An unsigned short value. l A signed long (32-bit) value. L An unsigned long value. q A signed quad (64-bit) value. Q An unsigned quad value. (Quads are available only if your system supports 64-bit integer values _and_ if Perl has been compiled to support those. Causes a fatal error otherwise.) i A signed integer value. I A unsigned integer value. (This 'integer' is _at_least_ 32 bits wide. Its exact size depends on what a local C compiler calls 'int'.) n An unsigned short (16-bit) in "network" (big-endian) order. N An unsigned long (32-bit) in "network" (big-endian) order. v An unsigned short (16-bit) in "VAX" (little-endian) order. V An unsigned long (32-bit) in "VAX" (little-endian) order. j A Perl internal signed integer value (IV). J A Perl internal unsigned integer value (UV). f A single-precision float in the native format. d A double-precision float in the native format. F A Perl internal floating point value (NV) in the native format D A long double-precision float in the native format. (Long doubles are available only if your system supports long double values _and_ if Perl has been compiled to support those. Causes a fatal error otherwise.) p A pointer to a null-terminated string.  U A Unicode character number. Encodes to a character in character mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in byte mode. w A BER compressed integer (not an ASN.1 BER, see perlpacktut for details). 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 or truncate to absolute position, counted from the start of the innermost ()-group. . Null fill or truncate to absolute position specified by value. ( Start of a ()-group.
One or more of the modifiers below may optionally follow some letters in the TEMPLATE (the second column lists the letters for which the modifier is valid):
! sSlLiI Forces native (short, long, int) sizes instead of fixed (16-/32-bit) sizes. xX Make x and X act as alignment commands. nNvV Treat integers as signed instead of unsigned. @. Specify position as byte offset in the internal representation of the packed string. Efficient but dangerous. > sSiIlLqQ Force big-endian byte-order on the type. jJfFdDpP (The "big end" touches the construct.) < sSiIlLqQ Force little-endian byte-order on the type. jJfFdDpP (The "little end" touches the construct.)
The ">" and "<" modifiers can also be used on "()"-groups, in which case they force a certain byte-order on all components of that group, including subgroups.
The following rules apply:
-
- *
-
Each letter may optionally be followed by a number giving a repeat
count. With all types except "a", "A", "Z", "b", "B", "h",
"H", "@", ".", "x", "X" and "P" the pack function will gobble up
that many values from the LIST. A "*" for the repeat count means to
use however many items are left, except for "@", "x", "X", where it
is equivalent to 0, for <.> where it means relative to string start
and "u", where it is equivalent to 1 (or 45, which is the same).
A numeric repeat count may optionally be enclosed in brackets, as in
"pack 'C[80]', @arr".
One can replace the numeric repeat count by a template enclosed in brackets; then the packed length of this template in bytes is used as a count. For example, "x[L]" skips a long (it skips the number of bytes in a long); the template "$t X[$t] $t" unpack()s twice what $t unpacks. If the template in brackets contains alignment commands (such as "x![d]"), its packed length is calculated as if the start of the template has the maximal possible alignment.
When used with "Z", "*" results in the addition of a trailing null byte (so the packed result will be one longer than the byte "length" of the item).
When used with "@", the repeat count represents an offset from the start of the innermost () group.
When used with ".", the repeat count is used to determine the starting position from where the value offset is calculated. If the repeat count is 0, it's relative to the current position. If the repeat count is "*", the offset is relative to the start of the packed string. And if its an integer "n" the offset is relative to the start of the n-th innermost () group (or the start of the string if "n" is bigger then the group level).
The repeat count for "u" is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65.
- *
-
The "a", "A", and "Z" types gobble just one value, but pack it as a
string of length count, padding with nulls or spaces as necessary. When
unpacking, "A" strips trailing whitespace and nulls, "Z" strips everything
after the first null, and "a" returns data verbatim.
If the value-to-pack is too long, it is truncated. If too long and an explicit count is provided, "Z" packs only "$count-1" bytes, followed by a null byte. Thus "Z" always packs a trailing null (except when the count is 0).
- *
-
Likewise, the "b" and "B" fields pack a string that many bits long.
Each character of the input field of pack() generates 1 bit of the result.
Each result bit is based on the least-significant bit of the corresponding
input character, i.e., on "ord($char)%2". In particular, characters "0"
and "1" generate bits 0 and 1, as do characters "\0" and "\1".
Starting from the beginning of the input string of pack(), each 8-tuple of characters is converted to 1 character of output. With format "b" the first character of the 8-tuple determines the least-significant bit of a character, and with format "B" it determines the most-significant bit of a character.
If the length of the input string is not exactly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly, during unpack()ing the ``extra'' bits are ignored.
If the input string of pack() is longer than needed, extra characters are ignored. A "*" for the repeat count of pack() means to use all the characters of the input field. On unpack()ing the bits are converted to a string of "0"s and "1"s.
- *
-
The "h" and "H" fields pack a string that many nybbles (4-bit groups,
representable as hexadecimal digits, 0-9a-f) long.
Each character of the input field of pack() generates 4 bits of the result. For non-alphabetical characters the result is based on the 4 least-significant bits of the input character, i.e., on "ord($char)%16". In particular, characters "0" and "1" generate nybbles 0 and 1, as do bytes "\0" and "\1". For characters "a".."f" and "A".."F" the result is compatible with the usual hexadecimal digits, so that "a" and "A" both generate the nybble "0xa==10". The result for characters "g".."z" and "G".."Z" is not well-defined.
Starting from the beginning of the input string of pack(), each pair of characters is converted to 1 character of output. With format "h" the first character of the pair determines the least-significant nybble of the output character, and with format "H" it determines the most-significant nybble.
If the length of the input string is not even, it behaves as if padded by a null character at the end. Similarly, during unpack()ing the ``extra'' nybbles are ignored.
If the input string of pack() is longer than needed, extra characters are ignored. A "*" for the repeat count of pack() means to use all the characters of the input field. On unpack()ing the nybbles are converted to a string of hexadecimal digits.
- *
-
The "p" type packs a pointer to a null-terminated string. You are
responsible for ensuring the string is not a temporary value (which can
potentially get deallocated before you get around to using the packed result).
The "P" type packs a pointer to a structure of the size indicated by the
length. A NULL pointer is created if the corresponding value for "p" or
"P" is "undef", similarly for unpack().
If your system has a strange pointer size (i.e. a pointer is neither as big as an int nor as big as a long), it may not be possible to pack or unpack pointers in big- or little-endian byte order. Attempting to do so will result in a fatal error.
- *
-
The "/" template character allows packing and unpacking of a sequence of
items where the packed structure contains a packed item count followed by
the packed items themselves.
For "pack" you write length-item"/"sequence-item and the length-item describes how the length value is packed. The ones likely to be of most use are integer-packing ones like "n" (for Java strings), "w" (for ASN.1 or SNMP) and "N" (for Sun XDR).
For "pack", the sequence-item may have a repeat count, in which case the minimum of that and the number of available items is used as argument for the length-item. If it has no repeat count or uses a '*', the number of available items is used.
For "unpack" an internal stack of integer arguments unpacked so far is used. You write "/"sequence-item and the repeat count is obtained by popping off the last element from the stack. The sequence-item must not have a repeat count.
If the sequence-item refers to a string type ("A", "a" or "Z"), the length-item is a string length, not a number of strings. If there is an explicit repeat count for pack, the packed string will be adjusted to that given length.
unpack 'W/a', "\04Gurusamy"; gives ('Guru') unpack 'a3/A A*', '007 Bond J '; gives (' Bond', 'J') unpack 'a3 x2 /A A*', '007: Bond, J.'; gives ('Bond, J', '.') pack 'n/a* w/a','hello,','world'; gives "\000\006hello,\005world" pack 'a/W2', ord('a') .. ord('z'); gives '2ab'
The length-item is not returned explicitly from "unpack".
Adding a count to the length-item letter is unlikely to do anything useful, unless that letter is "A", "a" or "Z". Packing with a length-item of "a" or "Z" may introduce "\000" characters, which Perl does not regard as legal in numeric strings.
- *
-
The integer types "s", "S", "l", and "L" may be
followed by a "!" modifier to signify native shorts or
longs---as you can see from above for example a bare "l" does mean
exactly 32 bits, the native "long" (as seen by the local C compiler)
may be larger. This is an issue mainly in 64-bit platforms. You can
see whether using "!" makes any difference by
print length(pack("s")), " ", length(pack("s!")), "\n"; print length(pack("l")), " ", length(pack("l!")), "\n";
"i!" and "I!" also work but only because of completeness; they are identical to "i" and "I".
The actual sizes (in bytes) of native shorts, ints, longs, and long longs on the platform where Perl was built are also available via Config:
use Config; print $Config{shortsize}, "\n"; print $Config{intsize}, "\n"; print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n";
(The $Config{longlongsize} will be undefined if your system does not support long longs.)
- *
-
The integer formats "s", "S", "i", "I", "l", "L", "j", and "J"
are inherently non-portable between processors and operating systems
because they obey the native byteorder and endianness. For example a
4-byte integer 0x12345678 (305419896 decimal) would be ordered natively
(arranged in and handled by the CPU registers) into bytes as
0x12 0x34 0x56 0x78 # big-endian 0x78 0x56 0x34 0x12 # little-endian
Basically, the Intel and VAX CPUs are little-endian, while everybody else, for example Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray are big-endian. Alpha and MIPS can be either: Digital/Compaq used/uses them in little-endian mode; SGI/Cray uses them in big-endian mode.
The names `big-endian' and `little-endian' are comic references to the classic ``Gulliver's Travels'' (via the paper ``On Holy Wars and a Plea for Peace'' by Danny Cohen, USC/ISI IEN 137, April 1, 1980) and the egg-eating habits of the Lilliputians.
Some systems may have even weirder byte orders such as
0x56 0x78 0x12 0x34 0x34 0x12 0x78 0x56
You can see your system's preference with
print join(" ", map { sprintf "%#02x", $_ } unpack("W*",pack("L",0x12345678))), "\n";
The byteorder on the platform where Perl was built is also available via Config:
use Config; print $Config{byteorder}, "\n";
Byteorders '1234' and '12345678' are little-endian, '4321' and '87654321' are big-endian.
If you want portable packed integers you can either use the formats "n", "N", "v", and "V", or you can use the ">" and "<" modifiers. These modifiers are only available as of perl 5.9.2. See also perlport.
- *
-
All integer and floating point formats as well as "p" and "P" and
"()"-groups may be followed by the ">" or "<" modifiers
to force big- or little- endian byte-order, respectively.
This is especially useful, since "n", "N", "v" and "V" don't cover
signed integers, 64-bit integers and floating point values. However,
there are some things to keep in mind.
Exchanging signed integers between different platforms only works if all platforms store them in the same format. Most platforms store signed integers in two's complement, so usually this is not an issue.
The ">" or "<" modifiers can only be used on floating point formats on big- or little-endian machines. Otherwise, attempting to do so will result in a fatal error.
Forcing big- or little-endian byte-order on floating point values for data exchange can only work if all platforms are using the same binary representation (e.g. IEEE floating point format). Even if all platforms are using IEEE, there may be subtle differences. Being able to use ">" or "<" on floating point values can be very useful, but also very dangerous if you don't know exactly what you're doing. It is definitely not a general way to portably store floating point values.
When using ">" or "<" on an "()"-group, this will affect all types inside the group that accept the byte-order modifiers, including all subgroups. It will silently be ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix.
- *
-
Real numbers (floats and doubles) are in the native machine format only;
due to the multiplicity of floating formats around, and the lack of a
standard ``network'' representation, no facility for interchange has been
made. This means that packed floating point data written on one machine
may not be readable on another - even if both use IEEE floating point
arithmetic (as the endian-ness of the memory representation is not part
of the IEEE spec). See also perlport.
If you know exactly what you're doing, you can use the ">" or "<" modifiers to force big- or little-endian byte-order on floating point values.
Note that Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, and converting from double into float and thence back to double again will lose precision (i.e., "unpack("f", pack("f", $foo)") will not in general equal $foo).
- *
- Pack and unpack can operate in two modes, character mode ("C0" mode) where the packed string is processed per character and UTF-8 mode ("U0" mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte by byte basis. Character mode is the default unless the format string starts with an "U". You can switch mode at any moment with an explicit "C0" or "U0" in the format. A mode is in effect until the next mode switch or until the end of the ()-group in which it was entered.
- *
- You must yourself do any alignment or padding by inserting for example enough 'x'es while packing. There is no way to pack() and unpack() could know where the characters are going to or coming from. Therefore "pack" (and "unpack") handle their output and input as flat sequences of characters.
- *
-
A ()-group is a sub-TEMPLATE enclosed in parentheses. A group may
take a repeat count, both as postfix, and for unpack() also via the "/"
template character. Within each repetition of a group, positioning with
"@" starts again at 0. Therefore, the result of
pack( '@1A((@2A)@3A)', 'a', 'b', 'c' )
is the string ``\0a\0\0bc''.
- *
-
"x" and "X" accept "!" modifier. In this case they act as
alignment commands: they jump forward/back to the closest position
aligned at a multiple of "count" characters. For example, to pack() or
unpack() C's "struct {char c; double d; char cc[2]}" one may need to
use the template "W x![d] d W[2]"; this assumes that doubles must be
aligned on the double's size.
For alignment commands "count" of 0 is equivalent to "count" of 1; both result in no-ops.
- *
- "n", "N", "v" and "V" accept the "!" modifier. In this case they will represent signed 16-/32-bit integers in big-/little-endian order. This is only portable if all platforms sharing the packed data use the same binary representation for signed integers (e.g. all platforms are using two's complement representation).
- *
- A comment in a TEMPLATE starts with "#" and goes to the end of line. White space may be used to separate pack codes from each other, but modifiers and a repeat count must follow immediately.
- *
- If TEMPLATE requires more arguments to pack() than actually given, pack() assumes additional "" arguments. If TEMPLATE requires fewer arguments to pack() than actually given, extra arguments are ignored.
-
Examples:
$foo = pack("WWWW",65,66,67,68); # foo eq "ABCD" $foo = pack("W4",65,66,67,68); # same thing $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. You don't get the UTF-8 # bytes because the U at the start of the format caused a switch to # U0-mode, so the UTF-8 bytes get joined into characters $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" # This is the UTF-8 encoding of the string in the previous example $foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD" # note: the above examples featuring "W" and "c" are true # only on ASCII and ASCII-derived systems such as ISO Latin 1 # and UTF-8. In EBCDIC the first example would be # $foo = pack("WWWW",193,194,195,196); $foo = pack("s2",1,2); # "\1\0\2\0" on little-endian # "\0\1\0\2" on big-endian $foo = pack("a4","abcd","x","y","z"); # "abcd" $foo = pack("aaaa","abcd","x","y","z"); # "axyz" $foo = pack("a14","abcdefg"); # "abcdefg\0\0\0\0\0\0\0" $foo = pack("i9pl", gmtime); # a real struct tm (on my system anyway) $utmp_template = "Z8 Z8 Z16 L"; $utmp = pack($utmp_template, @utmp1); # a struct utmp (BSDish) @utmp2 = unpack($utmp_template, $utmp); # "@utmp1" eq "@utmp2" sub bintodec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } $foo = pack('sx2l', 12, 34); # short 12, two zero bytes padding, long 34 $bar = pack('s@4l', 12, 34); # short 12, zero fill to position 4, long 34 # $foo eq $bar $baz = pack('s.l', 12, 4, 34); # short 12, zero fill to position 4, long 34 $foo = pack('nN', 42, 4711); # pack big-endian 16- and 32-bit unsigned integers $foo = pack('S>L>', 42, 4711); # exactly the same $foo = pack('s<l<', -42, 4711); # pack little-endian 16- and 32-bit signed integers $foo = pack('(sl)<', -42, 4711); # exactly the same
The same template may generally also be used in unpack().
-
- package NAMESPACE
- package
-
Declares the compilation unit as being in the given namespace. The scope
of the package declaration is from the declaration itself through the end
of the enclosing block, file, or eval (the same as the "my" operator).
All further unqualified dynamic identifiers will be in this namespace.
A package statement affects only dynamic variables---including those
you've used "local" on---but not lexical variables, which are created
with "my". Typically it would be the first declaration in a file to
be included by the "require" or "use" operator. You can switch into a
package in more than one place; it merely influences which symbol table
is used by the compiler for the rest of that block. You can refer to
variables and filehandles in other packages by prefixing the identifier
with the package name and a double colon: $Package::Variable.
If the package name is null, the "main" package as assumed. That is,
$::sail is equivalent to $main::sail (as well as to "$main'sail",
still seen in older code).
See ``Packages'' in perlmod for more information about packages, modules, and classes. See perlsub for other scoping issues.
- pipe READHANDLE,WRITEHANDLE
-
Opens a pair of connected pipes like the corresponding system call.
Note that if you set up a loop of piped processes, deadlock can occur
unless you are very careful. In addition, note that Perl's pipes use
IO buffering, so you may need to set $| to flush your WRITEHANDLE
after each command, depending on the application.
See IPC::Open2, IPC::Open3, and ``Bidirectional Communication'' in perlipc for examples of such things.
On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptors as determined by the value of $^F. See ``$^F'' in perlvar.
- pop ARRAY
- pop
-
Pops and returns the last value of the array, shortening the array by
one element.
If there are no elements in the array, returns the undefined value (although this may happen at other times as well). If ARRAY is omitted, pops the @ARGV array in the main program, and the @_ array in subroutines, just like "shift".
- pos SCALAR
- pos
- Returns the offset of where the last "m//g" search left off for the variable in question ($_ is used when the variable is not specified). Note that 0 is a valid match offset. "undef" indicates that the search position is reset (usually due to match failure, but can also be because no match has yet been performed on the scalar). "pos" directly accesses the location used by the regexp engine to store the offset, so assigning to "pos" will change that offset, and so will also influence the "\G" zero-width assertion in regular expressions. Because a failed "m//gc" match doesn't reset the offset, the return from "pos" won't change either in this case. See perlre and perlop.
- print FILEHANDLE LIST
- print LIST
-
Prints a string or a list of strings. Returns true if successful.
FILEHANDLE may be a scalar variable name, in which case the variable
contains the name of or a reference to the filehandle, thus introducing
one level of indirection. (NOTE: If FILEHANDLE is a variable and
the next token is a term, it may be misinterpreted as an operator
unless you interpose a "+" or put parentheses around the arguments.)
If FILEHANDLE is omitted, prints by default to standard output (or
to the last selected output channel---see ``select''). If LIST is
also omitted, prints $_ to the currently selected output channel.
To set the default output channel to something other than STDOUT
use the select operation. The current value of $, (if any) is
printed between each LIST item. The current value of "$\" (if
any) is printed after the entire LIST has been printed. Because
print takes a LIST, anything in the LIST is evaluated in list
context, and any subroutine that you call will have one or more of
its expressions evaluated in list context. Also be careful not to
follow the print keyword with a left parenthesis unless you want
the corresponding right parenthesis to terminate the arguments to
the print---interpose a "+" or put parentheses around all the
arguments.
Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:
print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n";
- printf FILEHANDLE FORMAT, LIST
- printf FORMAT, LIST
-
Equivalent to "print FILEHANDLE sprintf(FORMAT, LIST)", except that "$\"
(the output record separator) is not appended. The first argument
of the list will be interpreted as the "printf" format. See "sprintf"
for an explanation of the format argument. If "use locale" is in effect,
and POSIX::setlocale() has been called, the character used for the decimal
separator in formatted floating point numbers is affected by the LC_NUMERIC
locale. See perllocale and POSIX.
Don't fall into the trap of using a "printf" when a simple "print" would do. The "print" is more efficient and less error prone.
- prototype FUNCTION
-
Returns the prototype of a function as a string (or "undef" if the
function has no prototype). FUNCTION is a reference to, or the name of,
the function whose prototype you want to retrieve.
If FUNCTION is a string starting with "CORE::", the rest is taken as a name for Perl builtin. If the builtin is not overridable (such as "qw//") or if its arguments cannot be adequately expressed by a prototype (such as "system"), prototype() returns "undef", because the builtin does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned.
- push ARRAY,LIST
-
Treats ARRAY as a stack, and pushes the values of LIST
onto the end of ARRAY. The length of ARRAY increases by the length of
LIST. Has the same effect as
for $value (LIST) { $ARRAY[++$#ARRAY] = $value; }
but is more efficient. Returns the number of elements in the array following the completed "push".
- q/STRING/
- qq/STRING/
- qx/STRING/
- qw/STRING/
- Generalized quotes. See ``Quote-Like Operators'' in perlop.
- qr/STRING/
- Regexp-like quote. See ``Regexp Quote-Like Operators'' in perlop.
- quotemeta EXPR
- quotemeta
-
Returns the value of EXPR with all non-``word''
characters backslashed. (That is, all characters not matching
"/[A-Za-z_0-9]/" will be preceded by a backslash in the
returned string, regardless of any locale settings.)
This is the internal function implementing
the "\Q" escape in double-quoted strings.
If EXPR is omitted, uses $_.
- rand EXPR
- rand
-
Returns a random fractional number greater than or equal to 0 and less
than the value of EXPR. (EXPR should be positive.) If EXPR is
omitted, the value 1 is used. Currently EXPR with the value 0 is
also special-cased as 1 - this has not been documented before perl 5.8.0
and is subject to change in future versions of perl. Automatically calls
"srand" unless "srand" has already been called. See also "srand".
Apply "int()" to the value returned by "rand()" if you want random integers instead of random fractional numbers. For example,
int(rand(10))
returns a random integer between 0 and 9, inclusive.
(Note: If your rand function consistently returns numbers that are too large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.)
- read FILEHANDLE,SCALAR,LENGTH,OFFSET
- read FILEHANDLE,SCALAR,LENGTH
-
Attempts to read LENGTH characters of data into variable SCALAR
from the specified FILEHANDLE. Returns the number of characters
actually read, 0 at end of file, or undef if there was an error (in
the latter case $! is also set). SCALAR will be grown or shrunk
so that the last character actually read is the last character of the
scalar after the read.
An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with "\0" bytes before the result of the read is appended.
The call is actually implemented in terms of either Perl's or system's fread() call. To get a true read(2) system call, see "sysread".
Note the characters: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default all filehandles operate on bytes, but for example if the filehandle has been opened with the ":utf8" I/O layer (see ``open'', and the "open" pragma, open), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the ":encoding" pragma: in that case pretty much any characters can be read.
- readdir DIRHANDLE
-
Returns the next directory entry for a directory opened by "opendir".
If used in list context, returns all the rest of the entries in the
directory. If there are no more entries, returns an undefined value in
scalar context or a null list in list context.
If you're planning to filetest the return values out of a "readdir", you'd better prepend the directory in question. Otherwise, because we didn't "chdir" there, it would have been testing the wrong file.
opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh;
- readline EXPR
- readline
-
Reads from the filehandle whose typeglob is contained in EXPR (or from
*ARGV if EXPR is not provided). In scalar context, each call reads and
returns the next line, until end-of-file is reached, whereupon the
subsequent call returns undef. In list context, reads until end-of-file
is reached and returns a list of lines. Note that the notion of ``line''
used here is however you may have defined it with $/ or
$INPUT_RECORD_SEPARATOR). See ``$/'' in perlvar.
When $/ is set to "undef", when readline() is in scalar context (i.e. file slurp mode), and when an empty file is read, it returns '' the first time, followed by "undef" subsequently.
This is the internal function implementing the "<EXPR>" operator, but you can use it directly. The "<EXPR>" operator is discussed in more detail in ``I/O Operators'' in perlop.
$line = <STDIN>; $line = readline(*STDIN); # same thing
If readline encounters an operating system error, $! will be set with the corresponding error message. It can be helpful to check $! when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of "readline", and takes the necessary steps to ensure that "readline" was successful.
for (;;) { undef $!; unless (defined( $line = <> )) { last if eof; die $! if $!; } # ... }
- readlink EXPR
- readlink
- Returns the value of a symbolic link, if symbolic links are implemented. If not, gives a fatal error. If there is some system error, returns the undefined value and sets $! (errno). If EXPR is omitted, uses $_.
- readpipe EXPR
- readpipe
- EXPR is executed as a system command. The collected standard output of the command is returned. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR). This is the internal function implementing the "qx/EXPR/" operator, but you can use it directly. The "qx/EXPR/" operator is discussed in more detail in ``I/O Operators'' in perlop. If EXPR is omitted, uses $_.
- recv SOCKET,SCALAR,LENGTH,FLAGS
-
Receives a message on a socket. Attempts to receive LENGTH characters
of data into variable SCALAR from the specified SOCKET filehandle.
SCALAR will be grown or shrunk to the length actually read. Takes the
same flags as the system call of the same name. Returns the address
of the sender if SOCKET's protocol supports this; returns an empty
string otherwise. If there's an error, returns the undefined value.
This call is actually implemented in terms of recvfrom(2) system call.
See ``UDP: Message Passing'' in perlipc for examples.
Note the characters: depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the ":encoding(utf8)" I/O layer (see the "open" pragma, open), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the ":encoding" pragma: in that case pretty much any characters can be read.
- redo LABEL
- redo
-
The "redo" command restarts the loop block without evaluating the
conditional again. The "continue" block, if any, is not executed. If
the LABEL is omitted, the command refers to the innermost enclosing
loop. Programs that want to lie to themselves about what was just input
normally use this command:
# a simpleminded Pascal comment stripper # (warning: assumes no { or } in strings) LINE: while (<STDIN>) { while (s|({.*}.*){.*}|$1 |) {} s|{.*}| |; if (s|{.*| |) { $front = $_; while (<STDIN>) { if (/}/) { # end of comment? s|^|$front\{|; redo LINE; } } } print; }
"redo" cannot be used to retry a block which returns a value such as "eval {}", "sub {}" or "do {}", and should not be used to exit a grep() or map() operation.
Note that a block by itself is semantically identical to a loop that executes once. Thus "redo" inside such a block will effectively turn it into a looping construct.
See also ``continue'' for an illustration of how "last", "next", and "redo" work.
- ref EXPR
- ref
-
Returns a non-empty string if EXPR is a reference, the empty
string otherwise. If EXPR
is not specified, $_ will be used. The value returned depends on the
type of thing the reference is a reference to.
Builtin types include:
SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp
If the referenced object has been blessed into a package, then that package name is returned instead. You can think of "ref" as a "typeof" operator.
if (ref($r) eq "HASH") { print "r is a reference to a hash.\n"; } unless (ref($r)) { print "r is not a reference at all.\n"; }
The return value "LVALUE" indicates a reference to an lvalue that is not a variable. You get this from taking the reference of function calls like "pos()" or "substr()". "VSTRING" is returned if the reference points to a version string.
The result "Regexp" indicates that the argument is a regular expression resulting from "qr//".
See also perlref.
- rename OLDNAME,NEWNAME
-
Changes the name of a file; an existing file NEWNAME will be
clobbered. Returns true for success, false otherwise.
Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system mv command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre-existing files. Check perlport and either the rename(2) manpage or equivalent system documentation for details.
For a platform independent "move" function look at the File::Copy module.
- require VERSION
- require EXPR
- require
-
Demands a version of Perl specified by VERSION, or demands some semantics
specified by EXPR or by $_ if EXPR is not supplied.
VERSION may be either a numeric argument such as 5.006, which will be compared to $], or a literal of the form v5.6.1, which will be compared to $^V (aka $PERL_VERSION). A fatal error is produced at run time if VERSION is greater than the version of the current Perl interpreter. Compare with ``use'', which can do a similar check at compile time.
Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl that do not support this syntax. The equivalent numeric version should be used instead.
require v5.6.1; # run time version check require 5.6.1; # ditto require 5.006_001; # ditto; preferred for backwards compatibility
Otherwise, "require" demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of "eval" with the caveat that lexical variables in the invoking script will be invisible to the included code. Has semantics similar to the following subroutine:
sub require { my ($filename) = @_; if (exists $INC{$filename}) { return 1 if $INC{$filename}; die "Compilation failed in require"; } my ($realfilename,$result); ITER: { foreach $prefix (@INC) { $realfilename = "$prefix/$filename"; if (-f $realfilename) { $INC{$filename} = $realfilename; $result = do $realfilename; last ITER; } } die "Can't find $filename in \@INC"; } if ($@) { $INC{$filename} = undef; die $@; } elsif (!$result) { delete $INC{$filename}; die "$filename did not return true value"; } else { return $result; } }
Note that the file will not be included twice under the same specified name.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with "1;" unless you're sure it'll return true otherwise. But it's better just to put the "1;", in case you add more statements.
If EXPR is a bareword, the require assumes a ".pm`` extension and replaces ''::`` with ''/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
In other words, if you try this:
require Foo::Bar; # a splendid bareword
The require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array.
But if you try this:
$class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the ""
The require function will look for the "Foo::Bar`` file in the @INC array and will complain about not finding ''Foo::Bar" there. In this case you can do:
eval "require $class";
Now that you understand how "require" looks for files in the case of a bareword argument, there is a little extra functionality going on behind the scenes. Before "require" looks for a ".pm`` extension, it will first look for a similar filename with a ''.pmc`` extension. If this file is found, it will be loaded in place of any file ending in a ''.pm" extension.
You can also insert hooks into the import facility, by putting directly Perl code into the @INC array. There are three forms of hooks: subroutine references, array references and blessed objects.
Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, this subroutine gets called with two parameters, the first being a reference to itself, and the second the name of the file to be included (e.g. "Foo/Bar.pm"). The subroutine should return nothing, or a list of up to three values in the following order:
-
- 1.
- A filehandle, from which the file will be read.
- 2.
- A reference to a subroutine. If there is no filehandle (previous item), then this subroutine is expected to generate one line of source code per call, writing the line into $_ and returning 1, then returning 0 at ``end of file''. If there is a filehandle, then the subroutine will be called to act as a simple source filter, with the line as read in $_. Again, return 1 for each valid line, and 0 after all lines have been returned.
- 3.
- Optional state for the subroutine. The state is passed in as $_[1]. A reference to the subroutine itself is passed in as $_[0].
-
If an empty list, "undef", or nothing that matches the first 3 values above is returned then "require" will look at the remaining elements of @INC. Note that this file handle must be a real file handle (strictly a typeglob, or reference to a typeglob, blessed or unblessed) - tied file handles will be ignored and return value processing will stop there.
If the hook is an array reference, its first element must be a subroutine reference. This subroutine is called as above, but the first parameter is the array reference. This enables to pass indirectly some arguments to the subroutine.
In other words, you can write:
push @INC, \&my_sub; sub my_sub { my ($coderef, $filename) = @_; # $coderef is \&my_sub ... }
or:
push @INC, [ \&my_sub, $x, $y, ... ]; sub my_sub { my ($arrayref, $filename) = @_; # Retrieve $x, $y, ... my @parameters = @$arrayref[1..$#$arrayref]; ... }
If the hook is an object, it must provide an INC method that will be called as above, the first parameter being the object itself. (Note that you must fully qualify the sub's name, as unqualified "INC" is always forced into package "main".) Here is a typical code layout:
# In Foo.pm package Foo; sub new { ... } sub Foo::INC { my ($self, $filename) = @_; ... } # In the main program push @INC, Foo->new(...);
Note that these hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See ``%INC'' in perlvar.
For a yet-more-powerful import facility, see ``use'' and perlmod.
-
- reset EXPR
- reset
-
Generally used in a "continue" block at the end of a loop to clear
variables and reset "??" searches so that they work again. The
expression is interpreted as a list of single characters (hyphens
allowed for ranges). All variables and arrays beginning with one of
those letters are reset to their pristine state. If the expression is
omitted, one-match searches ("?pattern?") are reset to match again. Resets
only variables or searches in the current package. Always returns
1.  Resets only package variables---lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See ``my''.
- return EXPR
- return
-
Returns from a subroutine, "eval", or "do FILE" with the value
given in EXPR. Evaluation of EXPR may be in list, scalar, or void
context, depending on how the return value will be used, and the context
may vary from one execution to the next (see "wantarray"). If no EXPR
is given, returns an empty list in list context, the undefined value in
scalar context, and (of course) nothing at all in a void context.
(Note that in the absence of an explicit "return", a subroutine, eval, or do FILE will automatically return the value of the last expression evaluated.)
- reverse LIST
-
In list context, returns a list value consisting of the elements
of LIST in the opposite order. In scalar context, concatenates the
elements of LIST and returns a string value with all characters
in the opposite order.
print join(", ", reverse "world", "Hello"); # Hello, world print scalar reverse "dlrow ,", "olleH"; # Hello, world
Used without arguments in scalar context, reverse() reverses $_.
$_ = "dlrow ,olleH"; print reverse; # No output, list context print scalar reverse; # Hello, world
This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to unwind one hash and build a whole new one, which may take some time on a large hash, such as from a DBM file.
%by_name = reverse %by_address; # Invert the hash
- rewinddir DIRHANDLE
- Sets the current position to the beginning of the directory for the "readdir" routine on DIRHANDLE.
- rindex STR,SUBSTR,POSITION
- rindex STR,SUBSTR
- Works just like index() except that it returns the position of the last occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence beginning at or before that position.
- rmdir FILENAME
- rmdir
-
Deletes the directory specified by FILENAME if that directory is
empty. If it succeeds it returns true, otherwise it returns false and
sets $! (errno). If FILENAME is omitted, uses $_.
To remove a directory tree recursively ("rm -rf" on unix) look at the "rmtree" function of the File::Path module.
- s///
- The substitution operator. See ``Regexp Quote-Like Operators'' in perlop.
- say FILEHANDLE LIST
- say LIST
- say
-
Just like "print", but implicitly appends a newline.
"say LIST" is simply an abbreviation for "{ local $\ = "\n"; print
LIST }".
This keyword is only available when the ``say'' feature is enabled: see feature.
- scalar EXPR
-
Forces EXPR to be interpreted in scalar context and returns the value
of EXPR.
@counts = ( scalar @a, scalar @b, scalar @c );
There is no equivalent operator to force an expression to be interpolated in list context because in practice, this is never needed. If you really wanted to do so, however, you could use the construction "@{[ (some expression) ]}", but usually a simple "(some expression)" suffices.
Because "scalar" is unary operator, if you accidentally use for EXPR a parenthesized list, this behaves as a scalar comma expression, evaluating all but the last element in void context and returning the final element evaluated in scalar context. This is seldom what you want.
The following single statement:
print uc(scalar(&foo,$bar)),$baz;
is the moral equivalent of these two:
&foo; print(uc($bar),$baz);
See perlop for more details on unary operators and the comma operator.
- seek FILEHANDLE,POSITION,WHENCE
-
Sets FILEHANDLE's position, just like the "fseek" call of "stdio".
FILEHANDLE may be an expression whose value gives the name of the
filehandle. The values for WHENCE are 0 to set the new position
in bytes to POSITION, 1 to set it to the current position plus
POSITION, and 2 to set it to EOF plus POSITION (typically
negative). For WHENCE you may use the constants "SEEK_SET",
"SEEK_CUR", and "SEEK_END" (start of the file, current position, end
of the file) from the Fcntl module. Returns 1 upon success, 0
otherwise.
Note the in bytes: even if the filehandle has been set to operate on characters (for example by using the ":encoding(utf8)" open layer), tell() will return byte offsets, not character offsets (because implementing that would render seek() and tell() rather slow).
If you want to position file for "sysread" or "syswrite", don't use "seek"--buffering makes its effect on the file's system position unpredictable and non-portable. Use "sysseek" instead.
Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing. Amongst other things, this may have the effect of calling stdio's clearerr(3). A WHENCE of 1 ("SEEK_CUR") is useful for not moving the file position:
seek(TEST,0,1);
This is also useful for applications emulating "tail -f". Once you hit EOF on your read, and then sleep for a while, you might have to stick in a seek() to reset things. The "seek" doesn't change the current position, but it does clear the end-of-file condition on the handle, so that the next "<FILE>" makes Perl try again to read something. We hope.
If that doesn't work (some IO implementations are particularly cantankerous), then you may need something more like this:
for (;;) { for ($curpos = tell(FILE); $_ = <FILE>; $curpos = tell(FILE)) { # search for some stuff and put it into files } sleep($for_a_while); seek(FILE, $curpos, 0); }
- seekdir DIRHANDLE,POS
- Sets the current position for the "readdir" routine on DIRHANDLE. POS must be a value returned by "telldir". "seekdir" also has the same caveats about possible directory compaction as the corresponding system library routine.
- select FILEHANDLE
- select
-
Returns the currently selected filehandle. If FILEHANDLE is supplied,
sets the new current default filehandle for output. This has two
effects: first, a "write" or a "print" without a filehandle will
default to this FILEHANDLE. Second, references to variables related to
output will refer to this output channel. For example, if you have to
set the top of form format for more than one output channel, you might
do the following:
select(REPORT1); $^ = 'report1_top'; select(REPORT2); $^ = 'report2_top';
FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus:
$oldfh = select(STDERR); $| = 1; select($oldfh);
Some programmers may prefer to think of filehandles as objects with methods, preferring to write the last example as:
use IO::Handle; STDERR->autoflush(1);
- select RBITS,WBITS,EBITS,TIMEOUT
-
This calls the select(2) system call with the bit masks specified, which
can be constructed using "fileno" and "vec", along these lines:
$rin = $win = $ein = ''; vec($rin,fileno(STDIN),1) = 1; vec($win,fileno(STDOUT),1) = 1; $ein = $rin | $win;
If you want to select on many filehandles you might wish to write a subroutine:
sub fhbits { my(@fhlist) = split(' ',$_[0]); my($bits); for (@fhlist) { vec($bits,fileno($_),1) = 1; } $bits; } $rin = fhbits('STDIN TTY SOCK');
The usual idiom is:
($nfound,$timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
or to block until something becomes ready just do this
$nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
Most systems do not bother to return anything useful in $timeleft, so calling select() in scalar context just returns $nfound.
Any of the bit masks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout.
You can effect a sleep of 250 milliseconds this way:
select(undef, undef, undef, 0.25);
Note that whether "select" gets restarted after signals (say, SIGALRM) is implementation-dependent. See also perlport for notes on the portability of "select".
On error, "select" behaves like the select(2) system call : it returns -1 and sets $!.
Note: on some Unixes, the select(2) system call may report a socket file descriptor as ``ready for reading'', when actually no data is available, thus a subsequent read blocks. It can be avoided using always the O_NONBLOCK flag on the socket. See select(2) and fcntl(2) for further details.
WARNING: One should not attempt to mix buffered I/O (like "read" or <FH>) with "select", except as permitted by POSIX, and even then only on POSIX systems. You have to use "sysread" instead.
- semctl ID,SEMNUM,CMD,ARG
-
Calls the System V IPC function "semctl". You'll probably have to say
use IPC::SysV;
first to get the correct constant definitions. If CMD is IPC_STAT or GETALL, then ARG must be a variable that will hold the returned semid_ds structure or semaphore value array. Returns like "ioctl": the undefined value for error, ""0 but true"" for zero, or the actual return value otherwise. The ARG must consist of a vector of native short integers, which may be created with "pack("s!",(0)x$nsem)". See also ``SysV IPC'' in perlipc, "IPC::SysV", "IPC::Semaphore" documentation.
- semget KEY,NSEMS,FLAGS
- Calls the System V IPC function semget. Returns the semaphore id, or the undefined value if there is an error. See also ``SysV IPC'' in perlipc, "IPC::SysV", "IPC::SysV::Semaphore" documentation.
- semop KEY,OPSTRING
-
Calls the System V IPC function semop to perform semaphore operations
such as signalling and waiting. OPSTRING must be a packed array of
semop structures. Each semop structure can be generated with
"pack("s!3", $semnum, $semop, $semflag)". The length of OPSTRING
implies the number of semaphore operations. Returns true if
successful, or false if there is an error. As an example, the
following code waits on semaphore $semnum of semaphore id $semid:
$semop = pack("s!3", $semnum, -1, 0); die "Semaphore trouble: $!\n" unless semop($semid, $semop);
To signal the semaphore, replace "-1" with 1. See also ``SysV IPC'' in perlipc, "IPC::SysV", and "IPC::SysV::Semaphore" documentation.
- send SOCKET,MSG,FLAGS,TO
- send SOCKET,MSG,FLAGS
-
Sends a message on a socket. Attempts to send the scalar MSG to the
SOCKET filehandle. Takes the same flags as the system call of the
same name. On unconnected sockets you must specify a destination to
send TO, in which case it does a C "sendto". Returns the number of
characters sent, or the undefined value if there is an error. The C
system call sendmsg(2) is currently unimplemented. See
``UDP: Message Passing'' in perlipc for examples.
Note the characters: depending on the status of the socket, either (8-bit) bytes or characters are sent. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the ":encoding(utf8)" I/O layer (see ``open'', or the "open" pragma, open), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the ":encoding" pragma: in that case pretty much any characters can be sent.
- setpgrp PID,PGRP
- Sets the current process group for the specified PID, 0 for the current process. Will produce a fatal error if used on a machine that doesn't implement POSIX setpgid(2) or BSD setpgrp(2). If the arguments are omitted, it defaults to "0,0". Note that the BSD 4.2 version of "setpgrp" does not accept any arguments, so only "setpgrp(0,0)" is portable. See also "POSIX::setsid()".
- setpriority WHICH,WHO,PRIORITY
- Sets the current priority for a process, a process group, or a user. (See setpriority(2).) Will produce a fatal error if used on a machine that doesn't implement setpriority(2).
- setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL
-
Sets the socket option requested. Returns undefined if there is an
error. Use integer constants provided by the "Socket" module for
LEVEL and OPNAME. Values for LEVEL can also be obtained from
getprotobyname. OPTVAL might either be a packed string or an integer.
An integer OPTVAL is shorthand for pack(``i'', OPTVAL).
An example disabling the Nagle's algorithm for a socket:
use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
- shift ARRAY
- shift
-
Shifts the first value of the array off and returns it, shortening the
array by 1 and moving everything down. If there are no elements in the
array, returns the undefined value. If ARRAY is omitted, shifts the
@_ array within the lexical scope of subroutines and formats, and the
@ARGV array outside of a subroutine and also within the lexical scopes
established by the "eval STRING", "BEGIN {}", "INIT {}", "CHECK {}",
"UNITCHECK {}" and "END {}" constructs.
See also "unshift", "push", and "pop". "shift" and "unshift" do the same thing to the left end of an array that "pop" and "push" do to the right end.
- shmctl ID,CMD,ARG
-
Calls the System V IPC function shmctl. You'll probably have to say
use IPC::SysV;
first to get the correct constant definitions. If CMD is "IPC_STAT", then ARG must be a variable that will hold the returned "shmid_ds" structure. Returns like ioctl: the undefined value for error, "0 but true" for zero, or the actual return value otherwise. See also ``SysV IPC'' in perlipc and "IPC::SysV" documentation.
- shmget KEY,SIZE,FLAGS
- Calls the System V IPC function shmget. Returns the shared memory segment id, or the undefined value if there is an error. See also ``SysV IPC'' in perlipc and "IPC::SysV" documentation.
- shmread ID,VAR,POS,SIZE
- shmwrite ID,STRING,POS,SIZE
- Reads or writes the System V shared memory segment ID starting at position POS for size SIZE by attaching to it, copying in/out, and detaching from it. When reading, VAR must be a variable that will hold the data read. When writing, if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out SIZE bytes. Return true if successful, or false if there is an error. shmread() taints the variable. See also ``SysV IPC'' in perlipc, "IPC::SysV" documentation, and the "IPC::Shareable" module from CPAN.
- shutdown SOCKET,HOW
-
Shuts down a socket connection in the manner indicated by HOW, which
has the same interpretation as in the system call of the same name.
shutdown(SOCKET, 0); # I/we have stopped reading data shutdown(SOCKET, 1); # I/we have stopped writing data shutdown(SOCKET, 2); # I/we have stopped using this socket
This is useful with sockets when you want to tell the other side you're done writing but not done reading, or vice versa. It's also a more insistent form of close because it also disables the file descriptor in any forked copies in other processes.
Returns 1 for success. In the case of error, returns "undef" if the first argument is not a valid filehandle, or returns 0 and sets $! for any other failure.
- sin EXPR
- sin
-
Returns the sine of EXPR (expressed in radians). If EXPR is omitted,
returns sine of $_.
For the inverse sine operation, you may use the "Math::Trig::asin" function, or use this relation:
sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
- sleep EXPR
- sleep
-
Causes the script to sleep for EXPR seconds, or forever if no EXPR.
Returns the number of seconds actually slept.
May be interrupted if the process receives a signal such as "SIGALRM".
eval { local $SIG{ALARM} = sub { die "Alarm!\n" }; sleep; }; die $@ unless $@ eq "Alarm!\n";
You probably cannot mix "alarm" and "sleep" calls, because "sleep" is often implemented using "alarm".
On some older systems, it may sleep up to a full second less than what you requested, depending on how it counts seconds. Most modern systems always sleep the full amount. They may appear to sleep longer than that, however, because your process might not be scheduled right away in a busy multitasking system.
For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep(). You may also use Perl's four-argument version of select() leaving the first three arguments undefined, or you might be able to use the "syscall" interface to access setitimer(2) if your system supports it. See perlfaq8 for details.
See also the POSIX module's "pause" function.
- socket SOCKET,DOMAIN,TYPE,PROTOCOL
-
Opens a socket of the specified kind and attaches it to filehandle
SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for
the system call of the same name. You should "use Socket" first
to get the proper definitions imported. See the examples in
``Sockets: Client/Server Communication'' in perlipc.
On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See ``$^F'' in perlvar.
- socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL
-
Creates an unnamed pair of sockets in the specified domain, of the
specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as
for the system call of the same name. If unimplemented, yields a fatal
error. Returns true if successful.
On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptors, as determined by the value of $^F. See ``$^F'' in perlvar.
Some systems defined "pipe" in terms of "socketpair", in which a call to "pipe(Rdr, Wtr)" is essentially:
use Socket; socketpair(Rdr, Wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); shutdown(Rdr, 1); # no more writing for reader shutdown(Wtr, 0); # no more reading for writer
See perlipc for an example of socketpair use. Perl 5.8 and later will emulate socketpair using IP sockets to localhost if your system implements sockets but not socketpair.
- sort SUBNAME LIST
- sort BLOCK LIST
- sort LIST
-
In list context, this sorts the LIST and returns the sorted list value.
In scalar context, the behaviour of "sort()" is undefined.
If SUBNAME or BLOCK is omitted, "sort"s in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0, depending on how the elements of the list are to be ordered. (The "<=>" and "cmp" operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.
If the subroutine's prototype is "($$)", the elements to be compared are passed by reference in @_, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below). Note that in the latter case, it is usually counter-productive to declare $a and $b as lexicals.
The values to be compared are always passed by reference and should not be modified.
You also cannot exit out of the sort block or subroutine using any of the loop control operators described in perlsyn or with "goto".
When "use locale" is in effect, "sort LIST" sorts LIST according to the current collation locale. See perllocale.
sort() returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by sort() (for example, in a "foreach", "map" or "grep") actually modifies the element in the original list. This is usually something to be avoided when writing clear code.
Perl 5.6 and earlier used a quicksort algorithm to implement sort. That algorithm was not stable, and could go quadratic. (A stable sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), quadratic behavior, for some inputs.) In 5.7, the quicksort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN). But benchmarks indicated that for some inputs, on some platforms, the original quicksort was faster. 5.8 has a sort pragma for limited control of the sort. Its rather blunt control of the underlying algorithm may not persist into future Perls, but the ability to characterize the input or output in implementation independent ways quite probably will. See the sort pragma.
Examples:
# sort lexically @articles = sort @files; # same thing, but with explicit sort routine @articles = sort {$a cmp $b} @files; # now case-insensitively @articles = sort {uc($a) cmp uc($b)} @files; # same thing in reversed order @articles = sort {$b cmp $a} @files; # sort numerically ascending @articles = sort {$a <=> $b} @files; # sort numerically descending @articles = sort {$b <=> $a} @files; # this sorts the %age hash by value instead of key # using an in-line function @eldest = sort { $age{$b} <=> $age{$a} } keys %age; # sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming numeric } @sortedclass = sort byage @class; sub backwards { $b cmp $a } @harry = qw(dog cat x Cain Abel); @george = qw(gone chased yz Punished Axed); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print sort @george, 'to', @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz # inefficiently sort by descending numeric compare using # the first integer after the first = sign, or the # whole record case-insensitively otherwise @new = sort { ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] || uc($a) cmp uc($b) } @old; # same thing, but much more efficiently; # we'll build auxiliary indices instead # for speed @nums = @caps = (); for (@old) { push @nums, /=(\d+)/; push @caps, uc($_); } @new = @old[ sort { $nums[$b] <=> $nums[$a] || $caps[$a] cmp $caps[$b] } 0..$#old ]; # same thing, but without any temps @new = map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [$_, /=(\d+)/, uc($_)] } @old; # using a prototype allows you to use any comparison subroutine # as a sort subroutine (including other package's subroutines) package other; sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are not set here package main; @new = sort other::backwards @old; # guarantee stability, regardless of algorithm use sort 'stable'; @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; # force use of mergesort (not portable outside Perl 5.8) use sort '_mergesort'; # note discouraging _ @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;
Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call "find_records(@key)", you can use:
@contact = sort { $a cmp $b } find_records @key; @contact = sort +find_records(@key); @contact = sort &find_records(@key); @contact = sort(find_records(@key));
If instead you want to sort the array @key with the comparison routine "find_records()" then you can use:
@contact = sort { find_records() } @key; @contact = sort find_records(@key); @contact = sort(find_records @key); @contact = sort(find_records (@key));
If you're using strict, you must not declare $a and $b as lexicals. They are package globals. That means that if you're in the "main" package and type
@articles = sort {$b <=> $a} @files;
then $a and $b are $main::a and $main::b (or $::a and $::b), but if you're in the "FooPack" package, it's the same as typing
@articles = sort {$FooPack::b <=> $FooPack::a} @files;
The comparison function is required to behave. If it returns inconsistent results (sometimes saying $x[1] is less than $x[2] and sometimes saying the opposite, for example) the results are not well-defined.
Because "<=>" returns "undef" when either operand is "NaN" (not-a-number), and because "sort" will trigger a fatal error unless the result of a comparison is defined, when sorting with a comparison function like "$a <=> $b", be careful about lists that might contain a "NaN". The following example takes advantage of the fact that "NaN != NaN" to eliminate any "NaN"s from the input.
@result = sort { $a <=> $b } grep { $_ == $_ } @input;
- splice ARRAY,OFFSET,LENGTH,LIST
- splice ARRAY,OFFSET,LENGTH
- splice ARRAY,OFFSET
- splice ARRAY
-
Removes the elements designated by OFFSET and LENGTH from an array, and
replaces them with the elements of LIST, if any. In list context,
returns the elements removed from the array. In scalar context,
returns the last element removed, or "undef" if no elements are
removed. The array grows or shrinks as necessary.
If OFFSET is negative then it starts that far from the end of the array.
If LENGTH is omitted, removes everything from OFFSET onward.
If LENGTH is negative, removes the elements from OFFSET onward
except for -LENGTH elements at the end of the array.
If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is
past the end of the array, perl issues a warning, and splices at the
end of the array.
The following equivalences hold (assuming "$[ == 0 and $#a >= $i" )
push(@a,$x,$y) splice(@a,@a,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$i] = $y splice(@a,$i,1,$y)
Example, assuming array lengths are passed before arrays:
sub aeq { # compare two list values my(@a) = splice(@_,0,shift); my(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
- split /PATTERN/,EXPR,LIMIT
- split /PATTERN/,EXPR
- split /PATTERN/
- split
-
Splits the string EXPR into a list of strings and returns that list. By
default, empty leading fields are preserved, and empty trailing ones are
deleted. (If all fields are empty, they are considered to be trailing.)
In scalar context, returns the number of fields found. In scalar and void context it splits into the @_ array. Use of split in scalar and void context is deprecated, however, because it clobbers your subroutine arguments.
If EXPR is omitted, splits the $_ string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.)
If LIMIT is specified and positive, it represents the maximum number of fields the EXPR will be split into, though the actual number of fields returned depends on the number of times PATTERN matches within EXPR. If LIMIT is unspecified or zero, trailing null fields are stripped (which potential users of "pop" would do well to remember). If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified. Note that splitting an EXPR that evaluates to the empty string always returns the empty list, regardless of the LIMIT specified.
A pattern matching the null string (not to be confused with a null pattern "//", which is just one member of the set of patterns matching a null string) will split the value of EXPR into separate characters at each point it matches that way. For example:
print join(':', split(/ */, 'hi there')), "\n";
produces the output 'h:i:t:h:e:r:e'.
As a special case for "split", using the empty pattern "//" specifically matches only the null string, and is not be confused with the regular use of "//" to mean ``the last successful pattern match''. So, for "split", the following:
print join(':', split(//, 'hi there')), "\n";
produces the output 'h:i: :t:h:e:r:e'.
Empty leading fields are produced when there are positive-width matches at the beginning of the string; a zero-width match at the beginning of the string does not produce an empty field. For example:
print join(':', split(/(?=\w)/, 'hi there!'));
produces the output 'h:i :t:h:e:r:e!'. Empty trailing fields, on the other hand, are produced when there is a match at the end of the string (and when LIMIT is given and is not 0), regardless of the length of the match. For example:
print join(':', split(//, 'hi there!', -1)), "\n"; print join(':', split(/\W/, 'hi there!', -1)), "\n";
produce the output 'h:i: :t:h:e:r:e:!:' and 'hi:there:', respectively, both with an empty trailing field.
The LIMIT parameter can be used to split a line partially
($login, $passwd, $remainder) = split(/:/, $_, 3);
When assigning to a list, if LIMIT is omitted, or zero, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work. For the list above LIMIT would have been 4 by default. In time critical applications it behooves you not to split into more fields than you really need.
If the PATTERN contains parentheses, additional list elements are created from each matching substring in the delimiter.
split(/([,-])/, "1-10,20", 3);
produces the list value
(1, '-', 10, ',', 20)
If you had the entire header of a normal Unix email message in $header, you could split it up into fields and their values this way:
$header =~ s/\n(?=\s)//g; # fix continuation lines %hdrs = (UNIX_FROM => split /^(\S*?):\s*/m, $header);
The pattern "/PATTERN/" may be replaced with an expression to specify patterns that vary at runtime. (To do runtime compilation only once, use "/$variable/o".)
As a special case, specifying a PATTERN of space (' ') will split on white space just as "split" with no arguments does. Thus, "split(' ')" can be used to emulate awk's default behavior, whereas "split(/ /)" will give you as many null initial fields as there are leading spaces. A "split" on "/\s+/" is like a "split(' ')" except that any leading whitespace produces a null first field. A "split" with no arguments really does a "split(' ', $_)" internally.
A PATTERN of "/^/" is treated as if it were "/^/m", since it isn't much use otherwise.
Example:
open(PASSWD, '/etc/passwd'); while (<PASSWD>) { chomp; ($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/); #... }
As with regular pattern matching, any capturing parentheses that are not matched in a "split()" will be set to "undef" when returned:
@fields = split /(A)|B/, "1A2B3"; # @fields is (1, 'A', 2, undef, 3)
- sprintf FORMAT, LIST
-
Returns a string formatted by the usual "printf" conventions of the C
library function "sprintf". See below for more details
and see sprintf(3) or printf(3) on your system for an explanation of
the general principles.
For example:
# Format number with up to 8 leading zeroes $result = sprintf("%08d", $number); # Round number to 3 digits after decimal point $rounded = sprintf("%.3f", $number);
Perl does its own "sprintf" formatting---it emulates the C function "sprintf", but it doesn't use it (except for floating-point numbers, and even then only the standard modifiers are allowed). As a result, any non-standard extensions in your local "sprintf" are not available from Perl.
Unlike "printf", "sprintf" does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful.
Perl's "sprintf" permits the following universally-known conversions:
%% a percent sign %c a character with the given number %s a string %d a signed integer, in decimal %u an unsigned integer, in decimal %o an unsigned integer, in octal %x an unsigned integer, in hexadecimal %e a floating-point number, in scientific notation %f a floating-point number, in fixed decimal notation %g a floating-point number, in %e or %f notation
In addition, Perl permits the following widely-supported conversions:
%X like %x, but using upper-case letters %E like %e, but using an upper-case "E" %G like %g, but with an upper-case "E" (if applicable) %b an unsigned integer, in binary %B like %b, but using an upper-case "B" with the # flag %p a pointer (outputs the Perl value's address in hexadecimal) %n special: *stores* the number of characters output so far into the next variable in the parameter list
Finally, for backward (and we do mean ``backward'') compatibility, Perl permits these unnecessary but widely-supported conversions:
%i a synonym for %d %D a synonym for %ld %U a synonym for %lu %O a synonym for %lo %F a synonym for %f
Note that the number of exponent digits in the scientific notation produced by %e, %E, %g and %G for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either ``1.23e99'' or ``1.23e099''.
Between the "%" and the format letter, you may specify a number of additional attributes controlling the interpretation of the format. In order, these are:
-
- format parameter index
-
An explicit format parameter index, such as "2$". By default sprintf
will format the next unused argument in the list, but this allows you
to take the arguments out of order, e.g.:
printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
- flags
-
one or more of:
space prefix non-negative number with a space + prefix non-negative number with a plus sign - left-justify within the field 0 use zeros, not spaces, to right-justify # ensure the leading "0" for any octal, prefix non-zero hexadecimal with "0x" or "0X", prefix non-zero binary with "0b" or "0B"
For example:
printf '<% d>', 12; # prints "< 12>" printf '<%+d>', 12; # prints "<+12>" printf '<%6s>', 12; # prints "< 12>" printf '<%-6s>', 12; # prints "<12 >" printf '<%06s>', 12; # prints "<000012>" printf '<%#o>', 12; # prints "<014>" printf '<%#x>', 12; # prints "<0xc>" printf '<%#X>', 12; # prints "<0XC>" printf '<%#b>', 12; # prints "<0b1100>" printf '<%#B>', 12; # prints "<0B1100>"
When a space and a plus sign are given as the flags at once, a plus sign is used to prefix a positive number.
printf '<%+ d>', 12; # prints "<+12>" printf '<% +d>', 12; # prints "<+12>"
When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading ``0''.
printf '<%#.5o>', 012; # prints "<00012>" printf '<%#.5o>', 012345; # prints "<012345>" printf '<%#.0o>', 0; # prints "<0>"
- vector flag
-
This flag tells perl to interpret the supplied string as a vector of
integers, one for each character in the string. Perl applies the format to
each integer in turn, then joins the resulting strings with a separator (a
dot "." by default). This can be useful for displaying ordinal values of
characters in arbitrary strings:
printf "%vd", "AB\x{100}"; # prints "65.66.256" printf "version is v%vd\n", $^V; # Perl's version
Put an asterisk "*" before the "v" to override the string to use to separate the numbers:
printf "address is %*vX\n", ":", $addr; # IPv6 address printf "bits are %0*v8b\n", " ", $bits; # random bitstring
You can also explicitly specify the argument number to use for the join string using e.g. "*2$v":
printf '%*4$vX %*4$vX %*4$vX', @addr[1..3], ":"; # 3 IPv6 addresses
- (minimum) width
-
Arguments are usually formatted to be only as wide as required to
display the given value. You can override the width by putting
a number here, or get the width from the next argument (with "*")
or from a specified argument (with e.g. "*2$"):
printf '<%s>', "a"; # prints "<a>" printf '<%6s>', "a"; # prints "< a>" printf '<%*s>', 6, "a"; # prints "< a>" printf '<%*2$s>', "a", 6; # prints "< a>" printf '<%2s>', "long"; # prints "<long>" (does not truncate)
If a field width obtained through "*" is negative, it has the same effect as the "-" flag: left-justification.
- precision, or maximum width
-
You can specify a precision (for numeric conversions) or a maximum
width (for string conversions) by specifying a "." followed by a number.
For floating point formats, with the exception of 'g' and 'G', this specifies
the number of decimal places to show (the default being 6), e.g.:
# these examples are subject to system-specific variation printf '<%f>', 1; # prints "<1.000000>" printf '<%.1f>', 1; # prints "<1.0>" printf '<%.0f>', 1; # prints "<1>" printf '<%e>', 10; # prints "<1.000000e+01>" printf '<%.1e>', 10; # prints "<1.0e+01>"
For 'g' and 'G', this specifies the maximum number of digits to show, including prior to the decimal point as well as after it, e.g.:
# these examples are subject to system-specific variation printf '<%g>', 1; # prints "<1>" printf '<%.10g>', 1; # prints "<1>" printf '<%g>', 100; # prints "<100>" printf '<%.1g>', 100; # prints "<1e+02>" printf '<%.2g>', 100.01; # prints "<1e+02>" printf '<%.5g>', 100.01; # prints "<100.01>" printf '<%.4g>', 100.01; # prints "<100>"
For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored:
printf '<%.6d>', 1; # prints "<000001>" printf '<%+.6d>', 1; # prints "<+000001>" printf '<%-10.6d>', 1; # prints "<000001 >" printf '<%10.6d>', 1; # prints "< 000001>" printf '<%010.6d>', 1; # prints "< 000001>" printf '<%+10.6d>', 1; # prints "< +000001>" printf '<%.6x>', 1; # prints "<000001>" printf '<%#.6x>', 1; # prints "<0x000001>" printf '<%-10.6x>', 1; # prints "<000001 >" printf '<%10.6x>', 1; # prints "< 000001>" printf '<%010.6x>', 1; # prints "< 000001>" printf '<%#10.6x>', 1; # prints "< 0x000001>"
For string conversions, specifying a precision truncates the string to fit in the specified width:
printf '<%.5s>', "truncated"; # prints "<trunc>" printf '<%10.5s>', "truncated"; # prints "< trunc>"
You can also get the precision from the next argument using ".*":
printf '<%.6x>', 1; # prints "<000001>" printf '<%.*x>', 6, 1; # prints "<000001>"
If a precision obtained through "*" is negative, it has the same effect as no precision.
printf '<%.*s>', 7, "string"; # prints "<string>" printf '<%.*s>', 3, "string"; # prints "<str>" printf '<%.*s>', 0, "string"; # prints "<>" printf '<%.*s>', -1, "string"; # prints "<string>" printf '<%.*d>', 1, 0; # prints "<0>" printf '<%.*d>', 0, 0; # prints "<>" printf '<%.*d>', -1, 0; # prints "<0>"
You cannot currently get the precision from a specified number, but it is intended that this will be possible in the future using e.g. ".*2$":
printf '<%.*2$x>', 1, 6; # INVALID, but in future will print "<000001>"
- size
-
For numeric conversions, you can specify the size to interpret the
number as using "l", "h", "V", "q", "L", or "ll". For integer
conversions ("d u o x X b i D U O"), numbers are usually assumed to be
whatever the default integer size is on your platform (usually 32 or 64
bits), but you can override this to use instead one of the standard C types,
as supported by the compiler used to build Perl:
l interpret integer as C type "long" or "unsigned long" h interpret integer as C type "short" or "unsigned short" q, L or ll interpret integer as C type "long long", "unsigned long long". or "quads" (typically 64-bit integers)
The last will produce errors if Perl does not understand ``quads'' in your installation. (This requires that either the platform natively supports quads or Perl was specifically compiled to support quads.) You can find out whether your Perl supports quads via Config:
use Config; ($Config{use64bitint} eq 'define' || $Config{longsize} >= 8) && print "quads\n";
For floating point conversions ("e f g E F G"), numbers are usually assumed to be the default floating point size on your platform (double or long double), but you can force 'long double' with "q", "L", or "ll" if your platform supports them. You can find out whether your Perl supports long doubles via Config:
use Config; $Config{d_longdbl} eq 'define' && print "long doubles\n";
You can find out whether Perl considers 'long double' to be the default floating point size to use on your platform via Config:
use Config; ($Config{uselongdouble} eq 'define') && print "long doubles by default\n";
It can also be the case that long doubles and doubles are the same thing:
use Config; ($Config{doublesize} == $Config{longdblsize}) && print "doubles are long doubles\n";
The size specifier "V" has no effect for Perl code, but it is supported for compatibility with XS code; it means 'use the standard size for a Perl integer (or floating-point number)', which is already the default for Perl code.
- order of arguments
-
Normally, sprintf takes the next unused argument as the value to
format for each format specification. If the format specification
uses "*" to require additional arguments, these are consumed from
the argument list in the order in which they appear in the format
specification before the value to format. Where an argument is
specified using an explicit index, this does not affect the normal
order for the arguments (even when the explicitly specified index
would have been the next argument in any case).
So:
printf '<%*.*s>', $a, $b, $c;
would use $a for the width, $b for the precision and $c as the value to format, while:
printf '<%*1$.*s>', $a, $b;
would use $a for the width and the precision, and $b as the value to format.
Here are some more examples - beware that when using an explicit index, the "$" may need to be escaped:
printf "%2\$d %d\n", 12, 34; # will print "34 12\n" printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n"
-
If "use locale" is in effect, and POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating point numbers is affected by the LC_NUMERIC locale. See perllocale and POSIX.
-
- sqrt EXPR
- sqrt
-
Return the square root of EXPR. If EXPR is omitted, returns square
root of $_. Only works on non-negative operands, unless you've
loaded the standard Math::Complex module.
use Math::Complex; print sqrt(-2); # prints 1.4142135623731i
- srand EXPR
- srand
-
Sets the random number seed for the "rand" operator.
The point of the function is to ``seed'' the "rand" function so that "rand" can produce a different sequence each time you run your program.
If srand() is not called explicitly, it is called implicitly at the first use of the "rand" operator. However, this was not the case in versions of Perl before 5.004, so if your script will run under older Perl versions, it should call "srand".
Most programs won't even call srand() at all, except those that need a cryptographically-strong starting point rather than the generally acceptable default, which is based on time of day, process ID, and memory allocation, or the /dev/urandom device, if available.
You can call srand($seed) with the same $seed to reproduce the same sequence from rand(), but this is usually reserved for generating predictable results for testing or debugging. Otherwise, don't call srand() more than once in your program.
Do not call srand() (i.e. without an argument) more than once in a script. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling srand() again actually loses randomness.
Most implementations of "srand" take an integer and will silently truncate decimal numbers. This means "srand(42)" will usually produce the same results as "srand(42.1)". To be safe, always pass "srand" an integer.
In versions of Perl prior to 5.004 the default seed was just the current "time". This isn't a particularly good seed, so many old programs supply their own seed value (often "time ^ $$" or "time ^ ($$ + ($$ << 15))"), but that isn't necessary any more.
For cryptographic purposes, however, you need something much more random than the default seed. Checksumming the compressed output of one or more rapidly changing operating system status programs is the usual method. For example:
srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);
If you're particularly concerned with this, see the "Math::TrulyRandom" module in CPAN.
Frequently called programs (like CGI scripts) that simply use
time ^ $$
for a seed can fall prey to the mathematical property that
a^b == (a+1)^(b+1)
one-third of the time. So don't do that.
- stat FILEHANDLE
- stat EXPR
- stat DIRHANDLE
- stat
-
Returns a 13-element list giving the status info for a file, either
the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is
omitted, it stats $_. Returns a null list if the stat fails. Typically
used as follows:
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($filename);
Not all fields are supported on all filesystem types. Here are the meanings of the fields:
0 dev device number of filesystem 1 ino inode number 2 mode file mode (type and permissions) 3 nlink number of (hard) links to the file 4 uid numeric user ID of file's owner 5 gid numeric group ID of file's owner 6 rdev the device identifier (special files only) 7 size total size of file, in bytes 8 atime last access time in seconds since the epoch 9 mtime last modify time in seconds since the epoch 10 ctime inode change time in seconds since the epoch (*) 11 blksize preferred block size for file system I/O 12 blocks actual number of blocks allocated
(The epoch was at 00:00 January 1, 1970 GMT.)
(*) Not all fields are supported on all filesystem types. Notably, the ctime field is non-portable. In particular, you cannot expect it to be a ``creation time'', see ``Files and Filesystems'' in perlport for details.
If "stat" is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last "stat", "lstat", or filetest are returned. Example:
if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; }
(This works on machines only for which the device number is negative under NFS.)
Because the mode contains both the file type and its permissions, you should mask off the file type portion and (s)printf using a "%o" if you want to see the real permissions.
$mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode & 07777;
In scalar context, "stat" returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle "_".
The File::stat module provides a convenient, by-name access mechanism:
use File::stat; $sb = stat($filename); printf "File is %s, size is %s, perm %04o, mtime %s\n", $filename, $sb->size, $sb->mode & 07777, scalar localtime $sb->mtime;
You can import symbolic mode constants ("S_IF*") and functions ("S_IS*") from the Fcntl module:
use Fcntl ':mode'; $mode = (stat($filename))[2]; $user_rwx = ($mode & S_IRWXU) >> 6; $group_read = ($mode & S_IRGRP) >> 3; $other_execute = $mode & S_IXOTH; printf "Permissions are %04o\n", S_IMODE($mode), "\n"; $is_setuid = $mode & S_ISUID; $is_directory = S_ISDIR($mode);
You could write the last two using the "-u" and "-d" operators. The commonly available "S_IF*" constants are
# Permissions: read, write, execute, for user, group, others. S_IRWXU S_IRUSR S_IWUSR S_IXUSR S_IRWXG S_IRGRP S_IWGRP S_IXGRP S_IRWXO S_IROTH S_IWOTH S_IXOTH # Setuid/Setgid/Stickiness/SaveText. # Note that the exact meaning of these is system dependent. S_ISUID S_ISGID S_ISVTX S_ISTXT # File types. Not necessarily all are available on your system. S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO S_IFSOCK S_IFWHT S_ENFMT # The following are compatibility aliases for S_IRUSR, S_IWUSR, S_IXUSR. S_IREAD S_IWRITE S_IEXEC
and the "S_IF*" functions are
S_IMODE($mode) the part of $mode containing the permission bits and the setuid/setgid/sticky bits S_IFMT($mode) the part of $mode containing the file type which can be bit-anded with e.g. S_IFREG or with the following functions # The operators -f, -d, -l, -b, -c, -p, and -S. S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) # No direct -X operator counterpart, but for the first one # the -g operator is often equivalent. The ENFMT stands for # record flocking enforcement, a platform-dependent feature. S_ISENFMT($mode) S_ISWHT($mode)
See your native chmod(2) and stat(2) documentation for more details about the "S_*" constants. To get status info for a symbolic link instead of the target file behind the link, use the "lstat" function.
- state EXPR
- state TYPE EXPR
- state EXPR : ATTRS
- state TYPE EXPR : ATTRS
-
"state" declares a lexically scoped variable, just like "my" does.
However, those variables will never be reinitialized, contrary to
lexical variables that are reinitialized each time their enclosing block
is entered.
"state" variables are only enabled when the "feature 'state'" pragma is in effect. See feature.
- study SCALAR
- study
-
Takes extra time to study SCALAR ($_ if unspecified) in anticipation of
doing many pattern matches on the string before it is next modified.
This may or may not save time, depending on the nature and number of
patterns you are searching on, and on the distribution of character
frequencies in the string to be searched---you probably want to compare
run times with and without it to see which runs faster. Those loops
that scan for many short constant strings (including the constant
parts of more complex patterns) will benefit most. You may have only
one "study" active at a time---if you study a different scalar the first
is ``unstudied''. (The way "study" works is this: a linked list of every
character in the string to be searched is made, so we know, for
example, where all the 'k' characters are. From each search string,
the rarest character is selected, based on some static frequency tables
constructed from some C programs and English text. Only those places
that contain this ``rarest'' character are examined.)
For example, here is a loop that inserts index producing entries before any line containing a certain pattern:
while (<>) { study; print ".IX foo\n" if /\bfoo\b/; print ".IX bar\n" if /\bbar\b/; print ".IX blurfl\n" if /\bblurfl\b/; # ... print; }
In searching for "/\bfoo\b/", only those locations in $_ that contain "f" will be looked at, because "f" is rarer than "o". In general, this is a big win except in pathological cases. The only question is whether it saves you more time than it took to build the linked list in the first place.
Note that if you have to look for strings that you don't know till runtime, you can build an entire loop as a string and "eval" that to avoid recompiling all your patterns all the time. Together with undefining $/ to input entire files as one record, this can be very fast, often faster than specialized programs like fgrep(1). The following scans a list of files (@files) for a list of words (@words), and prints out the names of those files that contain a match:
$search = 'while (<>) { study;'; foreach $word (@words) { $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n"; } $search .= "}"; @ARGV = @files; undef $/; eval $search; # this screams $/ = "\n"; # put back to normal input delimiter foreach $file (sort keys(%seen)) { print $file, "\n"; }
- sub NAME BLOCK
- sub NAME (PROTO) BLOCK
- sub NAME : ATTRS BLOCK
- sub NAME (PROTO) : ATTRS BLOCK
-
This is subroutine definition, not a real function per se.
Without a BLOCK it's just a forward declaration. Without a NAME,
it's an anonymous function declaration, and does actually return
a value: the CODE ref of the closure you just created.
See perlsub and perlref for details about subroutines and references, and attributes and Attribute::Handlers for more information about attributes.
- substr EXPR,OFFSET,LENGTH,REPLACEMENT
- substr EXPR,OFFSET,LENGTH
- substr EXPR,OFFSET
-
Extracts a substring out of EXPR and returns it. First character is at
offset 0, or whatever you've set $[ to (but don't do that).
If OFFSET is negative (or more precisely, less than $[), starts
that far from the end of the string. If LENGTH is omitted, returns
everything to the end of the string. If LENGTH is negative, leaves that
many characters off the end of the string.
my $s = "The black cat climbed the green tree"; my $color = substr $s, 4, 5; # black my $middle = substr $s, 4, -11; # black cat climbed the my $end = substr $s, 14; # climbed the green tree my $tail = substr $s, -4; # tree my $z = substr $s, -4, 2; # tr
You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length you may need to pad or chop your value using "sprintf".
If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, substr() returns the undefined value and produces a warning. When used as an lvalue, specifying a substring that is entirely outside the string is a fatal error. Here's an example showing the behavior for boundary cases:
my $name = 'fred'; substr($name, 4) = 'dy'; # $name is now 'freddy' my $null = substr $name, 6, 2; # returns '' (no warning) my $oops = substr $name, 7; # returns undef, with warning substr($name, 7) = 'gap'; # fatal error
An alternative to using substr() as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice().
my $s = "The black cat climbed the green tree"; my $z = substr $s, 14, 7, "jumped from"; # climbed # $s is now "The black cat jumped from the green tree"
Note that the lvalue returned by the 3-arg version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example:
$x = '1234'; for (substr($x,1,2)) { $_ = 'a'; print $x,"\n"; # prints 1a4 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 $x = '56789'; $_ = 'pq'; print $x,"\n"; # prints 5pq9 }
Prior to Perl version 5.9.1, the result of using an lvalue multiple times was unspecified.
- symlink OLDFILE,NEWFILE
-
Creates a new filename symbolically linked to the old filename.
Returns 1 for success, 0 otherwise. On systems that don't support
symbolic links, produces a fatal error at run time. To check for that,
use eval:
$symlink_exists = eval { symlink("",""); 1 };
- syscall NUMBER, LIST
-
Calls the system call specified as the first element of the list,
passing the remaining elements as arguments to the system call. If
unimplemented, produces a fatal error. The arguments are interpreted
as follows: if a given argument is numeric, the argument is passed as
an int. If not, the pointer to the string value is passed. You are
responsible to make sure a string is pre-extended long enough to
receive any result that might be written into a string. You can't use a
string literal (or other read-only string) as an argument to "syscall"
because Perl has to assume that any string pointer might be written
through. If your
integer arguments are not literals and have never been interpreted in a
numeric context, you may need to add 0 to them to force them to look
like numbers. This emulates the "syswrite" function (or vice versa):
require 'syscall.ph'; # may need to run h2ph $s = "hi there\n"; syscall(&SYS_write, fileno(STDOUT), $s, length $s);
Note that Perl supports passing of up to only 14 arguments to your system call, which in practice should usually suffice.
Syscall returns whatever value returned by the system call it calls. If the system call fails, "syscall" returns "-1" and sets $! (errno). Note that some system calls can legitimately return "-1". The proper way to handle such calls is to assign "$!=0;" before the call and check the value of $! if syscall returns "-1".
There's a problem with "syscall(&SYS_pipe)": it returns the file number of the read end of the pipe it creates. There is no way to retrieve the file number of the other end. You can avoid this problem by using "pipe" instead.
- sysopen FILEHANDLE,FILENAME,MODE
- sysopen FILEHANDLE,FILENAME,MODE,PERMS
-
Opens the file whose filename is given by FILENAME, and associates it
with FILEHANDLE. If FILEHANDLE is an expression, its value is used as
the name of the real filehandle wanted. This function calls the
underlying operating system's "open" function with the parameters
FILENAME, MODE, PERMS.
The possible values and flag bits of the MODE parameter are system-dependent; they are available via the standard module "Fcntl". See the documentation of your operating system's "open" to see which values and flag bits are available. You may combine several flags using the "|"-operator.
Some of the most common values are "O_RDONLY" for opening the file in read-only mode, "O_WRONLY" for opening the file in write-only mode, and "O_RDWR" for opening the file in read-write mode.
For historical reasons, some values work on almost every system supported by perl: zero means read-only, one means write-only, and two means read/write. We know that these values do not work under OS/390 & VM/ESA Unix and on the Macintosh; you probably don't want to use them in new code.
If the file named by FILENAME does not exist and the "open" call creates it (typically because MODE includes the "O_CREAT" flag), then the value of PERMS specifies the permissions of the newly created file. If you omit the PERMS argument to "sysopen", Perl uses the octal value 0666. These permission values need to be in octal, and are modified by your process's current "umask".
In many systems the "O_EXCL" flag is available for opening files in exclusive mode. This is not locking: exclusiveness means here that if the file already exists, sysopen() fails. "O_EXCL" may not work on network filesystems, and has no effect unless the "O_CREAT" flag is set as well. Setting "O_CREAT|O_EXCL" prevents the file from being opened if it is a symbolic link. It does not protect against symbolic links in the file's path.
Sometimes you may want to truncate an already-existing file. This can be done using the "O_TRUNC" flag. The behavior of "O_TRUNC" with "O_RDONLY" is undefined.
You should seldom if ever use 0644 as argument to "sysopen", because that takes away the user's option to have a more permissive umask. Better to omit it. See the perlfunc(1) entry on "umask" for more on this.
Note that "sysopen" depends on the fdopen() C library function. On many UNIX systems, fdopen() is known to fail when file descriptors exceed a certain value, typically 255. If you need more file descriptors than that, consider rebuilding Perl to use the "sfio" library, or perhaps using the POSIX::open() function.
See perlopentut for a kinder, gentler explanation of opening files.
- sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
- sysread FILEHANDLE,SCALAR,LENGTH
-
Attempts to read LENGTH bytes of data into variable SCALAR from the
specified FILEHANDLE, using the system call read(2). It bypasses
buffered IO, so mixing this with other kinds of reads, "print",
"write", "seek", "tell", or "eof" can cause confusion because the
perlio or stdio layers usually buffers data. Returns the number of
bytes actually read, 0 at end of file, or undef if there was an
error (in the latter case $! is also set). SCALAR will be grown or
shrunk so that the last byte actually read is the last byte of the
scalar after the read.
An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with "\0" bytes before the result of the read is appended.
There is no syseof() function, which is ok, since eof() doesn't work very well on device files (like ttys) anyway. Use sysread() and check for a return value for 0 to decide whether you're done.
Note that if the filehandle has been marked as ":utf8" Unicode characters are read instead of bytes (the LENGTH, OFFSET, and the return value of sysread() are in Unicode characters). The ":encoding(...)" layer implicitly introduces the ":utf8" layer. See ``binmode'', ``open'', and the "open" pragma, open.
- sysseek FILEHANDLE,POSITION,WHENCE
-
Sets FILEHANDLE's system position in bytes using the system call
lseek(2). FILEHANDLE may be an expression whose value gives the name
of the filehandle. The values for WHENCE are 0 to set the new
position to POSITION, 1 to set the it to the current position plus
POSITION, and 2 to set it to EOF plus POSITION (typically
negative).
Note the in bytes: even if the filehandle has been set to operate on characters (for example by using the ":encoding(utf8)" I/O layer), tell() will return byte offsets, not character offsets (because implementing that would render sysseek() very slow).
sysseek() bypasses normal buffered IO, so mixing this with reads (other than "sysread", for example "<>" or read()) "print", "write", "seek", "tell", or "eof" may cause confusion.
For WHENCE, you may also use the constants "SEEK_SET", "SEEK_CUR", and "SEEK_END" (start of the file, current position, end of the file) from the Fcntl module. Use of the constants is also more portable than relying on 0, 1, and 2. For example to define a ``systell'' function:
use Fcntl 'SEEK_CUR'; sub systell { sysseek($_[0], 0, SEEK_CUR) }
Returns the new position, or the undefined value on failure. A position of zero is returned as the string "0 but true"; thus "sysseek" returns true on success and false on failure, yet you can still easily determine the new position.
- system LIST
- system PROGRAM LIST
-
Does exactly the same thing as "exec LIST", except that a fork is
done first, and the parent process waits for the child process to
complete. Note that argument processing varies depending on the
number of arguments. If there is more than one argument in LIST,
or if LIST is an array with more than one value, starts the program
given by the first element of the list with arguments given by the
rest of the list. If there is only one scalar argument, the argument
is checked for shell metacharacters, and if there are any, the
entire argument is passed to the system's command shell for parsing
(this is "/bin/sh -c" on Unix platforms, but varies on other
platforms). If there are no shell metacharacters in the argument,
it is split into words and passed directly to "execvp", which is
more efficient.
Beginning with v5.6.0, Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the "autoflush()" method of "IO::Handle" on any open handles.
The return value is the exit status of the program as returned by the "wait" call. To get the actual exit value, shift right by eight (see below). See also ``exec''. This is not what you want to use to capture the output from a command, for that you should use merely backticks or "qx//", as described in ```STRING`'' in perlop. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason).
If you'd like to make "system" (and many other bits of Perl) die on error, have a look at the autodie pragma.
Like "exec", "system" allows you to lie to a program about its name if you use the "system PROGRAM LIST" syntax. Again, see ``exec''.
Since "SIGINT" and "SIGQUIT" are ignored during the execution of "system", if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value.
@args = ("command", "arg1", "arg2"); system(@args) == 0 or die "system @args failed: $?"
If you'd like to manually inspect "system"'s failure, you can check all possible failure modes by inspecting $? like this:
if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; }
Alternatively you might inspect the value of "${^CHILD_ERROR_NATIVE}" with the W*() calls of the POSIX extension.
When the arguments get executed via the system shell, results and return codes will be subject to its quirks and capabilities. See ```STRING`'' in perlop and ``exec'' for details.
- syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
- syswrite FILEHANDLE,SCALAR,LENGTH
- syswrite FILEHANDLE,SCALAR
-
Attempts to write LENGTH bytes of data from variable SCALAR to the
specified FILEHANDLE, using the system call write(2). If LENGTH is
not specified, writes whole SCALAR. It bypasses buffered IO, so
mixing this with reads (other than sysread()), "print", "write",
"seek", "tell", or "eof" may cause confusion because the perlio and
stdio layers usually buffers data. Returns the number of bytes
actually written, or "undef" if there was an error (in this case the
errno variable $! is also set). If the LENGTH is greater than the
available data in the SCALAR after the OFFSET, only as much data as is
available will be written.
An OFFSET may be specified to write the data from some part of the string other than the beginning. A negative OFFSET specifies writing that many characters counting backwards from the end of the string. In the case the SCALAR is empty you can use OFFSET but only zero offset.
Note that if the filehandle has been marked as ":utf8", Unicode characters are written instead of bytes (the LENGTH, OFFSET, and the return value of syswrite() are in UTF-8 encoded Unicode characters). The ":encoding(...)" layer implicitly introduces the ":utf8" layer. See ``binmode'', ``open'', and the "open" pragma, open.
- tell FILEHANDLE
- tell
-
Returns the current position in bytes for FILEHANDLE, or -1 on
error. FILEHANDLE may be an expression whose value gives the name of
the actual filehandle. If FILEHANDLE is omitted, assumes the file
last read.
Note the in bytes: even if the filehandle has been set to operate on characters (for example by using the ":encoding(utf8)" open layer), tell() will return byte offsets, not character offsets (because that would render seek() and tell() rather slow).
The return value of tell() for the standard streams like the STDIN depends on the operating system: it may return -1 or something else. tell() on pipes, fifos, and sockets usually returns -1.
There is no "systell" function. Use "sysseek(FH, 0, 1)" for that.
Do not use tell() (or other buffered I/O operations) on a file handle that has been manipulated by sysread(), syswrite() or sysseek(). Those functions ignore the buffering, while tell() does not.
- telldir DIRHANDLE
- Returns the current position of the "readdir" routines on DIRHANDLE. Value may be given to "seekdir" to access a particular location in a directory. "telldir" has the same caveats about possible directory compaction as the corresponding system library routine.
- tie VARIABLE,CLASSNAME,LIST
-
This function binds a variable to a package class that will provide the
implementation for the variable. VARIABLE is the name of the variable
to be enchanted. CLASSNAME is the name of a class implementing objects
of correct type. Any additional arguments are passed to the "new"
method of the class (meaning "TIESCALAR", "TIEHANDLE", "TIEARRAY",
or "TIEHASH"). Typically these are arguments such as might be passed
to the "dbm_open()" function of C. The object returned by the "new"
method is also returned by the "tie" function, which would be useful
if you want to access other methods in CLASSNAME.
Note that functions such as "keys" and "values" may return huge lists when used on large objects, like DBM files. You may prefer to use the "each" function to iterate over such. Example:
# print out history file offsets use NDBM_File; tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } untie(%HIST);
A class implementing a hash should have the following methods:
TIEHASH classname, LIST FETCH this, key STORE this, key, value DELETE this, key CLEAR this EXISTS this, key FIRSTKEY this NEXTKEY this, lastkey SCALAR this DESTROY this UNTIE this
A class implementing an ordinary array should have the following methods:
TIEARRAY classname, LIST FETCH this, key STORE this, key, value FETCHSIZE this STORESIZE this, count CLEAR this PUSH this, LIST POP this SHIFT this UNSHIFT this, LIST SPLICE this, offset, length, LIST EXTEND this, count DESTROY this UNTIE this
A class implementing a file handle should have the following methods:
TIEHANDLE classname, LIST READ this, scalar, length, offset READLINE this GETC this WRITE this, scalar, length, offset PRINT this, LIST PRINTF this, format, LIST BINMODE this EOF this FILENO this SEEK this, position, whence TELL this OPEN this, mode, LIST CLOSE this DESTROY this UNTIE this
A class implementing a scalar should have the following methods:
TIESCALAR classname, LIST FETCH this, STORE this, value DESTROY this UNTIE this
Not all methods indicated above need be implemented. See perltie, Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle.
Unlike "dbmopen", the "tie" function will not use or require a module for you---you need to do that explicitly yourself. See DB_File or the Config module for interesting "tie" implementations.
For further details see perltie, ``tied VARIABLE''.
- tied VARIABLE
- Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the "tie" call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package.
- time
-
Returns the number of non-leap seconds since whatever time the system
considers to be the epoch, suitable for feeding to "gmtime" and
"localtime". On most systems the epoch is 00:00:00 UTC, January 1, 1970;
a prominent exception being Mac OS Classic which uses 00:00:00, January 1,
1904 in the current local time zone for its epoch.
For measuring time in better granularity than one second, you may use either the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution), or if you have gettimeofday(2), you may be able to use the "syscall" interface of Perl. See perlfaq8 for details.
For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the DateTime module.
- times
-
Returns a four-element list giving the user and system times, in
seconds, for this process and the children of this process.
($user,$system,$cuser,$csystem) = times;
In scalar context, "times" returns $user.
Note that times for children are included only after they terminate.
- tr///
- The transliteration operator. Same as "y///". See ``Quote and Quote-like Operators'' in perlop.
- truncate FILEHANDLE,LENGTH
- truncate EXPR,LENGTH
-
Truncates the file opened on FILEHANDLE, or named by EXPR, to the
specified length. Produces a fatal error if truncate isn't implemented
on your system. Returns true if successful, the undefined value
otherwise.
The behavior is undefined if LENGTH is greater than the length of the file.
The position in the file of FILEHANDLE is left unchanged. You may want to call seek before writing to the file.
- uc EXPR
- uc
-
Returns an uppercased version of EXPR. This is the internal function
implementing the "\U" escape in double-quoted strings. Respects
current LC_CTYPE locale if "use locale" in force. See perllocale
and perlunicode for more details about locale and Unicode support.
It does not attempt to do titlecase mapping on initial letters. See
"ucfirst" for that.
If EXPR is omitted, uses $_.
- ucfirst EXPR
- ucfirst
-
Returns the value of EXPR with the first character in uppercase
(titlecase in Unicode). This is the internal function implementing
the "\u" escape in double-quoted strings. Respects current LC_CTYPE
locale if "use locale" in force. See perllocale and perlunicode
for more details about locale and Unicode support.
If EXPR is omitted, uses $_.
- umask EXPR
- umask
-
Sets the umask for the process to EXPR and returns the previous value.
If EXPR is omitted, merely returns the current umask.
The Unix permission "rwxr-x---" is represented as three sets of three bits, or three octal digits: 0750 (the leading 0 indicates octal and isn't one of the digits). The "umask" value is such a number representing disabled permissions bits. The permission (or ``mode'') values you pass "mkdir" or "sysopen" are modified by your umask, so even if you tell "sysopen" to create a file with permissions 0777, if your umask is 0022 then the file will actually be created with permissions 0755. If your "umask" were 0027 (group can't write; others can't read, write, or execute), then passing "sysopen" 0666 would create a file with mode 0640 ("0666 &~ 027" is 0640).
Here's some advice: supply a creation mode of 0666 for regular files (in "sysopen") and one of 0777 for directories (in "mkdir") and executable files. This gives users the freedom of choice: if they want protected files, they might choose process umasks of 022, 027, or even the particularly antisocial mask of 077. Programs should rarely if ever make policy decisions better left to the user. The exception to this is when writing files that should be kept private: mail files, web browser cookies, .rhosts files, and so on.
If umask(2) is not implemented on your system and you are trying to restrict access for yourself (i.e., (EXPR & 0700) > 0), produces a fatal error at run time. If umask(2) is not implemented and you are not trying to restrict access for yourself, returns "undef".
Remember that a umask is a number, usually given in octal; it is not a string of octal digits. See also ``oct'', if all you have is a string.
- undef EXPR
- undef
-
Undefines the value of EXPR, which must be an lvalue. Use only on a
scalar value, an array (using "@"), a hash (using "%"), a subroutine
(using "&"), or a typeglob (using "*"). (Saying "undef $hash{$key}"
will probably not do what you expect on most predefined variables or
DBM list values, so don't do that; see delete.) Always returns the
undefined value. You can omit the EXPR, in which case nothing is
undefined, but you still get an undefined value that you could, for
instance, return from a subroutine, assign to a variable or pass as a
parameter. Examples:
undef $foo; undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; undef @ary; undef %hash; undef &mysub; undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; select undef, undef, undef, 0.25; ($a, $b, undef, $c) = &foo; # Ignore third value returned
Note that this is a unary operator, not a list operator.
- unlink LIST
- unlink
-
Deletes a list of files. Returns the number of files successfully
deleted.
$cnt = unlink 'a', 'b', 'c'; unlink @goners; unlink <*.bak>;
Note: "unlink" will not attempt to delete directories unless you are superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using "unlink" on directories is not supported on many operating systems. Use "rmdir" instead.
If LIST is omitted, uses $_.
- unpack TEMPLATE,EXPR
- unpack TEMPLATE
-
"unpack" does the reverse of "pack": it takes a string
and expands it out into a list of values.
(In scalar context, it returns merely the first value produced.)
If EXPR is omitted, unpacks the $_ string.
The string is broken into chunks described by the TEMPLATE. Each chunk is converted separately to a value. Typically, either the string is a result of "pack", or the characters of the string represent a C structure of some kind.
The TEMPLATE has the same format as in the "pack" function. Here's a subroutine that does substring:
sub substr { my($what,$where,$howmuch) = @_; unpack("x$where a$howmuch", $what); }
and then there's
sub ordinal { unpack("W",$_[0]); } # same as ord()
In addition to fields allowed in pack(), you may prefix a field with a %<number> to indicate that you want a <number>-bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. Checksum is calculated by summing numeric values of expanded values (for string fields the sum of "ord($char)" is taken, for bit fields the sum of zeroes and ones).
For example, the following computes the same number as the System V sum program:
$checksum = do { local $/; # slurp! unpack("%32W*",<>) % 65535; };
The following efficiently counts the number of set bits in a bit vector:
$setbits = unpack("%32b*", $selectmask);
The "p" and "P" formats should be used with care. Since Perl has no way of checking whether the value passed to "unpack()" corresponds to a valid memory location, passing a pointer value that's not known to be valid is likely to have disastrous consequences.
If there are more pack codes or if the repeat count of a field or a group is larger than what the remainder of the input string allows, the result is not well defined: in some cases, the repeat count is decreased, or "unpack()" will produce null strings or zeroes, or terminate with an error. If the input string is longer than one described by the TEMPLATE, the rest is ignored.
See ``pack'' for more examples and notes.
- untie VARIABLE
- Breaks the binding between a variable and a package. (See "tie".) Has no effect if the variable is not tied.
- unshift ARRAY,LIST
-
Does the opposite of a "shift". Or the opposite of a "push",
depending on how you look at it. Prepends list to the front of the
array, and returns the new number of elements in the array.
unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;
Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use "reverse" to do the reverse.
- use Module VERSION LIST
- use Module VERSION
- use Module LIST
- use Module
- use VERSION
-
Imports some semantics into the current package from the named module,
generally by aliasing certain subroutine or variable names into your
package. It is exactly equivalent to
BEGIN { require Module; Module->import( LIST ); }
except that Module must be a bareword.
In the peculiar "use VERSION" form, VERSION may be either a numeric argument such as 5.006, which will be compared to $], or a literal of the form v5.6.1, which will be compared to $^V (aka $PERL_VERSION). A fatal error is produced if VERSION is greater than the version of the current Perl interpreter; Perl will not attempt to parse the rest of the file. Compare with ``require'', which can do a similar check at run time. Symmetrically, "no VERSION" allows you to specify that you want a version of perl older than the specified one.
Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl (that is, prior to 5.6.0) that do not support this syntax. The equivalent numeric version should be used instead.
use v5.6.1; # compile time version check use 5.6.1; # ditto use 5.006_001; # ditto; preferred for backwards compatibility
This is often useful if you need to check the current Perl version before "use"ing library modules that won't work with older versions of Perl. (We try not to do this more than we have to.)
Also, if the specified perl version is greater than or equal to 5.9.5, "use VERSION" will also load the "feature" pragma and enable all features available in the requested version. See feature.
The "BEGIN" forces the "require" and "import" to happen at compile time. The "require" makes sure the module is loaded into memory if it hasn't been yet. The "import" is not a builtin---it's just an ordinary static method call into the "Module" package to tell the module to import the list of features back into the current package. The module can implement its "import" method any way it likes, though most modules just choose to derive their "import" method via inheritance from the "Exporter" class that is defined in the "Exporter" module. See Exporter. If no "import" method can be found then the call is skipped, even if there is an AUTOLOAD method.
If you do not want to call the package's "import" method (for instance, to stop your namespace from being altered), explicitly supply the empty list:
use Module ();
That is exactly equivalent to
BEGIN { require Module }
If the VERSION argument is present between Module and LIST, then the "use" will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable $Module::VERSION.
Again, there is a distinction between omitting LIST ("import" called with no arguments) and an explicit empty LIST "()" ("import" not called). Note that there is no comma after VERSION!
Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. Currently implemented pragmas are:
use constant; use diagnostics; use integer; use sigtrap qw(SEGV BUS); use strict qw(subs vars refs); use subs qw(afunc blurfl); use warnings qw(all); use sort qw(stable _quicksort _mergesort);
Some of these pseudo-modules import semantics into the current block scope (like "strict" or "integer", unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file).
There's a corresponding "no" command that unimports meanings imported by "use", i.e., it calls "unimport Module LIST" instead of "import". It behaves exactly as "import" does with respect to VERSION, an omitted LIST, empty LIST, or no unimport method being found.
no integer; no strict 'refs'; no warnings;
See perlmodlib for a list of standard modules and pragmas. See perlrun for the "-M" and "-m" command-line options to perl that give "use" functionality from the command-line.
- utime LIST
-
Changes the access and modification times on each file of a list of
files. The first two elements of the list must be the NUMERICAL access
and modification times, in that order. Returns the number of files
successfully changed. The inode change time of each file is set
to the current time. For example, this code has the same effect as the
Unix touch(1) command when the files already exist and belong to
the user running the program:
#!/usr/bin/perl $atime = $mtime = time; utime $atime, $mtime, @ARGV;
Since perl 5.7.2, if the first two elements of the list are "undef", then the utime(2) function in the C library will be called with a null second argument. On most systems, this will set the file's access and modification times to the current time (i.e. equivalent to the example above) and will even work on other users' files where you have write permission:
utime undef, undef, @ARGV;
Under NFS this will use the time of the NFS server, not the time of the local machine. If there is a time synchronization problem, the NFS server and local machine will have different times. The Unix touch(1) command will in fact normally use this form instead of the one shown in the first example.
Note that only passing one of the first two elements as "undef" will be equivalent of passing it as 0 and will not have the same effect as described when they are both "undef". This case will also trigger an uninitialized warning.
On systems that support futimes, you might pass file handles among the files. On systems that don't support futimes, passing file handles produces a fatal error at run time. The file handles must be passed as globs or references to be recognized. Barewords are considered file names.
- values HASH
-
Returns a list consisting of all the values of the named hash.
(In a scalar context, returns the number of values.)
The values are returned in an apparently random order. The actual random order is subject to change in future versions of perl, but it is guaranteed to be the same order as either the "keys" or "each" function would produce on the same (unmodified) hash. Since Perl 5.8.1 the ordering is different even between different runs of Perl for security reasons (see ``Algorithmic Complexity Attacks'' in perlsec).
As a side effect, calling values() resets the HASH's internal iterator, see ``each''. (In particular, calling values() in void context resets the iterator with no other overhead.)
Note that the values are not copied, which means modifying them will modify the contents of the hash:
for (values %hash) { s/foo/bar/g } # modifies %hash values for (@hash{keys %hash}) { s/foo/bar/g } # same
See also "keys", "each", and "sort".
- vec EXPR,OFFSET,BITS
-
Treats the string in EXPR as a bit vector made up of elements of
width BITS, and returns the value of the element specified by OFFSET
as an unsigned integer. BITS therefore specifies the number of bits
that are reserved for each element in the bit vector. This must
be a power of two from 1 to 32 (or 64, if your platform supports
that).
If BITS is 8, ``elements'' coincide with bytes of the input string.
If BITS is 16 or more, bytes of the input string are grouped into chunks of size BITS/8, and each group is converted to a number as with pack()/unpack() with big-endian formats "n"/"N" (and analogously for BITS==64). See ``pack'' for details.
If bits is 4 or less, the string is broken into bytes, then the bits of each byte are broken into 8/BITS groups. Bits of a byte are numbered in a little-endian-ish way, as in 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80. For example, breaking the single input byte "chr(0x36)" into two groups gives a list "(0x6, 0x3)"; breaking it into 4 groups gives "(0x2, 0x1, 0x3, 0x0)".
"vec" may also be assigned to, in which case parentheses are needed to give the expression the correct precedence as in
vec($image, $max_x * $x + $y, 8) = 3;
If the selected element is outside the string, the value 0 is returned. If an element off the end of the string is written to, Perl will first extend the string with sufficiently many zero bytes. It is an error to try to write off the beginning of the string (i.e. negative OFFSET).
If the string happens to be encoded as UTF-8 internally (and thus has the UTF8 flag set), this is ignored by "vec", and it operates on the internal byte string, not the conceptual character string, even if you only have characters with values less than 256.
Strings created with "vec" can also be manipulated with the logical operators "|", "&", "^", and "~". These operators will assume a bit vector operation is desired when both operands are strings. See ``Bitwise String Operators'' in perlop.
The following code will build up an ASCII string saying 'PerlPerlPerl'. The comments show the string after each step. Note that this code works in the same way on big-endian or little-endian machines.