For each such format, "pack" generates 4 bits of result. With 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 "\000" and "\001". 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". Use only these specific hex characters with this format.
Starting from the beginning of the template to "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; 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, "extra" nybbles are ignored during unpacking.
If the input string is longer than needed, extra characters are ignored.
A "*" for the repeat count uses all characters of the input field. For "unpack", nybbles are converted to a string of hexadecimal digits.
If your system has a strange pointer size--meaning 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 raises an exception.
For "pack", you write length-item"/"sequence-item, and the length-item describes how the length value is packed. Formats 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", sequence-item may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for 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 sequence-item refers to a string type ("A", "a", or "Z"), the length-item is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example:
This code: gives this result: unpack("W/a", "\004Gurusamy") ("Guru") unpack("a3/A A*", "007 Bond J ") (" Bond", "J") unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") pack("n/a* w/a","hello,","world") "\000\006hello,\005world" pack("a/W2", ord("a") .. ord("z")) "2ab"
The length-item is not returned explicitly from "unpack".
Supplying a count to the length-item format letter is only useful with "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.
printf "format s is %d, s! is %d\n", length pack("s"), length pack("s!"); printf "format l is %d, l! is %d\n", length pack("l"), length pack("l!");
"i!" and "I!" are also allowed, but only for completeness' sake: 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 from the command line:
$ perl -V:{short,int,long{,long}}size shortsize='2'; intsize='4'; longsize='4'; longlongsize='8';
or programmatically via the "Config" module:
use Config; print $Config{shortsize}, "\n"; print $Config{intsize}, "\n"; print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n";
$Config{longlongsize} is undefined on systems without long long support.
0x12 0x34 0x56 0x78 # big-endian 0x78 0x56 0x34 0x12 # little-endian
Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) them in little-endian mode, but SGI/Cray uses them in big-endian mode.
The names big-endian and little-endian are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, Gulliver's Travels. This entered computer lingo via the paper "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.
Some systems may have even weirder byte orders such as
0x56 0x78 0x12 0x34 0x34 0x12 0x78 0x56
These are called mid-endian, middle-endian, mixed-endian, or just weird.
You can determine your system endianness with this incantation:
printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);
The byteorder on the platform where Perl was built is also available via Config:
use Config; print "$Config{byteorder}\n";
or from the command line:
$ perl -V:byteorder
Byteorders "1234" and "12345678" are little-endian; "4321" and "87654321" are big-endian. Systems with multiarchitecture binaries will have "ffff", signifying that static information doesn't work, one must use runtime probing.
For portably packed integers, either use the formats "n", "N", "v", and "V" or else use the ">" and "<" modifiers described immediately below. See also perlport.
Portability-wise the best option is probably to keep to the IEEE 754 64-bit doubles, and of agreed-upon endianness. Another possibility is the "%a") format of "printf".
Here are some concerns to keep in mind when using an endianness modifier:
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.
Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so "unpack("f", pack("f", $foo)") will not in general equal $foo.
Using "C0" to get Unicode characters while using "U0" to get non-Unicode bytes is not necessarily obvious. Probably only the first of these is what you want:
$ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 03B1.03C9 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' C3.8E.C2.B1.C3.8F.C2.89
Those examples also illustrate that you should not try to use "pack"/"unpack" as a substitute for the Encode module.
pack("@1A((@2A)@3A)", qw[X Y Z])
is the string "\0X\0\0YZ".
struct { char c; /* one signed, 8-bit character */ double d; char cc[2]; }
one may need to use the template "c x![d] d c[2]". This assumes that doubles must be aligned to the size of double.
For alignment commands, a "count" of 0 is equivalent to a "count" of 1; both are no-ops.
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 examples above featuring "W" and "c" are true # only on ASCII and ASCII-derived systems such as ISO Latin 1 # and UTF-8. On EBCDIC systems, the first example would be # $foo = pack("WWWW",193,194,195,196); $foo = pack("s2",1,2); # "\001\000\002\000" on little-endian # "\000\001\000\002" 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".
A package statement affects dynamic variables only, including those you've used "local" on, but not lexically-scoped variables, which are created with "my", "state", or "our". Typically it would be the first declaration in a file included by "require" or "use". You can switch into a package in more than one place, since this only determines which default symbol table the compiler uses for the rest of that block. You can refer to identifiers in other packages than the current one by prefixing the identifier with the package name and a double colon, as in $SomePack::var or "ThatPack::INPUT_HANDLE". If package name is omitted, the "main" package as assumed. That is, $::sail is equivalent to $main::sail (as well as to "$main'sail", still seen in ancient code, mostly from Perl 4).
If VERSION is provided, "package" sets the $VERSION variable in the given namespace to a version object with the VERSION provided. VERSION must be a "strict" style version number as defined by the version module: a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. You should set $VERSION only once per package.
See "Packages" in perlmod for more information about packages, modules, and classes. See perlsub for other scoping issues.
Returns true on success.
See IPC::Open2, IPC::Open3, and "Bidirectional Communication with Another Process" in perlipc for examples of such things.
On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose "fileno"s are higher than the current value of $^F (by default 2 for "STDERR"). See "$^F" in perlvar.
Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the @ARGV array in the main program, but the @_ array in subroutines, just like "shift".
Starting with Perl 5.14, an experimental feature allowed "pop" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
"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. Both of these effects take place for the next match, so you can't affect the position with "pos" during the current match, such as in "(?{pos() = 5})" or "s//pos() = 5/e".
Setting "pos" also resets the matched with zero-length flag, described under "Repeated Patterns Matching a Zero-length Substring" in perlre.
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.
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, including any subroutines whose return lists you pass to "print". 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; put parentheses around all arguments (or interpose a "+", but that doesn't look as good).
If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted:
print { $files[$i] } "stuff\n"; print { $OK ? *STDOUT : *STDERR } "stuff\n";
Printing to a closed pipe or socket will generate a SIGPIPE signal. See perlipc for more on signal handling.
For historical reasons, if you omit the list, $_ is used as the format; to use FILEHANDLE without a list, you must use a bareword filehandle like "FH", not an indirect one like $fh. However, this will rarely do what you want; if $_ contains formatting codes, they will be replaced with the empty string and a warning will be emitted if warnings are enabled. Just use "print" if you want to print the contents of $_.
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.
If FUNCTION is a string starting with "CORE::", the rest is taken as a name for a Perl builtin. If the builtin's 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.
for my $value (LIST) { $ARRAY[++$#ARRAY] = $value; }
but is more efficient. Returns the number of elements in the array following the completed "push".
Starting with Perl 5.14, an experimental feature allowed "push" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
If EXPR is omitted, uses $_.
quotemeta (and "\Q" ... "\E") are useful when interpolating strings into regular expressions, because by default an interpolated variable will be considered a mini-regular expression.
On the other hand:
my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; $sentence =~ s{\Q$substring\E}{big bad wolf};
Or:
my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; my $quoted_substring = quotemeta($substring); $sentence =~ s{$quoted_substring}{big bad wolf};
Will both leave the sentence as is. Normally, when accepting literal string input from the user, "quotemeta" or "\Q" must be used.
In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded strings, but not quoted in UTF-8 strings.
Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for quoting non-ASCII characters; the quoting of ASCII characters is unchanged.
Also unchanged is the quoting of non-UTF-8 strings when outside the scope of a "use feature 'unicode_strings'", which is to quote all characters in the upper Latin1 range. This provides complete backwards compatibility for old programs which do not use Unicode. (Note that "unicode_strings" is automatically enabled within the scope of a "use v5.12" or greater.)
Within the scope of "use locale", all non-ASCII Latin1 code points are quoted whether the string is encoded as UTF-8 or not. As mentioned above, locale does not affect the quoting of ASCII-range characters. This protects against those locales where characters such as "|" are considered to be word characters.
Otherwise, Perl quotes non-ASCII characters using an adaptation from Unicode (see <http://www.unicode.org/reports/tr31/>). The only code points that are quoted are those that have any of the Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, Default_Ignorable_Code_Point, or General_Category=Control.
Of these properties, the two important ones are Pattern_Syntax and Pattern_White_Space. They have been set up by Unicode for exactly this purpose of deciding which characters in a regular expression pattern should be quoted. No character that can be in an identifier has these properties.
Perl promises, that if we ever add regular expression pattern metacharacters to the dozen already defined ("\ | ( ) [ { ^ $ * + ? ."), that we will only use ones that have the Pattern_Syntax property. Perl also promises, that if we ever add characters that are considered to be white space in regular expressions (currently mostly affected by "/x"), they will all have the Pattern_White_Space property.
Unicode promises that the set of code points that have these two properties will never change, so something that is not quoted in v5.16 will never need to be quoted in any future Perl release. (Not all the code points that match Pattern_Syntax have actually had characters assigned to them; so there is room to grow, but they are quoted whether assigned or not. Perl, of course, would never use an unassigned code point as an actual metacharacter.)
Quoting characters that have the other 3 properties is done to enhance the readability of the regular expression and not because they actually need to be quoted for regular expression purposes (characters with the White_Space property are likely to be indistinguishable on the page or screen from those with the Pattern_White_Space property; and the other two properties contain non-printing characters).
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.)
"rand" is not cryptographically secure. You should not rely on it in security-sensitive situations. As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: Data::Entropy, Crypt::Random, Math::Random::Secure, and Math::TrulyRandom.
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 implemented in terms of either Perl's or your system's native fread(3) library function. 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), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the ":encoding" layer: in that case pretty much any characters can be read.
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: $!"; my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh;
As of Perl 5.12 you can use a bare "readdir" in a "while" loop, which will set $_ on every iteration. If either a "readdir" expression or an explicit assignment of a "readdir" expression to a scalar is used as a "while"/"for" condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.
opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!"; while (readdir $dh) { print "$some_dir/$_\n"; } closedir $dh;
To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious failures, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:
use 5.012; # so readdir assigns to $_ in a lone while test
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.
my $line = <STDIN>; my $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 dies if the result is not defined.
while ( ! eof($fh) ) { defined( $_ = readline $fh ) or die "readline failed: $!"; ... }
Note that you have can't handle "readline" errors that way with the "ARGV" filehandle. In that case, you have to open each element of @ARGV yourself since "eof" handles "ARGV" differently.
foreach my $arg (@ARGV) { open(my $fh, $arg) or warn "Can't open $arg: $!"; while ( ! eof($fh) ) { defined( $_ = readline $fh ) or die "readline failed for $arg: $!"; ... } }
Like the "<EXPR>" operator, if a "readline" expression is used as the condition of a "while" or "for" loop, then it will be implicitly assigned to $_. If either a "readline" expression or an explicit assignment of a "readline" expression to a scalar is used as a "while"/"for" condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.
Portability issues: "readlink" in perlport.
Note that if the socket has been marked as ":utf8", "recv" will throw an exception. The ":encoding(...)" layer implicitly introduces the ":utf8" layer. See "binmode".
# a simpleminded Pascal comment stripper # (warning: assumes no { or } in strings) LINE: while (<STDIN>) { while (s|({.*}.*){.*}|$1 |) {} s|{.*}| |; if (s|{.*| |) { my $front = $_; while (<STDIN>) { if (/}/) { # end of comment? s|^|$front\{|; redo LINE; } } } print; }
"redo" cannot return a value from a block that typically returns a value, such as "eval {}", "sub {}", or "do {}". It will perform its flow control behavior, which precludes any return value. It 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.
Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so "redo ("foo")."bar"" will cause "bar" to be part of the argument to "redo".
If the operand is not a reference, then the empty string will be returned. An empty string will only be returned in this situation. "ref" is often useful to just test whether a value is a reference, which can be done by comparing the result to the empty string. It is a common mistake to use the result of "ref" directly as a truth value: this goes wrong because 0 (which is false) can be returned for a reference.
If the operand is a reference to a blessed object, then the name of the class into which the referent is blessed will be returned. "ref" doesn't care what the physical type of the referent is; blessing takes precedence over such concerns. Beware that exact comparison of "ref" results against a class name doesn't perform a class membership test: a class's members also include objects blessed into subclasses, for which "ref" will return the name of the subclass. Also beware that class names can clash with the built-in type names (described below).
If the operand is a reference to an unblessed object, then the return value indicates the type of object. If the unblessed referent is not a scalar, then the return value will be one of the strings "ARRAY", "HASH", "CODE", "FORMAT", or "IO", indicating only which kind of object it is. If the unblessed referent is a scalar, then the return value will be one of the strings "SCALAR", "VSTRING", "REF", "GLOB", "LVALUE", or "REGEXP", depending on the kind of value the scalar currently has. But note that "qr//" scalars are created already blessed, so "ref qr/.../" will likely return "Regexp". Beware that these built-in type names can also be used as class names, so "ref" returning one of these names doesn't unambiguously indicate that the referent is of the kind to which the name refers.
The ambiguity between built-in type names and class names significantly limits the utility of "ref". For unambiguous information, use "Scalar::Util::blessed()" for information about blessing, and "Scalar::Util::reftype()" for information about physical types. Use the "isa" method for class membership tests, though one must be sure of blessedness before attempting a method call.
See also perlref and perlobj.
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.
Portability issues: "rename" in perlport.
VERSION may be either a literal such as v5.24.1, which will be compared to $^V (or $PERL_VERSION in English), or a numeric argument of the form 5.024001, which will be compared to $]. An exception is raised 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 numeric argument of the form 5.024001 should generally be avoided as older less readable syntax compared to v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric form was the only supported syntax, which is why you might see it in older code.
require v5.24.1; # run time version check require 5.24.1; # ditto require 5.024_001; # ditto; older syntax compatible with perl 5.6
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. If it were implemented in pure Perl, it would have semantics similar to the following:
use Carp 'croak'; use version; sub require { my ($filename) = @_; if ( my $version = eval { version->parse($filename) } ) { if ( $version > $^V ) { my $vn = $version->normal; croak "Perl $vn required--this is only $^V, stopped"; } return 1; } if (exists $INC{$filename}) { return 1 if $INC{$filename}; croak "Compilation failed in require"; } foreach $prefix (@INC) { if (ref($prefix)) { #... do other stuff - see text below .... } # (see text below about possible appending of .pmc # suffix to $filename) my $realfilename = "$prefix/$filename"; next if ! -e $realfilename || -d _ || -b _; $INC{$filename} = $realfilename; my $result = do($realfilename); # but run in caller's namespace if (!defined $result) { $INC{$filename} = undef; croak $@ ? "$@Compilation failed in require" : "Can't locate $filename: $!\n"; } if (!$result) { delete $INC{$filename}; croak "$filename did not return true value"; } $! = 0; return $result; } croak "Can't locate $filename in \@INC ..."; }
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, "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, however it will autovivify the stash for the required module.
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, and it will autovivify the "Foo::Bar::" stash at compile time.
But if you try this:
my $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";
or you could do
require "Foo/Bar.pm";
Neither of these forms will autovivify any stashes at compile time and only have run time effects.
Now that you understand how "require" looks for files with 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. This applies to both the explicit "require "Foo/Bar.pm";" form and the "require Foo::Bar;" form.
You can also insert hooks into the import facility by putting Perl code directly 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 a reference to itself, and the second the name of the file to be included (e.g., Foo/Bar.pm). The subroutine should return either nothing or else a list of up to four values in the following order:
If an empty list, "undef", or nothing that matches the first 3 values above is returned, then "require" looks at the remaining elements of @INC. Note that this filehandle must be a real filehandle (strictly a typeglob or reference to a typeglob, whether blessed or unblessed); tied filehandles will be ignored and 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 lets you indirectly pass 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 (undef, @parameters) = @$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(...);
These hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See "%INC" in perlvar.

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".
(In the absence of an explicit "return", a subroutine, "eval", or "do FILE" automatically returns the value of the last expression evaluated.)
Unlike most named operators, this is also exempt from the looks-like-a-function rule, so "return ("foo")."bar"" will cause "bar" to be part of the argument to "return".
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
Note that reversing an array to itself (as in "@a = reverse @a") will preserve non-existent elements whenever possible; i.e., for non-magical arrays or for tied arrays with "EXISTS" and "DELETE" methods.
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.
my %by_name = reverse %by_address; # Invert the hash
Portability issues: "rewinddir" in perlport.
To remove a directory tree recursively ("rm -rf" on Unix) look at the "rmtree" function of the File::Path module.
"say" is available only if the "say" feature is enabled or if it is prefixed with "CORE::". The "say" feature is enabled automatically with a "use v5.10" (or higher) declaration in the current scope.
my @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 a unary operator, if you accidentally use a parenthesized list for the EXPR, 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, and perldata for details on evaluating a hash in scalar contex.
Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the ":encoding(UTF-8)" I/O layer), the "seek", "tell", and "sysseek" family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.
If you want to position the file for "sysread" or "syswrite", don't use "seek", because buffering makes its effect on the file's read-write 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($fh, 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 (probably) have to stick in a dummy "seek" to reset things. The "seek" doesn't change the position, but it does clear the end-of-file condition on the handle, so that the next "readline FILE" makes Perl try again to read something. (We hope.)
If that doesn't work (some I/O implementations are particularly cantankerous), you might need something like this:
for (;;) { for ($curpos = tell($fh); $_ = readline($fh); $curpos = tell($fh)) { # search for some stuff and put it into files } sleep($for_a_while); seek($fh, $curpos, 0); }
For example, 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:
my $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:
STDERR->autoflush(1);
(Prior to Perl version 5.14, you have to "use IO::Handle;" explicitly first.)
Portability issues: "select" in perlport.
my $rin = my $win = my $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 may wish to write a subroutine like this:
sub fhbits { my @fhlist = @_; my $bits = ""; for my $fh (@fhlist) { vec($bits, fileno($fh), 1) = 1; } return $bits; } my $rin = fhbits(\*STDIN, $tty, $mysock);
The usual idiom is:
my ($nfound, $timeleft) = select(my $rout = $rin, my $wout = $win, my $eout = $ein, $timeout);
or to block until something becomes ready just do this
my $nfound = select(my $rout = $rin, my $wout = $win, my $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 just like select(2): it returns "-1" and sets $!.
On some Unixes, select(2) may report a socket file descriptor as "ready for reading" even when no data is available, and thus any subsequent "read" would block. This can be avoided if you always use "O_NONBLOCK" on the socket. See select(2) and fcntl(2) for further details.
The standard "IO::Select" module provides a user-friendlier interface to "select", mostly because it does all the bit-mask work for you.
WARNING: One should not attempt to mix buffered I/O (like "read" or "readline") with "select", except as permitted by POSIX, and even then only on POSIX systems. You have to use "sysread" instead.
Portability issues: "select" in perlport.
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 and the documentation for "IPC::SysV" and "IPC::Semaphore".
Portability issues: "semctl" in perlport.
Portability issues: "semget" in perlport.
my $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 and the documentation for "IPC::SysV" and "IPC::Semaphore".
Portability issues: "semop" in perlport.
Note that if the socket has been marked as ":utf8", "send" will throw an exception. The ":encoding(...)" layer implicitly introduces the ":utf8" layer. See "binmode".
Portability issues: "setpgrp" in perlport.
"WHICH" can be any of "PRIO_PROCESS", "PRIO_PGRP" or "PRIO_USER" imported from "RESOURCE CONSTANTS" in POSIX.
Portability issues: "setpriority" in perlport.
An example disabling Nagle's algorithm on a socket:
use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);
Portability issues: "setsockopt" in perlport.
Starting with Perl 5.14, an experimental feature allowed "shift" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
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.
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: "undef" for error; "0 but true" for zero; and the actual return value otherwise. See also "SysV IPC" in perlipc and the documentation for "IPC::SysV".
Portability issues: "shmctl" in perlport.
Portability issues: "shmget" in perlport.
Portability issues: "shmread" in perlport and "shmwrite" in perlport.
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; on error, returns "undef" if the first argument is not a valid filehandle, or returns 0 and sets $! for any other failure.
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])) }
May be interrupted if the process receives a signal such as "SIGALRM".
eval { local $SIG{ALRM} = 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.
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.
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 define "pipe" in terms of "socketpair", in which a call to "pipe($rdr, $wtr)" is essentially:
use Socket; socketpair(my $rdr, my $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.
Portability issues: "socketpair" in perlport.
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).
If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set.
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" (but not "use locale ':not_characters'") 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.
Historically Perl has varied in whether sorting is stable by default. If stability matters, it can be controlled explicitly by using the sort pragma.
Examples:
# sort lexically my @articles = sort @files; # same thing, but with explicit sort routine my @articles = sort {$a cmp $b} @files; # now case-insensitively my @articles = sort {fc($a) cmp fc($b)} @files; # same thing in reversed order my @articles = sort {$b cmp $a} @files; # sort numerically ascending my @articles = sort {$a <=> $b} @files; # sort numerically descending my @articles = sort {$b <=> $a} @files; # this sorts the %age hash by value instead of key # using an in-line function my @eldest = sort { $age{$b} <=> $age{$a} } keys %age; # sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming numeric } my @sortedclass = sort byage @class; sub backwards { $b cmp $a } my @harry = qw(dog cat x Cain Abel); my @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 my @new = sort { ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] || fc($a) cmp fc($b) } @old; # same thing, but much more efficiently; # we'll build auxiliary indices instead # for speed my (@nums, @caps); for (@old) { push @nums, ( /=(\d+)/ ? $1 : undef ); push @caps, fc($_); } my @new = @old[ sort { $nums[$b] <=> $nums[$a] || $caps[$a] cmp $caps[$b] } 0..$#old ]; # same thing, but without any temps my @new = map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [$_, /=(\d+)/, fc($_)] } @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; my @new = sort Other::backwards @old; # guarantee stability use sort 'stable'; my @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:
my @contact = sort { $a cmp $b } find_records @key; my @contact = sort +find_records(@key); my @contact = sort &find_records(@key); my @contact = sort(find_records(@key));
If instead you want to sort the array @key with the comparison routine "find_records()" then you can use:
my @contact = sort { find_records() } @key; my @contact = sort find_records(@key); my @contact = sort(find_records @key); my @contact = sort(find_records (@key));
$a and $b are set as package globals in the package the sort() is called from. That means $main::a and $main::b (or $::a and $::b) in the "main" package, $FooPack::a and $FooPack::b in the "FooPack" package, etc. If the sort block is in scope of a "my" or "state" declaration of $a and/or $b, you must spell out the full name of the variables in the sort block :
package main; my $a = "C"; # DANGER, Will Robinson, DANGER !!! print sort { $a cmp $b } qw(A C E G B D F H); # WRONG sub badlexi { $a cmp $b } print sort badlexi qw(A C E G B D F H); # WRONG # the above prints BACFEDGH or some other incorrect ordering print sort { $::a cmp $::b } qw(A C E G B D F H); # OK print sort { our $a cmp our $b } qw(A C E G B D F H); # also OK print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); # also OK sub lexi { our $a cmp our $b } print sort lexi qw(A C E G B D F H); # also OK # the above print ABCDEFGH
With proper care you may mix package and my (or state) $a and/or $b:
my $a = { tiny => -2, small => -1, normal => 0, big => 1, huge => 2 }; say sort { $a->{our $a} <=> $a->{our $b} } qw{ huge normal tiny small big}; # prints tinysmallnormalbighuge
$a and $b are implicitly local to the sort() execution and regain their former values upon completing the sort.
Sort subroutines written using $a and $b are bound to their calling package. It is possible, but of limited interest, to define them in a different package, since the subroutine must still refer to the calling package's $a and $b :
package Foo; sub lexi { $Bar::a cmp $Bar::b } package Bar; ... sort Foo::lexi ...
Use the prototyped versions (see above) for a more generic alternative.
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), be careful when sorting with a comparison function like "$a <=> $b" any lists that might contain a "NaN". The following example takes advantage that "NaN != NaN" to eliminate any "NaN"s from the input list.
my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
The following equivalences hold (assuming "$#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)
"splice" can be used, for example, to implement n-ary queue processing:
sub nary_print { my $n = shift; while (my @next_n = splice @_, 0, $n) { say join q{ -- }, @next_n; } } nary_print(3, qw(a b c d e f g h)); # prints: # a -- b -- c # d -- e -- f # g -- h
Starting with Perl 5.14, an experimental feature allowed "splice" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
If only PATTERN is given, EXPR defaults to $_.
Anything in EXPR that matches PATTERN is taken to be a separator that separates the EXPR into substrings (called "fields") that do not include the separator. Note that a separator may be longer than one character or even have no characters at all (the empty string, which is a zero-width match).
The PATTERN need not be constant; an expression may be used to specify a pattern that varies at runtime.
If PATTERN matches the empty string, the EXPR is split at the match position (between characters). As an example, the following:
print join(':', split(/b/, 'abc')), "\n";
uses the "b" in 'abc' as a separator to produce the output "a:c". However, this:
print join(':', split(//, 'abc')), "\n";
uses empty string matches as separators to produce the output "a:b:c"; thus, the empty string may be used to split EXPR into a list of its component characters.
As a special case for "split", the empty pattern given in match operator syntax ("//") specifically matches the empty string, which is contrary to its usual interpretation as the last successful match.
If PATTERN is "/^/", then it is treated as if it used the multiline modifier ("/^/m"), since it isn't much use otherwise.
"/m" and any of the other pattern modifiers valid for "qr" (summarized in "qr/STRING/msixpodualn" in perlop) may be specified explicitly.
As another special case, "split" emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a string composed of a single space character (such as ' ' or "\x20", but not e.g. "/ /"). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were "/\s+/"; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern "/ /" instead of the string " ", thereby allowing only a single space character to be a separator. In earlier Perls this special case was restricted to the use of a plain " " as the pattern argument to split; in Perl 5.18.0 and later this special case is triggered by any expression which evaluates to the simple string " ".
As of Perl 5.28, this special-cased whitespace splitting works as expected in the scope of "use feature 'unicode_strings". In previous versions, and outside the scope of that feature, it exhibits "The "Unicode Bug"" in perlunicode: characters that are whitespace according to Unicode rules but not according to ASCII rules can be treated as part of fields rather than as field separators, depending on the string's internal encoding.
If omitted, PATTERN defaults to a single space, " ", triggering the previously described awk emulation.
If LIMIT is specified and positive, it represents the maximum number of fields into which the EXPR may be split; in other words, LIMIT is one greater than the maximum number of times EXPR may be split. Thus, the LIMIT value 1 means that EXPR may be split a maximum of zero times, producing a maximum of one field (namely, the entire value of EXPR). For instance:
print join(':', split(//, 'abc', 1)), "\n";
produces the output "abc", and this:
print join(':', split(//, 'abc', 2)), "\n";
produces the output "a:bc", and each of these:
print join(':', split(//, 'abc', 3)), "\n"; print join(':', split(//, 'abc', 4)), "\n";
produces the output "a:b:c".
If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.
If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved); if all fields are empty, then all fields are considered to be trailing (and are thus stripped in this case). Thus, the following:
print join(':', split(/,/, 'a,b,c,,,')), "\n";
produces the output "a:b:c", but the following:
print join(':', split(/,/, 'a,b,c,,,', -1)), "\n";
produces the output "a:b:c:::".
In time-critical applications, it is worthwhile to avoid splitting into more fields than necessary. Thus, when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list; for the following, LIMIT is implicitly 3:
my ($login, $passwd) = split(/:/);
Note that splitting an EXPR that evaluates to the empty string always produces zero fields, regardless of the LIMIT specified.
An empty leading field is produced when there is a positive-width match at the beginning of EXPR. For instance:
print join(':', split(/ /, ' abc')), "\n";
produces the output ":abc". However, a zero-width match at the beginning of EXPR never produces an empty field, so that:
print join(':', split(//, ' abc'));
produces the output " :a:b:c" (rather than ": :a:b:c").
An empty trailing field, on the other hand, is produced when there is a match at the end of EXPR, regardless of the length of the match (of course, unless a non-zero LIMIT is given explicitly, such fields are removed, as in the last example). Thus:
print join(':', split(//, ' abc', -1)), "\n";
produces the output " :a:b:c:".
If the PATTERN contains capturing groups, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per backreferences); if any group does not match, then it captures the "undef" value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does not count towards the LIMIT. Consider the following expressions evaluated in list context (each returned list is provided in the associated comment):
split(/-|,/, "1-10,20", 3) # ('1', '10', '20') split(/(-|,)/, "1-10,20", 3) # ('1', '-', '10', ',', '20') split(/-|(,)/, "1-10,20", 3) # ('1', undef, '10', ',', '20') split(/(-)|,/, "1-10,20", 3) # ('1', '-', '10', undef, '20') split(/(-)|(,)/, "1-10,20", 3) # ('1', '-', undef, '10', undef, ',', '20')
For example:
# Format number with up to 8 leading zeroes my $result = sprintf("%08d", $number); # Round number to 3 digits after decimal point my $rounded = sprintf("%.3f", $number);
Perl does its own "sprintf" formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable 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 argument in the parameter list %a hexadecimal floating point %A like %a, but using upper-case letters
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". Similarly for %a and %A: the exponent or the hexadecimal digits may float: especially the "long doubles" Perl configuration option may cause surprises.
Between the "%" and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are:
printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1"
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>', 0; # prints "< 0>" printf '<% d>', -12; # prints "<-12>" printf '<%+d>', 12; # prints "<+12>" printf '<%+d>', 0; # prints "<+0>" 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, the space is ignored.
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>"
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 something like "*2$v"; for example:
printf '%*4$vX %*4$vX %*4$vX', # 3 IPv6 addresses @addr[1..3], ":";
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.
# 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 significant digits to show; for example:
# 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>" printf '<%.1g>', 0.0111; # prints "<0.01>" printf '<%.2g>', 0.0111; # prints "<0.011>" printf '<%.3g>', 0.0111; # prints "<0.0111>"
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 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 ".*", or from a specified argument (e.g., with ".*2$"):
printf '<%.6x>', 1; # prints "<000001>" printf '<%.*x>', 6, 1; # prints "<000001>" printf '<%.*2$x>', 1, 6; # prints "<000001>" printf '<%6.*2$x>', 1, 4; # prints "< 0001>"
If a precision obtained through "*" is negative, it counts as having no precision at all.
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>"
hh interpret integer as C type "char" or "unsigned char" on Perl 5.14 or later h interpret integer as C type "short" or "unsigned short" j interpret integer as C type "intmax_t" on Perl 5.14 or later; and prior to Perl 5.30, only with a C99 compiler (unportable) l interpret integer as C type "long" or "unsigned long" q, L, or ll interpret integer as C type "long long", "unsigned long long", or "quad" (typically 64-bit integers) t interpret integer as C type "ptrdiff_t" on Perl 5.14 or later z interpret integer as C type "size_t" on Perl 5.14 or later
As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the "printf" warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this:
use warnings FATAL => "printf";
If you would like to know about a version dependency before you start running the program, put something like this at its top:
use 5.014; # for hh/j/t/z/ printf modifiers
You can find out whether your Perl supports quads via Config:
use Config; if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) { print "Nice 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; print "long doubles\n" if $Config{d_longdbl} eq "define";
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; if ($Config{uselongdouble} eq "define") { print "long doubles by default\n"; }
It can also be 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 is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default.
So:
printf "<%*.*s>", $a, $b, $c;
uses $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 precision, and $b as the value to format.
Here are some more examples; be aware that when using an explicit index, the "$" may need escaping:
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" printf "%*1\$.*f\n", 4, 5, 10; # will print "5.0000\n"
If "use locale" (including "use locale ':not_characters'") 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.
use Math::Complex; print sqrt(-4); # prints 2i
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. When called with a parameter, "srand" uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will work only on Perls of a recent vintage:
use 5.014; # so srand returns the seed
If "srand" is not called explicitly, it is called implicitly without a parameter at the first use of the "rand" operator. However, there are a few situations where programs are likely to want to call "srand". One is for generating predictable results, generally for testing or debugging. There, you use "srand($seed)", with the same $seed each time. Another case is that you may want to call "srand" after a "fork" to avoid child processes sharing the same seed value as the parent (and consequently each other).
Do not call "srand()" (i.e., without an argument) more than once per process. 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.
A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the same results.
"rand" is not cryptographically secure. You should not rely on it in security-sensitive situations. As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: Data::Entropy, Crypt::Random, Math::Random::Secure, and Math::TrulyRandom.
my ($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 I/O size in bytes for interacting with the file (may vary from file to file) 12 blocks actual number of system-specific blocks allocated on disk (often, but not always, 512 bytes each)
(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.)
On some platforms inode numbers are of a type larger than perl knows how to handle as integer numerical values. If necessary, an inode number will be returned as a decimal string in order to preserve the entire value. If used in a numeric context, this will be converted to a floating-point numerical value, with rounding, a fate that is best avoided. Therefore, you should prefer to compare inode numbers using "eq" rather than "==". "eq" will work fine on inode numbers that are represented numerically, as well as those represented as strings.
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.
my $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; my $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'; my $mode = (stat($filename))[2]; my $user_rwx = ($mode & S_IRWXU) >> 6; my $group_read = ($mode & S_IRGRP) >> 3; my $other_execute = $mode & S_IXOTH; printf "Permissions are %04o\n", S_IMODE($mode), "\n"; my $is_setuid = $mode & S_ISUID; my $is_directory = S_ISDIR($mode);
You could write the last two using the "-u" and "-d" operators. 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 all are necessarily 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, and 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 (for example) 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.
Portability issues: "stat" in perlport.
If more than one variable is listed, the list must be placed in parentheses. With a parenthesised list, "undef" can be used as a dummy placeholder. However, since initialization of state variables in such lists is currently not possible this would serve no purpose.
"state" is available only if the "state" feature is enabled or if it is prefixed with "CORE::". The "state" feature is enabled automatically with a "use v5.10" (or higher) declaration in the current scope.
Prior to Perl version 5.16, it would create an inverted index of all characters that occurred in the given SCALAR (or $_ if unspecified). When matching a pattern, the rarest character from the pattern would be looked up in this index. Rarity was based on some static frequency tables constructed from some C programs and English text.
See perlsub and perlref for details about subroutines and references; see attributes and Attribute::Handlers for more information about attributes.
The behaviour of "__SUB__" within a regex code block (such as "/(?{...})/") is subject to change.
This token is only available under "use v5.16" or the "current_sub" feature. See feature.
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 raises an exception. 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'; # raises an exception
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 three-argument 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:
my $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 }
With negative offsets, it remembers its position from the end of the string when the target string is modified:
my $x = '1234'; for (substr($x, -3, 2)) { $_ = 'a'; print $x,"\n"; # prints 1a4, as above $x = 'abcdefg'; print $_,"\n"; # prints f }
Prior to Perl version 5.10, the result of using an lvalue multiple times was unspecified. Prior to 5.16, the result with negative offsets was unspecified.
my $symlink_exists = eval { symlink("",""); 1 };
Portability issues: "symlink" in perlport.
require 'syscall.ph'; # may need to run h2ph my $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 syscall, 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, then 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, but there is no way to retrieve the file number of the other end. You can avoid this problem by using "pipe" instead.
Portability issues: "syscall" in perlport.
Returns true on success and "undef" otherwise.
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(2) syscall 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: 0 means read-only, 1 means write-only, and 2 means read/write. We know that these values do not work under OS/390 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 "umask" for more on this.
Note that under Perls older than 5.8.0, "sysopen" depends on the fdopen(3) C library function. On many Unix systems, fdopen(3) is known to fail when file descriptors exceed a certain value, typically 255. If you need more file descriptors than that, consider using the "POSIX::open" function. For Perls 5.8.0 and later, PerlIO is (most often) the default.
See perlopentut for a kinder, gentler explanation of opening files.
Portability issues: "sysopen" in perlport.
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 well on device files (like ttys) anyway. Use "sysread" and check for a return value of 0 to decide whether you're done.
Note that if the filehandle has been marked as ":utf8", "sysread" will throw an exception. The ":encoding(...)" layer implicitly introduces the ":utf8" layer. See "binmode", "open", and the open pragma.
Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the ":encoding(UTF-8)" I/O layer), the "seek", "tell", and "sysseek" family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.
"sysseek" bypasses normal buffered IO, so mixing it with reads other than "sysread" (for example "readline" 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.
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.
my @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 may inspect the value of "${^CHILD_ERROR_NATIVE}" with the "W*()" calls from the POSIX module.
When "system"'s arguments are executed indirectly by the shell, results and return codes are subject to its quirks. See "`STRING`" in perlop and "exec" for details.
Since "system" does a "fork" and "wait" it may affect a "SIGCHLD" handler. See perlipc for details.
Portability issues: "system" in perlport.
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. If SCALAR is of length zero, you can only use an OFFSET of 0.
WARNING: If the filehandle is marked ":utf8", "syswrite" will raise an exception. The ":encoding(...)" layer implicitly introduces the ":utf8" layer. Alternately, if the handle is not marked with an encoding but you attempt to write characters with code points over 255, raises an exception. See "binmode", "open", and the open pragma.
Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the ":encoding(UTF-8)" I/O layer), the "seek", "tell", and "sysseek" family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.
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 filehandle that has been manipulated by "sysread", "syswrite", or "sysseek". Those functions ignore the buffering, while "tell" does not.
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(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); while (my ($key,$val) = each %HIST) { print $key, ' = ', unpack('L', $val), "\n"; }
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 DELETE this, key EXISTS this, key DESTROY this UNTIE this
A class implementing a filehandle 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".
For measuring time in better granularity than one second, use the Time::HiRes module from Perl 5.8 onwards (or from CPAN before then), 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.
my ($user,$system,$cuser,$csystem) = times;
In scalar context, "times" returns $user.
Children's times are only included for terminated children.
Portability issues: "times" in perlport.
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.
Portability issues: "truncate" in perlport.
If EXPR is omitted, uses $_.
This function behaves the same way under various pragmas, such as in a locale, as "lc" does.
If EXPR is omitted, uses $_.
This function behaves the same way under various pragmas, such as in a locale, as "lc" does.
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 (because "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"), raises an exception. 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.
Portability issues: "umask" in perlport.
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; my ($x, $y, undef, $z) = foo(); # Ignore third value returned
Note that this is a unary operator, not a list operator.
my $unlinked = unlink 'a', 'b', 'c'; unlink @goners; unlink glob "*.bak";
On error, "unlink" will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time:
foreach my $file ( @goners ) { unlink $file or warn "Could not unlink $file: $!"; }
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, "unlink" uses $_.
If EXPR is omitted, unpacks the $_ string. See perlpacktut for an introduction to this function.
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. The 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:
my $checksum = do { local $/; # slurp! unpack("%32W*", readline) % 65535; };
The following efficiently counts the number of set bits in a bit vector:
my $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: the repeat count may be decreased, or "unpack" may produce empty strings or zeros, or it may raise an exception. If the input string is longer than one described by the TEMPLATE, the remainder of that input string is ignored.
See "pack" for more examples and notes.
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.
Starting with Perl 5.14, an experimental feature allowed "unshift" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
BEGIN { require Module; Module->import( LIST ); }
except that Module must be a bareword. The importation can be made conditional by using the if module.
In the "use VERSION" form, VERSION may be either a v-string such as v5.24.1, which will be compared to $^V (aka $PERL_VERSION), or a numeric argument of the form 5.024001, which will be compared to $]. An exception is raised 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 numeric argument of the form 5.024001 should generally be avoided as older less readable syntax compared to v5.24.1. Before perl 5.8.0 released in 2002 the more verbose numeric form was the only supported syntax, which is why you might see it in
use v5.24.1; # compile time version check use 5.24.1; # ditto use 5.024_001; # ditto; older syntax compatible with perl 5.6
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.)
"use VERSION" also lexically enables all features available in the requested version as defined by the feature pragma, disabling any features not in the requested version's feature bundle. See feature. Similarly, if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with "use strict". Any explicit use of "use strict" or "no strict" overrides "use VERSION", even if it comes before it. Later use of "use VERSION" will override all behavior of a previous "use VERSION", possibly removing the "strict" and "feature" added by "use VERSION". "use VERSION" does not load the feature.pm or strict.pm files.
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:
use Module 12.34;
is equivalent to:
BEGIN { require Module; Module->VERSION(12.34) }
The default "VERSION" method, inherited from the "UNIVERSAL" class, croaks if the given version is larger than the value of the variable $Module::VERSION.
The VERSION argument cannot be an arbitrary expression. It only counts as a VERSION argument if it is a version number literal, starting with either a digit or "v" followed by a digit. Anything that doesn't look like a version literal will be parsed as the start of the LIST. Nevertheless, many attempts to use an arbitrary expression as a VERSION argument will appear to work, because Exporter's "import" method handles numeric arguments specially, performing version checks rather than treating them as things to export.
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. Some of the 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);
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).
Because "use" takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a "use" inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the if pragma:
use if $] < 5.008, "utf8"; use if WANT_WARNINGS, warnings => qw(all);
There's a corresponding "no" declaration that unimports meanings imported by "use", i.e., it calls "Module->unimport(LIST)" instead of "import". It behaves just as "import" does with VERSION, an omitted or empty LIST, or no unimport method being found.
no integer; no strict 'refs'; no warnings;
Care should be taken when using the "no VERSION" form of "no". It is only meant to be used to assert that the running Perl is of a earlier version than its argument and not to undo the feature-enabling side effects of "use VERSION".
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.
#!/usr/bin/perl my $atime = my $mtime = time; utime $atime, $mtime, @ARGV;
Since Perl 5.8.0, if the first two elements of the list are "undef", the utime(2) syscall from your C library is 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 work even on files you don't own provided you have write permission:
for my $file (@ARGV) { utime(undef, undef, $file) || warn "Couldn't touch $file: $!"; }
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.
Passing only one of the first two elements as "undef" is equivalent to passing a 0 and will not have the effect described when both are "undef". This also triggers an uninitialized warning.
On systems that support futimes(2), you may pass filehandles among the files. On systems that don't support futimes(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames.
Portability issues: "utime" in perlport.
Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash. Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by "each" or "keys" may be deleted without changing the order. So long as a given hash is unmodified you may rely on "keys", "values" and "each" to repeatedly return the same order as each other. See "Algorithmic Complexity Attacks" in perlsec for details on why hash order is randomized. Aside from the guarantees provided here the exact details of Perl's hash algorithm and the hash traversal order are subject to change in any release of Perl. Tied hashes may behave differently to Perl's hashes with respect to changes in order on insertion and deletion of items.
As a side effect, calling "values" resets the HASH or ARRAY's internal iterator (see "each") before yielding the values. In particular, calling "values" in void context resets the iterator with no other overhead.
Apart from resetting the iterator, "values @array" in list context is the same as plain @array. (We recommend that you use void context "keys @array" for this, but reasoned that taking "values @array" out would require more documentation than leaving it in.)
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
Starting with Perl 5.14, an experimental feature allowed "values" to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.
To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:
use 5.012; # so keys/values/each work on arrays
See also "keys", "each", and "sort".
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), "vec" tries to convert it to use a one-byte-per-character internal representation. However, if the string contains characters with values of 256 or higher, that conversion will fail, and a deprecation message will be raised. In that situation, "vec" will operate on the underlying buffer regardless, in its internal UTF-8 representation. In Perl 5.32, this will be a fatal error.
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.
my $foo = ''; vec($foo, 0, 32) = 0x5065726C; # 'Perl' # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') vec($foo, 2, 16) = 0x5065; # 'PerlPe' vec($foo, 3, 16) = 0x726C; # 'PerlPerl' vec($foo, 8, 8) = 0x50; # 'PerlPerlP' vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" vec($foo, 21, 4) = 7; # 'PerlPerlPer' # 'r' is "\x72" vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" vec($foo, 94, 1) = 1; # 'PerlPerlPerl' # 'l' is "\x6c"
To transform a bit vector into a string or list of 0's and 1's, use these:
my $bits = unpack("b*", $vector); my @bits = split(//, unpack("b*", $vector));
If you know the exact length in bits, it can be used in place of the "*".
Here is an example to illustrate how the bits actually fall in place:
#!/usr/bin/perl -wl print <<'EOT'; 0 1 2 3 unpack("V",$_)<PHONE_NUMBER>0123456789012345678901 ------------------------------------------------------------------ EOT for $w (0..3) { $width = 2**$w; for ($shift=0; $shift < $width; ++$shift) { for ($off=0; $off < 32/$width; ++$off) { $str = pack("B*", "0"x32); $bits = (1<<$shift); vec($str, $off, $width) = $bits; $res = unpack("b*",$str); $val = unpack("V", $str); write; } } } format STDOUT = vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $off, $width, $bits, $val, $res . __END__
Regardless of the machine architecture on which it runs, the example above should print the following table:
0 1 2 3 unpack("V",$_)<PHONE_NUMBER>0123456789012345678901 ------------------------------------------------------------------ vec($_, 0, 1) = 1 == 1<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 1) = 1 == 2<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 1) = 1 == 4<PHONE_NUMBER>0000000000000000000000 vec($_, 3, 1) = 1 == 8<PHONE_NUMBER>0000000000000000000000 vec($_, 4, 1) = 1 == 16<PHONE_NUMBER>0000000000000000000000 vec($_, 5, 1) = 1 == 32<PHONE_NUMBER>0000000000000000000000 vec($_, 6, 1) = 1 == 64<PHONE_NUMBER>0000000000000000000000 vec($_, 7, 1) = 1 ==<PHONE_NUMBER>1000000000000000000000000 vec($_, 8, 1) = 1 ==<PHONE_NUMBER>0100000000000000000000000 vec($_, 9, 1) = 1 ==<PHONE_NUMBER>0010000000000000000000000 vec($_,10, 1) = 1 == 1024<PHONE_NUMBER>1000000000000000000000 vec($_,11, 1) = 1 == 2048<PHONE_NUMBER>0100000000000000000000 vec($_,12, 1) = 1 == 4096<PHONE_NUMBER>0010000000000000000000 vec($_,13, 1) = 1 == 8192<PHONE_NUMBER>0001000000000000000000 vec($_,14, 1) = 1 == 16384<PHONE_NUMBER>0000100000000000000000 vec($_,15, 1) = 1 == 32768<PHONE_NUMBER>0000010000000000000000 vec($_,16, 1) = 1 == 65536<PHONE_NUMBER>0000001000000000000000 vec($_,17, 1) = 1 ==<PHONE_NUMBER>0000000000000100000000000000 vec($_,18, 1) = 1 ==<PHONE_NUMBER>0000000000000010000000000000 vec($_,19, 1) = 1 ==<PHONE_NUMBER>0000000000000001000000000000 vec($_,20, 1) = 1 == 1048576<PHONE_NUMBER>0000000000100000000000 vec($_,21, 1) = 1 == 2097152<PHONE_NUMBER>0000000000010000000000 vec($_,22, 1) = 1 == 4194304<PHONE_NUMBER>0000000000001000000000 vec($_,23, 1) = 1 == 8388608<PHONE_NUMBER>0000000000000100000000 vec($_,24, 1) = 1 == 16777216<PHONE_NUMBER>0000000000000010000000 vec($_,25, 1) = 1 == 33554432<PHONE_NUMBER>0000000000000001000000 vec($_,26, 1) = 1 == 67108864<PHONE_NUMBER>0000000000000000100000 vec($_,27, 1) = 1 == 134217728<PHONE_NUMBER>0000000000000000010000 vec($_,28, 1) = 1 == 268435456<PHONE_NUMBER>0000000000000000001000 vec($_,29, 1) = 1 == 536870912<PHONE_NUMBER>0000000000000000000100 vec($_,30, 1) = 1 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000010 vec($_,31, 1) = 1 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000001 vec($_, 0, 2) = 1 == 1<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 2) = 1 == 4<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 2) = 1 == 16<PHONE_NUMBER>0000000000000000000000 vec($_, 3, 2) = 1 == 64<PHONE_NUMBER>0000000000000000000000 vec($_, 4, 2) = 1 ==<PHONE_NUMBER>0100000000000000000000000 vec($_, 5, 2) = 1 == 1024<PHONE_NUMBER>1000000000000000000000 vec($_, 6, 2) = 1 == 4096<PHONE_NUMBER>0010000000000000000000 vec($_, 7, 2) = 1 == 16384<PHONE_NUMBER>0000100000000000000000 vec($_, 8, 2) = 1 == 65536<PHONE_NUMBER>0000001000000000000000 vec($_, 9, 2) = 1 ==<PHONE_NUMBER>0000000000000010000000000000 vec($_,10, 2) = 1 == 1048576<PHONE_NUMBER>0000000000100000000000 vec($_,11, 2) = 1 == 4194304<PHONE_NUMBER>0000000000001000000000 vec($_,12, 2) = 1 == 16777216<PHONE_NUMBER>0000000000000010000000 vec($_,13, 2) = 1 == 67108864<PHONE_NUMBER>0000000000000000100000 vec($_,14, 2) = 1 == 268435456<PHONE_NUMBER>0000000000000000001000 vec($_,15, 2) = 1 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000010 vec($_, 0, 2) = 2 == 2<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 2) = 2 == 8<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 2) = 2 == 32<PHONE_NUMBER>0000000000000000000000 vec($_, 3, 2) = 2 ==<PHONE_NUMBER>1000000000000000000000000 vec($_, 4, 2) = 2 ==<PHONE_NUMBER>0010000000000000000000000 vec($_, 5, 2) = 2 == 2048<PHONE_NUMBER>0100000000000000000000 vec($_, 6, 2) = 2 == 8192<PHONE_NUMBER>0001000000000000000000 vec($_, 7, 2) = 2 == 32768<PHONE_NUMBER>0000010000000000000000 vec($_, 8, 2) = 2 ==<PHONE_NUMBER>0000000000000100000000000000 vec($_, 9, 2) = 2 ==<PHONE_NUMBER>0000000000000001000000000000 vec($_,10, 2) = 2 == 2097152<PHONE_NUMBER>0000000000010000000000 vec($_,11, 2) = 2 == 8388608<PHONE_NUMBER>0000000000000100000000 vec($_,12, 2) = 2 == 33554432<PHONE_NUMBER>0000000000000001000000 vec($_,13, 2) = 2 == 134217728<PHONE_NUMBER>0000000000000000010000 vec($_,14, 2) = 2 == 536870912<PHONE_NUMBER>0000000000000000000100 vec($_,15, 2) = 2 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000001 vec($_, 0, 4) = 1 == 1<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 4) = 1 == 16<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 4) = 1 ==<PHONE_NUMBER>0100000000000000000000000 vec($_, 3, 4) = 1 == 4096<PHONE_NUMBER>0010000000000000000000 vec($_, 4, 4) = 1 == 65536<PHONE_NUMBER>0000001000000000000000 vec($_, 5, 4) = 1 == 1048576<PHONE_NUMBER>0000000000100000000000 vec($_, 6, 4) = 1 == 16777216<PHONE_NUMBER>0000000000000010000000 vec($_, 7, 4) = 1 == 268435456<PHONE_NUMBER>0000000000000000001000 vec($_, 0, 4) = 2 == 2<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 4) = 2 == 32<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 4) = 2 ==<PHONE_NUMBER>0010000000000000000000000 vec($_, 3, 4) = 2 == 8192<PHONE_NUMBER>0001000000000000000000 vec($_, 4, 4) = 2 ==<PHONE_NUMBER>0000000000000100000000000000 vec($_, 5, 4) = 2 == 2097152<PHONE_NUMBER>0000000000010000000000 vec($_, 6, 4) = 2 == 33554432<PHONE_NUMBER>0000000000000001000000 vec($_, 7, 4) = 2 == 536870912<PHONE_NUMBER>0000000000000000000100 vec($_, 0, 4) = 4 == 4<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 4) = 4 == 64<PHONE_NUMBER>0000000000000000000000 vec($_, 2, 4) = 4 == 1024<PHONE_NUMBER>1000000000000000000000 vec($_, 3, 4) = 4 == 16384<PHONE_NUMBER>0000100000000000000000 vec($_, 4, 4) = 4 ==<PHONE_NUMBER>0000000000000010000000000000 vec($_, 5, 4) = 4 == 4194304<PHONE_NUMBER>0000000000001000000000 vec($_, 6, 4) = 4 == 67108864<PHONE_NUMBER>0000000000000000100000 vec($_, 7, 4) = 4 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000010 vec($_, 0, 4) = 8 == 8<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 4) = 8 ==<PHONE_NUMBER>1000000000000000000000000 vec($_, 2, 4) = 8 == 2048<PHONE_NUMBER>0100000000000000000000 vec($_, 3, 4) = 8 == 32768<PHONE_NUMBER>0000010000000000000000 vec($_, 4, 4) = 8 ==<PHONE_NUMBER>0000000000000001000000000000 vec($_, 5, 4) = 8 == 8388608<PHONE_NUMBER>0000000000000100000000 vec($_, 6, 4) = 8 == 134217728<PHONE_NUMBER>0000000000000000010000 vec($_, 7, 4) = 8 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000001 vec($_, 0, 8) = 1 == 1<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 1 ==<PHONE_NUMBER>0100000000000000000000000 vec($_, 2, 8) = 1 == 65536<PHONE_NUMBER>0000001000000000000000 vec($_, 3, 8) = 1 == 16777216<PHONE_NUMBER>0000000000000010000000 vec($_, 0, 8) = 2 == 2<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 2 ==<PHONE_NUMBER>0010000000000000000000000 vec($_, 2, 8) = 2 ==<PHONE_NUMBER>0000000000000100000000000000 vec($_, 3, 8) = 2 == 33554432<PHONE_NUMBER>0000000000000001000000 vec($_, 0, 8) = 4 == 4<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 4 == 1024<PHONE_NUMBER>1000000000000000000000 vec($_, 2, 8) = 4 ==<PHONE_NUMBER>0000000000000010000000000000 vec($_, 3, 8) = 4 == 67108864<PHONE_NUMBER>0000000000000000100000 vec($_, 0, 8) = 8 == 8<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 8 == 2048<PHONE_NUMBER>0100000000000000000000 vec($_, 2, 8) = 8 ==<PHONE_NUMBER>0000000000000001000000000000 vec($_, 3, 8) = 8 == 134217728<PHONE_NUMBER>0000000000000000010000 vec($_, 0, 8) = 16 == 16<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 16 == 4096<PHONE_NUMBER>0010000000000000000000 vec($_, 2, 8) = 16 == 1048576<PHONE_NUMBER>0000000000100000000000 vec($_, 3, 8) = 16 == 268435456<PHONE_NUMBER>0000000000000000001000 vec($_, 0, 8) = 32 == 32<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 32 == 8192<PHONE_NUMBER>0001000000000000000000 vec($_, 2, 8) = 32 == 2097152<PHONE_NUMBER>0000000000010000000000 vec($_, 3, 8) = 32 == 536870912<PHONE_NUMBER>0000000000000000000100 vec($_, 0, 8) = 64 == 64<PHONE_NUMBER>0000000000000000000000 vec($_, 1, 8) = 64 == 16384<PHONE_NUMBER>0000100000000000000000 vec($_, 2, 8) = 64 == 4194304<PHONE_NUMBER>0000000000001000000000 vec($_, 3, 8) = 64 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000010 vec($_, 0, 8) = 128 ==<PHONE_NUMBER>1000000000000000000000000 vec($_, 1, 8) = 128 == 32768<PHONE_NUMBER>0000010000000000000000 vec($_, 2, 8) = 128 == 8388608<PHONE_NUMBER>0000000000000100000000 vec($_, 3, 8) = 128 ==<PHONE_NUMBER><PHONE_NUMBER>0000000000000000000001
If you use "wait" in your handler for $SIG{CHLD}, it may accidentally wait for the child created by "qx" or "system". See perlipc for details.
Portability issues: "wait" in perlport.
A PID of 0 indicates to wait for any child process whose process group ID is equal to that of the current process. A PID of less than "-1" indicates to wait for any child process whose process group ID is equal to -PID. A PID of "-1" indicates to wait for any child process.
If you say
use POSIX ":sys_wait_h"; my $kid; do { $kid = waitpid(-1, WNOHANG); } while $kid > 0;
or
1 while waitpid(-1, WNOHANG) > 0;
then you can do a non-blocking wait for all pending zombie processes (see "WAIT" in POSIX). Non-blocking wait is available on machines supporting either the waitpid(2) or wait4(2) syscalls. However, waiting for a particular pid with FLAGS of 0 is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.)
Note that on some systems, a return value of "-1" could mean that child processes are being automatically reaped. See perlipc for details, and for other examples.
Portability issues: "waitpid" in perlport.
return unless defined wantarray; # don't bother doing more my @a = complex_calculation(); return wantarray ? @a : "@a";
"wantarray"'s result is unspecified in the top level of a file, in a "BEGIN", "UNITCHECK", "CHECK", "INIT" or "END" block, or in a "DESTROY" method.
This function should have been named wantlist() instead.
By default, the exception derived from the operand LIST is stringified and printed to "STDERR". This behaviour can be altered by installing a $SIG{__WARN__} handler. If there is such a handler then no message is automatically printed; it is the handler's responsibility to deal with the exception as it sees fit (like, for instance, converting it into a "die"). Most handlers must therefore arrange to actually display the warnings that they are not prepared to deal with, by calling "warn" again in the handler. Note that this is quite safe and will not produce an endless loop, since "__WARN__" hooks are not called from inside one.
You will find this behavior is slightly different from that of $SIG{__DIE__} handlers (which don't suppress the error text, but can instead call "die" again to change it).
Using a "__WARN__" handler provides a powerful way to silence all warnings (even the so-called mandatory ones). An example:
# wipe out *all* compile-time warnings BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } my $foo = 10; my $foo = 20; # no warning about duplicate my $foo, # but hey, you asked for it! # no compile-time or run-time warnings before here $DOWARN = 1; # run-time warnings enabled after here warn "\$foo is alive and $foo!"; # does show up
See perlvar for details on setting %SIG entries and for more examples. See the Carp module for other kinds of warnings using its "carp" and "cluck" functions.
Top of form processing is handled automatically: if there is insufficient room on the current page for the formatted record, the page is advanced by writing a form feed and a special top-of-page format is used to format the new page header before the record is written. By default, the top-of-page format is the name of the filehandle with "_TOP" appended, or "top" in the current package if the former does not exist. This would be a problem with autovivified filehandles, but it may be dynamically set to the format of your choice by assigning the name to the $^ variable while that filehandle is selected. The number of lines remaining on the current page is in variable "$-", which can be set to 0 to force a new page.
If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the "select" operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see perlform.
Note that write is not the opposite of "read". Unfortunately.
perlmod
perlobj
perlop
perlsub
perlsyn
See the documentation for flow-control keywords in "Compound Statements" in perlsyn.
| 2019-10-21 | perl v5.30.3 |