code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
perl ExtUtils::MakeMaker::Config ExtUtils::MakeMaker::Config
===========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::MakeMaker::Config - Wrapper around Config.pm
SYNOPSIS
--------
```
use ExtUtils::MakeMaker::Config;
print $Config{installbin}; # or whatever
```
DESCRIPTION
-----------
**FOR INTERNAL USE ONLY**
A very thin wrapper around Config.pm so MakeMaker is easier to test.
perl Tie::Hash Tie::Hash
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Inheriting from Tie::StdHash](#Inheriting-from-Tie::StdHash)
* [Inheriting from Tie::ExtraHash](#Inheriting-from-Tie::ExtraHash)
* [SCALAR, UNTIE and DESTROY](#SCALAR,-UNTIE-and-DESTROY)
* [MORE INFORMATION](#MORE-INFORMATION)
NAME
----
Tie::Hash, Tie::StdHash, Tie::ExtraHash - base class definitions for tied hashes
SYNOPSIS
--------
```
package NewHash;
require Tie::Hash;
@ISA = qw(Tie::Hash);
sub DELETE { ... } # Provides needed method
sub CLEAR { ... } # Overrides inherited method
package NewStdHash;
require Tie::Hash;
@ISA = qw(Tie::StdHash);
# All methods provided by default, define
# only those needing overrides
# Accessors access the storage in %{$_[0]};
# TIEHASH should return a reference to the actual storage
sub DELETE { ... }
package NewExtraHash;
require Tie::Hash;
@ISA = qw(Tie::ExtraHash);
# All methods provided by default, define
# only those needing overrides
# Accessors access the storage in %{$_[0][0]};
# TIEHASH should return an array reference with the first element
# being the reference to the actual storage
sub DELETE {
$_[0][1]->('del', $_[0][0], $_[1]); # Call the report writer
delete $_[0][0]->{$_[1]}; # $_[0]->SUPER::DELETE($_[1])
}
package main;
tie %new_hash, 'NewHash';
tie %new_std_hash, 'NewStdHash';
tie %new_extra_hash, 'NewExtraHash',
sub {warn "Doing \U$_[1]\E of $_[2].\n"};
```
DESCRIPTION
-----------
This module provides some skeletal methods for hash-tying classes. See <perltie> for a list of the functions required in order to tie a hash to a package. The basic **Tie::Hash** package provides a `new` method, as well as methods `TIEHASH`, `EXISTS` and `CLEAR`. The **Tie::StdHash** and **Tie::ExtraHash** packages provide most methods for hashes described in <perltie> (the exceptions are `UNTIE` and `DESTROY`). They cause tied hashes to behave exactly like standard hashes, and allow for selective overwriting of methods. **Tie::Hash** has legacy support for the `new` method: it is used if `TIEHASH` is not defined in the case a class forgets to include a `TIEHASH` method.
For developers wishing to write their own tied hashes, the required methods are briefly defined below. See the <perltie> section for more detailed descriptive, as well as example code:
TIEHASH classname, LIST The method invoked by the command `tie %hash, classname`. Associates a new hash instance with the specified class. `LIST` would represent additional arguments (along the lines of [AnyDBM\_File](anydbm_file) and compatriots) needed to complete the association.
STORE this, key, value Store datum *value* into *key* for the tied hash *this*.
FETCH this, key Retrieve the datum in *key* for the tied hash *this*.
FIRSTKEY this Return the first key in the hash.
NEXTKEY this, lastkey Return the next key in the hash.
EXISTS this, key Verify that *key* exists with the tied hash *this*.
The **Tie::Hash** implementation is a stub that simply croaks.
DELETE this, key Delete the key *key* from the tied hash *this*.
CLEAR this Clear all values from the tied hash *this*.
SCALAR this Returns what evaluating the hash in scalar context yields.
**Tie::Hash** does not implement this method (but **Tie::StdHash** and **Tie::ExtraHash** do).
Inheriting from **Tie::StdHash**
---------------------------------
The accessor methods assume that the actual storage for the data in the tied hash is in the hash referenced by `tied(%tiedhash)`. Thus overwritten `TIEHASH` method should return a hash reference, and the remaining methods should operate on the hash referenced by the first argument:
```
package ReportHash;
our @ISA = 'Tie::StdHash';
sub TIEHASH {
my $storage = bless {}, shift;
warn "New ReportHash created, stored in $storage.\n";
$storage
}
sub STORE {
warn "Storing data with key $_[1] at $_[0].\n";
$_[0]{$_[1]} = $_[2]
}
```
Inheriting from **Tie::ExtraHash**
-----------------------------------
The accessor methods assume that the actual storage for the data in the tied hash is in the hash referenced by `(tied(%tiedhash))->[0]`. Thus overwritten `TIEHASH` method should return an array reference with the first element being a hash reference, and the remaining methods should operate on the hash `%{ $_[0]->[0] }`:
```
package ReportHash;
our @ISA = 'Tie::ExtraHash';
sub TIEHASH {
my $class = shift;
my $storage = bless [{}, @_], $class;
warn "New ReportHash created, stored in $storage.\n";
$storage;
}
sub STORE {
warn "Storing data with key $_[1] at $_[0].\n";
$_[0][0]{$_[1]} = $_[2]
}
```
The default `TIEHASH` method stores "extra" arguments to tie() starting from offset 1 in the array referenced by `tied(%tiedhash)`; this is the same storage algorithm as in TIEHASH subroutine above. Hence, a typical package inheriting from **Tie::ExtraHash** does not need to overwrite this method.
`SCALAR`, `UNTIE` and `DESTROY`
--------------------------------
The methods `UNTIE` and `DESTROY` are not defined in **Tie::Hash**, **Tie::StdHash**, or **Tie::ExtraHash**. Tied hashes do not require presence of these methods, but if defined, the methods will be called in proper time, see <perltie>.
`SCALAR` is only defined in **Tie::StdHash** and **Tie::ExtraHash**.
If needed, these methods should be defined by the package inheriting from **Tie::Hash**, **Tie::StdHash**, or **Tie::ExtraHash**. See ["SCALAR" in perltie](perltie#SCALAR) to find out what happens when `SCALAR` does not exist.
MORE INFORMATION
-----------------
The packages relating to various DBM-related implementations (*DB\_File*, *NDBM\_File*, etc.) show examples of general tied hashes, as does the [Config](config) module. While these do not utilize **Tie::Hash**, they serve as good working examples.
perl perldeprecation perldeprecation
===============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Perl 5.40](#Perl-5.40)
- [Downgrading a use VERSION to below v5.11](#Downgrading-a-use-VERSION-to-below-v5.11)
+ [Perl 5.38](#Perl-5.38)
- [Pod::Html utility functions](#Pod::Html-utility-functions)
+ [Perl 5.34](#Perl-5.34)
+ [Perl 5.32](#Perl-5.32)
- [Constants from lexical variables potentially modified elsewhere](#Constants-from-lexical-variables-potentially-modified-elsewhere)
- [Use of strings with code points over 0xFF as arguments to vec](#Use-of-strings-with-code-points-over-0xFF-as-arguments-to-vec)
- [Use of code points over 0xFF in string bitwise operators](#Use-of-code-points-over-0xFF-in-string-bitwise-operators)
- [hostname() doesn't accept any arguments](#hostname()-doesn't-accept-any-arguments)
- [Unescaped left braces in regular expressions](#Unescaped-left-braces-in-regular-expressions)
- [In XS code, use of various macros dealing with UTF-8.](#In-XS-code,-use-of-various-macros-dealing-with-UTF-8.)
- [File::Glob::glob() was removed](#File::Glob::glob()-was-removed)
+ [Perl 5.30](#Perl-5.30)
- [$\* is no longer supported](#%24*-is-no-longer-supported)
- [$# is no longer supported](#%24%23-is-no-longer-supported)
- [Assigning non-zero to $[ is fatal](#Assigning-non-zero-to-%24%5B-is-fatal)
- [File::Glob::glob() will disappear](#File::Glob::glob()-will-disappear)
- [Unescaped left braces in regular expressions (for 5.30)](#Unescaped-left-braces-in-regular-expressions-(for-5.30))
- [Unqualified dump()](#Unqualified-dump())
- [Using my() in false conditional.](#Using-my()-in-false-conditional.)
- [Reading/writing bytes from/to :utf8 handles.](#Reading/writing-bytes-from/to-:utf8-handles.)
- [Use of unassigned code point or non-standalone grapheme for a delimiter.](#Use-of-unassigned-code-point-or-non-standalone-grapheme-for-a-delimiter.)
+ [Perl 5.28](#Perl-5.28)
- [Attributes :locked and :unique](#Attributes-:locked-and-:unique)
- [Bare here-document terminators](#Bare-here-document-terminators)
- [Setting $/ to a reference to a non-positive integer](#Setting-%24/-to-a-reference-to-a-non-positive-integer)
- [Limit on the value of Unicode code points.](#Limit-on-the-value-of-Unicode-code-points.)
- [Use of comma-less variable list in formats.](#Use-of-comma-less-variable-list-in-formats.)
- [Use of \N{}](#Use-of-%5CN%7B%7D)
- [Using the same symbol to open a filehandle and a dirhandle](#Using-the-same-symbol-to-open-a-filehandle-and-a-dirhandle)
- [${^ENCODING} is no longer supported.](#%24%7B%5EENCODING%7D-is-no-longer-supported.)
- [B::OP::terse](#B::OP::terse)
- [Use of inherited AUTOLOAD for non-method %s::%s() is no longer allowed](#Use-of-inherited-AUTOLOAD-for-non-method-%25s::%25s()-is-no-longer-allowed)
- [Use of code points over 0xFF in string bitwise operators](#Use-of-code-points-over-0xFF-in-string-bitwise-operators1)
- [In XS code, use of to\_utf8\_case()](#In-XS-code,-use-of-to_utf8_case())
+ [Perl 5.26](#Perl-5.26)
- [--libpods in Pod::Html](#-libpods-in-Pod::Html)
- [The utilities c2ph and pstruct](#The-utilities-c2ph-and-pstruct)
- [Trapping $SIG {\_\_DIE\_\_} other than during program exit.](#Trapping-%24SIG-%7B__DIE__%7D-other-than-during-program-exit.)
- [Malformed UTF-8 string in "%s"](#Malformed-UTF-8-string-in-%22%25s%22)
+ [Perl 5.24](#Perl-5.24)
- [Use of \*glob{FILEHANDLE}](#Use-of-*glob%7BFILEHANDLE%7D)
- [Calling POSIX::%s() is deprecated](#Calling-POSIX::%25s()-is-deprecated)
+ [Perl 5.16](#Perl-5.16)
- [Use of %s on a handle without \* is deprecated](#Use-of-%25s-on-a-handle-without-*-is-deprecated)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perldeprecation - list Perl deprecations
DESCRIPTION
-----------
The purpose of this document is to document what has been deprecated in Perl, and by which version the deprecated feature will disappear, or, for already removed features, when it was removed.
This document will try to discuss what alternatives for the deprecated features are available.
The deprecated features will be grouped by the version of Perl in which they will be removed.
###
Perl 5.40
####
Downgrading a `use VERSION` to below v5.11
Once Perl has seen a `use VERSION` declaration that requests a version `v5.11` or above, a subsequent second declaration that requests an earlier version will print a deprecation warning. For example,
```
use v5.14;
say "We can use v5.14's features here";
use v5.10; # This prints a warning
```
This behaviour will be removed in Perl 5.40; such a subsequent request will become a compile-time error.
This is because of an intended related change to the interaction between `use VERSION` and `use strict`. If you specify a version >= 5.11, strict is enabled implicitly. If you request a version < 5.11, strict will become disabled *even if you had previously written* `use strict`. This was not the previous behaviour of `use VERSION`, which at present will track explicitly-enabled strictness flags independently.
###
Perl 5.38
####
Pod::Html utility functions
The definition and documentation of three utility functions previously importable from <Pod::Html> were moved to new package <Pod::Html::Util> in Perl 5.36. While they remain importable from <Pod::Html> in Perl 5.36, as of Perl 5.38 they will only be importable, on request, from <Pod::Html::Util>.
###
Perl 5.34
There are no deprecations or fatalizations scheduled for Perl 5.34.
###
Perl 5.32
####
Constants from lexical variables potentially modified elsewhere
You wrote something like
```
my $var;
$sub = sub () { $var };
```
but $var is referenced elsewhere and could be modified after the `sub` expression is evaluated. Either it is explicitly modified elsewhere (`$var = 3`) or it is passed to a subroutine or to an operator like `printf` or `map`, which may or may not modify the variable.
Traditionally, Perl has captured the value of the variable at that point and turned the subroutine into a constant eligible for inlining. In those cases where the variable can be modified elsewhere, this breaks the behavior of closures, in which the subroutine captures the variable itself, rather than its value, so future changes to the variable are reflected in the subroutine's return value.
If you intended for the subroutine to be eligible for inlining, then make sure the variable is not referenced elsewhere, possibly by copying it:
```
my $var2 = $var;
$sub = sub () { $var2 };
```
If you do want this subroutine to be a closure that reflects future changes to the variable that it closes over, add an explicit `return`:
```
my $var;
$sub = sub () { return $var };
```
This usage was deprecated and as of Perl 5.32 is no longer allowed.
####
Use of strings with code points over 0xFF as arguments to `vec`
`vec` views its string argument as a sequence of bits. A string containing a code point over 0xFF is nonsensical. This usage is deprecated in Perl 5.28, and was removed in Perl 5.32.
####
Use of code points over 0xFF in string bitwise operators
The string bitwise operators, `&`, `|`, `^`, and `~`, treat their operands as strings of bytes. As such, values above 0xFF are nonsensical. Some instances of these have been deprecated since Perl 5.24, and were made fatal in 5.28, but it turns out that in cases where the wide characters did not affect the end result, no deprecation notice was raised, and so remain legal. Now, all occurrences either are fatal or raise a deprecation warning, so that the remaining legal occurrences became fatal in 5.32.
An example of this is
```
"" & "\x{100}"
```
The wide character is not used in the `&` operation because the left operand is shorter. This now throws an exception.
####
hostname() doesn't accept any arguments
The function `hostname()` in the <Sys::Hostname> module has always been documented to be called with no arguments. Historically it has not enforced this, and has actually accepted and ignored any arguments. As a result, some users have got the mistaken impression that an argument does something useful. To avoid these bugs, the function is being made strict. Passing arguments was deprecated in Perl 5.28 and became fatal in Perl 5.32.
####
Unescaped left braces in regular expressions
The simple rule to remember, if you want to match a literal `{` character (U+007B `LEFT CURLY BRACKET`) in a regular expression pattern, is to escape each literal instance of it in some way. Generally easiest is to precede it with a backslash, like `\{` or enclose it in square brackets (`[{]`). If the pattern delimiters are also braces, any matching right brace (`}`) should also be escaped to avoid confusing the parser, for example,
```
qr{abc\{def\}ghi}
```
Forcing literal `{` characters to be escaped will enable the Perl language to be extended in various ways in future releases. To avoid needlessly breaking existing code, the restriction is not enforced in contexts where there are unlikely to ever be extensions that could conflict with the use there of `{` as a literal. A non-deprecation warning that the left brace is being taken literally is raised in contexts where there could be confusion about it.
Literal uses of `{` were deprecated in Perl 5.20, and some uses of it started to give deprecation warnings since. These cases were made fatal in Perl 5.26. Due to an oversight, not all cases of a use of a literal `{` got a deprecation warning. Some cases started warning in Perl 5.26, and were made fatal in Perl 5.30. Other cases started in Perl 5.28, and were made fatal in 5.32.
####
In XS code, use of various macros dealing with UTF-8.
The macros below now require an extra parameter than in versions prior to Perl 5.32. The final parameter in each one is a pointer into the string supplied by the first parameter beyond which the input will not be read. This prevents potential reading beyond the end of the buffer. `isALPHANUMERIC_utf8`, `isASCII_utf8`, `isBLANK_utf8`, `isCNTRL_utf8`, `isDIGIT_utf8`, `isIDFIRST_utf8`, `isPSXSPC_utf8`, `isSPACE_utf8`, `isVERTWS_utf8`, `isWORDCHAR_utf8`, `isXDIGIT_utf8`, `isALPHANUMERIC_LC_utf8`, `isALPHA_LC_utf8`, `isASCII_LC_utf8`, `isBLANK_LC_utf8`, `isCNTRL_LC_utf8`, `isDIGIT_LC_utf8`, `isGRAPH_LC_utf8`, `isIDCONT_LC_utf8`, `isIDFIRST_LC_utf8`, `isLOWER_LC_utf8`, `isPRINT_LC_utf8`, `isPSXSPC_LC_utf8`, `isPUNCT_LC_utf8`, `isSPACE_LC_utf8`, `isUPPER_LC_utf8`, `isWORDCHAR_LC_utf8`, `isXDIGIT_LC_utf8`, `toFOLD_utf8`, `toLOWER_utf8`, `toTITLE_utf8`, and `toUPPER_utf8`.
Since Perl 5.26, this functionality with the extra parameter has been available by using a corresponding macro to each one of these, and whose name is formed by appending `_safe` to the base name. There is no change to the functionality of those. For example, `isDIGIT_utf8_safe` corresponds to `isDIGIT_utf8`, and both now behave identically. All are documented in ["Character case changing" in perlapi](perlapi#Character-case-changing) and ["Character classification" in perlapi](perlapi#Character-classification).
This change was originally scheduled for 5.30, but was delayed until 5.32.
####
`File::Glob::glob()` was removed
`File::Glob` has a function called `glob`, which just calls `bsd_glob`.
`File::Glob::glob()` was deprecated in Perl 5.8. A deprecation message was issued from Perl 5.26 onwards, the function became fatal in Perl 5.30, and was removed entirely in Perl 5.32.
Code using `File::Glob::glob()` should call `File::Glob::bsd_glob()` instead.
###
Perl 5.30
####
`$*` is no longer supported
Before Perl 5.10, setting `$*` to a true value globally enabled multi-line matching within a string. This relique from the past lost its special meaning in 5.10. Use of this variable became a fatal error in Perl 5.30, freeing the variable up for a future special meaning.
To enable multiline matching one should use the `/m` regexp modifier (possibly in combination with `/s`). This can be set on a per match bases, or can be enabled per lexical scope (including a whole file) with `use re '/m'`.
####
`$#` is no longer supported
This variable used to have a special meaning -- it could be used to control how numbers were formatted when printed. This seldom used functionality was removed in Perl 5.10. In order to free up the variable for a future special meaning, its use became a fatal error in Perl 5.30.
To specify how numbers are formatted when printed, one is advised to use `printf` or `sprintf` instead.
####
Assigning non-zero to `$[` is fatal
This variable (and the corresponding `array_base` feature and <arybase> module) allowed changing the base for array and string indexing operations.
Setting this to a non-zero value has been deprecated since Perl 5.12 and throws a fatal error as of Perl 5.30.
####
`File::Glob::glob()` will disappear
`File::Glob` has a function called `glob`, which just calls `bsd_glob`. However, its prototype is different from the prototype of `CORE::glob`, and hence, `File::Glob::glob` should not be used.
`File::Glob::glob()` was deprecated in Perl 5.8. A deprecation message was issued from Perl 5.26 onwards, and in Perl 5.30 this was turned into a fatal error.
Code using `File::Glob::glob()` should call `File::Glob::bsd_glob()` instead.
####
Unescaped left braces in regular expressions (for 5.30)
See ["Unescaped left braces in regular expressions"](#Unescaped-left-braces-in-regular-expressions) above.
####
Unqualified `dump()`
Use of `dump()` instead of `CORE::dump()` was deprecated in Perl 5.8, and an unqualified `dump()` is no longer available as of Perl 5.30.
See ["dump" in perlfunc](perlfunc#dump).
####
Using my() in false conditional.
There has been a long-standing bug in Perl that causes a lexical variable not to be cleared at scope exit when its declaration includes a false conditional. Some people have exploited this bug to achieve a kind of static variable. To allow us to fix this bug, people should not be relying on this behavior.
Instead, it's recommended one uses `state` variables to achieve the same effect:
```
use 5.10.0;
sub count {state $counter; return ++ $counter}
say count (); # Prints 1
say count (); # Prints 2
```
`state` variables were introduced in Perl 5.10.
Alternatively, you can achieve a similar static effect by declaring the variable in a separate block outside the function, e.g.,
```
sub f { my $x if 0; return $x++ }
```
becomes
```
{ my $x; sub f { return $x++ } }
```
The use of `my()` in a false conditional has been deprecated in Perl 5.10, and became a fatal error in Perl 5.30.
####
Reading/writing bytes from/to :utf8 handles.
The sysread(), recv(), syswrite() and send() operators are deprecated on handles that have the `:utf8` layer, either explicitly, or implicitly, eg., with the `:encoding(UTF-16LE)` layer.
Both sysread() and recv() currently use only the `:utf8` flag for the stream, ignoring the actual layers. Since sysread() and recv() do no UTF-8 validation they can end up creating invalidly encoded scalars.
Similarly, syswrite() and send() use only the `:utf8` flag, otherwise ignoring any layers. If the flag is set, both write the value UTF-8 encoded, even if the layer is some different encoding, such as the example above.
Ideally, all of these operators would completely ignore the `:utf8` state, working only with bytes, but this would result in silently breaking existing code. To avoid this a future version of perl will throw an exception when any of sysread(), recv(), syswrite() or send() are called on handle with the `:utf8` layer.
As of Perl 5.30, it is no longer be possible to use sysread(), recv(), syswrite() or send() to read or send bytes from/to :utf8 handles.
####
Use of unassigned code point or non-standalone grapheme for a delimiter.
A grapheme is what appears to a native-speaker of a language to be a character. In Unicode (and hence Perl) a grapheme may actually be several adjacent characters that together form a complete grapheme. For example, there can be a base character, like "R" and an accent, like a circumflex "^", that appear to be a single character when displayed, with the circumflex hovering over the "R".
As of Perl 5.30, use of delimiters which are non-standalone graphemes is fatal, in order to move the language to be able to accept multi-character graphemes as delimiters.
Also, as of Perl 5.30, delimiters which are unassigned code points but that may someday become assigned are prohibited. Otherwise, code that works today would fail to compile if the currently unassigned delimiter ends up being something that isn't a stand-alone grapheme. Because Unicode is never going to assign [non-character code points](perlunicode#Noncharacter-code-points), nor [code points that are above the legal Unicode maximum](perlunicode#Beyond-Unicode-code-points), those can be delimiters.
###
Perl 5.28
####
Attributes `:locked` and `:unique`
The attributes `:locked` (on code references) and `:unique` (on array, hash and scalar references) have had no effect since Perl 5.005 and Perl 5.8.8 respectively. Their use has been deprecated since.
As of Perl 5.28, these attributes are syntax errors. Since the attributes do not do anything, removing them from your code fixes the syntax error; and removing them will not influence the behaviour of your code.
####
Bare here-document terminators
Perl has allowed you to use a bare here-document terminator to have the here-document end at the first empty line. This practise was deprecated in Perl 5.000; as of Perl 5.28, using a bare here-document terminator throws a fatal error.
You are encouraged to use the explicitly quoted form if you wish to use an empty line as the terminator of the here-document:
```
print <<"";
Print this line.
# Previous blank line ends the here-document.
```
####
Setting $/ to a reference to a non-positive integer
You assigned a reference to a scalar to `$/` where the referenced item is not a positive integer. In older perls this **appeared** to work the same as setting it to `undef` but was in fact internally different, less efficient and with very bad luck could have resulted in your file being split by a stringified form of the reference.
In Perl 5.20.0 this was changed so that it would be **exactly** the same as setting `$/` to undef, with the exception that this warning would be thrown.
As of Perl 5.28, setting `$/` to a reference of a non-positive integer throws a fatal error.
You are recommended to change your code to set `$/` to `undef` explicitly if you wish to slurp the file.
####
Limit on the value of Unicode code points.
Unicode only allows code points up to 0x10FFFF, but Perl allows much larger ones. Up till Perl 5.28, it was allowed to use code points exceeding the maximum value of an integer (`IV_MAX`). However, that did break the perl interpreter in some constructs, including causing it to hang in a few cases. The known problem areas were in `tr///`, regular expression pattern matching using quantifiers, as quote delimiters in `q*X*...*X*` (where *X* is the `chr()` of a large code point), and as the upper limits in loops.
The use of out of range code points was deprecated in Perl 5.24; as of Perl 5.28 using a code point exceeding `IV_MAX` throws a fatal error.
If your code is to run on various platforms, keep in mind that the upper limit depends on the platform. It is much larger on 64-bit word sizes than 32-bit ones. For 32-bit integers, `IV_MAX` equals `0x7FFFFFFF`, for 64-bit integers, `IV_MAX` equals `0x7FFFFFFFFFFFFFFF`.
####
Use of comma-less variable list in formats.
It was allowed to use a list of variables in a format, without separating them with commas. This usage has been deprecated for a long time, and as of Perl 5.28, this throws a fatal error.
####
Use of `\N{}`
Use of `\N{}` with nothing between the braces was deprecated in Perl 5.24, and throws a fatal error as of Perl 5.28.
Since such a construct is equivalent to using an empty string, you are recommended to remove such `\N{}` constructs.
####
Using the same symbol to open a filehandle and a dirhandle
It used to be legal to use `open()` to associate both a filehandle and a dirhandle to the same symbol (glob or scalar). This idiom is likely to be confusing, and it was deprecated in Perl 5.10.
Using the same symbol to `open()` a filehandle and a dirhandle throws a fatal error as of Perl 5.28.
You should be using two different symbols instead.
####
${^ENCODING} is no longer supported.
The special variable `${^ENCODING}` was used to implement the `encoding` pragma. Setting this variable to anything other than `undef` was deprecated in Perl 5.22. Full deprecation of the variable happened in Perl 5.25.3.
Setting this variable to anything other than an undefined value throws a fatal error as of Perl 5.28.
####
`B::OP::terse`
This method, which just calls `B::Concise::b_terse`, has been deprecated, and disappeared in Perl 5.28. Please use `B::Concise` instead.
####
Use of inherited AUTOLOAD for non-method %s::%s() is no longer allowed
As an (ahem) accidental feature, `AUTOLOAD` subroutines were looked up as methods (using the `@ISA` hierarchy) even when the subroutines to be autoloaded were called as plain functions (e.g. `Foo::bar()`), not as methods (e.g. `Foo->bar()` or `$obj->bar()`).
This bug was deprecated in Perl 5.004, has been rectified in Perl 5.28 by using method lookup only for methods' `AUTOLOAD`s.
The simple rule is: Inheritance will not work when autoloading non-methods. The simple fix for old code is: In any module that used to depend on inheriting `AUTOLOAD` for non-methods from a base class named `BaseClass`, execute `*AUTOLOAD = \&BaseClass::AUTOLOAD` during startup.
In code that currently says `use AutoLoader; @ISA = qw(AutoLoader);` you should remove AutoLoader from @ISA and change `use AutoLoader;` to `use AutoLoader 'AUTOLOAD';`.
####
Use of code points over 0xFF in string bitwise operators
The string bitwise operators, `&`, `|`, `^`, and `~`, treat their operands as strings of bytes. As such, values above 0xFF are nonsensical. Using such code points with these operators was deprecated in Perl 5.24, and is fatal as of Perl 5.28.
####
In XS code, use of `to_utf8_case()`
This function has been removed as of Perl 5.28; instead convert to call the appropriate one of: [`toFOLD_utf8_safe`](perlapi#toFOLD_utf8_safe). [`toLOWER_utf8_safe`](perlapi#toLOWER_utf8_safe), [`toTITLE_utf8_safe`](perlapi#toTITLE_utf8_safe), or [`toUPPER_utf8_safe`](perlapi#toUPPER_utf8_safe).
###
Perl 5.26
####
`--libpods` in `Pod::Html`
Since Perl 5.18, the option `--libpods` has been deprecated, and using this option did not do anything other than producing a warning.
The `--libpods` option is no longer recognized as of Perl 5.26.
####
The utilities `c2ph` and `pstruct`
These old, perl3-era utilities have been deprecated in favour of `h2xs` for a long time. As of Perl 5.26, they have been removed.
####
Trapping `$SIG {__DIE__}` other than during program exit.
The `$SIG{__DIE__}` hook is called even inside an `eval()`. It was never intended to happen this way, but an implementation glitch made this possible. This used to be deprecated, as it allowed strange action at a distance like rewriting a pending exception in `$@`. Plans to rectify this have been scrapped, as users found that rewriting a pending exception is actually a useful feature, and not a bug.
Perl never issued a deprecation warning for this; the deprecation was by documentation policy only. But this deprecation has been lifted as of Perl 5.26.
####
Malformed UTF-8 string in "%s"
This message indicates a bug either in the Perl core or in XS code. Such code was trying to find out if a character, allegedly stored internally encoded as UTF-8, was of a given type, such as being punctuation or a digit. But the character was not encoded in legal UTF-8. The `%s` is replaced by a string that can be used by knowledgeable people to determine what the type being checked against was.
Passing malformed strings was deprecated in Perl 5.18, and became fatal in Perl 5.26.
###
Perl 5.24
####
Use of `*glob{FILEHANDLE}`
The use of `*glob{FILEHANDLE}` was deprecated in Perl 5.8. The intention was to use `*glob{IO}` instead, for which `*glob{FILEHANDLE}` is an alias.
However, this feature was undeprecated in Perl 5.24.
####
Calling POSIX::%s() is deprecated
The following functions in the `POSIX` module are no longer available: `isalnum`, `isalpha`, `iscntrl`, `isdigit`, `isgraph`, `islower`, `isprint`, `ispunct`, `isspace`, `isupper`, and `isxdigit`. The functions are buggy and don't work on UTF-8 encoded strings. See their entries in [POSIX](posix) for more information.
The functions were deprecated in Perl 5.20, and removed in Perl 5.24.
###
Perl 5.16
####
Use of %s on a handle without \* is deprecated
It used to be possible to use `tie`, `tied` or `untie` on a scalar while the scalar holds a typeglob. This caused its filehandle to be tied. It left no way to tie the scalar itself when it held a typeglob, and no way to untie a scalar that had had a typeglob assigned to it.
This was deprecated in Perl 5.14, and the bug was fixed in Perl 5.16.
So now `tie $scalar` will always tie the scalar, not the handle it holds. To tie the handle, use `tie *$scalar` (with an explicit asterisk). The same applies to `tied *$scalar` and `untie *$scalar`.
SEE ALSO
---------
<warnings>, <diagnostics>.
| programming_docs |
perl Test2::API::InterceptResult::Squasher Test2::API::InterceptResult::Squasher
=====================================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::InterceptResult::Squasher - Encapsulation of the algorithm that squashes diags into assertions.
DESCRIPTION
-----------
Internal use only, please ignore.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl ops ops
===
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ops - Perl pragma to restrict unsafe operations when compiling
SYNOPSIS
--------
```
perl -Mops=:default ... # only allow reasonably safe operations
perl -M-ops=system ... # disable the 'system' opcode
```
DESCRIPTION
-----------
Since the `ops` pragma currently has an irreversible global effect, it is only of significant practical use with the `-M` option on the command line.
See the [Opcode](opcode) module for information about opcodes, optags, opmasks and important information about safety.
SEE ALSO
---------
[Opcode](opcode), [Safe](safe), <perlrun>
perl Test2::EventFacet::Render Test2::EventFacet::Render
=========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Render - Facet that dictates how to render an event.
DESCRIPTION
-----------
This facet is used to dictate how the event should be rendered by the standard test2 rendering tools. If this facet is present then ONLY what is specified by it will be rendered. It is assumed that anything important or note-worthy will be present here, no other facets will be considered for rendering/display.
This facet is a list type, you can add as many items as needed.
FIELDS
------
$string = $render->[#]->{details}
$string = $render->[#]->details() Human readable text for display.
$string = $render->[#]->{tag}
$string = $render->[#]->tag() Tag that should prefix/identify the main text.
$string = $render->[#]->{facet}
$string = $render->[#]->facet() Optional, if the display text was generated from another facet this should state what facet it was.
$mode = $render->[#]->{mode}
$mode = $render->[#]->mode() calculated Calculated means the facet was generated from another facet. Calculated facets may be cleared and regenerated whenever the event state changes.
replace Replace means the facet is intended to replace the normal rendering of the event.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl attributes attributes
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [What import does](#What-import-does)
+ [Built-in Attributes](#Built-in-Attributes)
+ [Available Subroutines](#Available-Subroutines)
+ [Package-specific Attribute Handling](#Package-specific-Attribute-Handling)
+ [Syntax of Attribute Lists](#Syntax-of-Attribute-Lists)
* [EXPORTS](#EXPORTS)
+ [Default exports](#Default-exports)
+ [Available exports](#Available-exports)
+ [Export tags defined](#Export-tags-defined)
* [EXAMPLES](#EXAMPLES)
* [MORE EXAMPLES](#MORE-EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
NAME
----
attributes - get/set subroutine or variable attributes
SYNOPSIS
--------
```
sub foo : method ;
my ($x,@y,%z) : Bent = 1;
my $s = sub : method { ... };
use attributes (); # optional, to get subroutine declarations
my @attrlist = attributes::get(\&foo);
use attributes 'get'; # import the attributes::get subroutine
my @attrlist = get \&foo;
```
DESCRIPTION
-----------
Subroutine declarations and definitions may optionally have attribute lists associated with them. (Variable `my` declarations also may, but see the warning below.) Perl handles these declarations by passing some information about the call site and the thing being declared along with the attribute list to this module. In particular, the first example above is equivalent to the following:
```
use attributes __PACKAGE__, \&foo, 'method';
```
The second example in the synopsis does something equivalent to this:
```
use attributes ();
my ($x,@y,%z);
attributes::->import(__PACKAGE__, \$x, 'Bent');
attributes::->import(__PACKAGE__, \@y, 'Bent');
attributes::->import(__PACKAGE__, \%z, 'Bent');
($x,@y,%z) = 1;
```
Yes, that's a lot of expansion.
**WARNING**: attribute declarations for variables are still evolving. The semantics and interfaces of such declarations could change in future versions. They are present for purposes of experimentation with what the semantics ought to be. Do not rely on the current implementation of this feature.
There are only a few attributes currently handled by Perl itself (or directly by this module, depending on how you look at it.) However, package-specific attributes are allowed by an extension mechanism. (See ["Package-specific Attribute Handling"](#Package-specific-Attribute-Handling) below.)
The setting of subroutine attributes happens at compile time. Variable attributes in `our` declarations are also applied at compile time. However, `my` variables get their attributes applied at run-time. This means that you have to *reach* the run-time component of the `my` before those attributes will get applied. For example:
```
my $x : Bent = 42 if 0;
```
will neither assign 42 to $x *nor* will it apply the `Bent` attribute to the variable.
An attempt to set an unrecognized attribute is a fatal error. (The error is trappable, but it still stops the compilation within that `eval`.) Setting an attribute with a name that's all lowercase letters that's not a built-in attribute (such as "foo") will result in a warning with **-w** or `use warnings 'reserved'`.
###
What `import` does
In the description it is mentioned that
```
sub foo : method;
```
is equivalent to
```
use attributes __PACKAGE__, \&foo, 'method';
```
As you might know this calls the `import` function of `attributes` at compile time with these parameters: 'attributes', the caller's package name, the reference to the code and 'method'.
```
attributes->import( __PACKAGE__, \&foo, 'method' );
```
So you want to know what `import` actually does?
First of all `import` gets the type of the third parameter ('CODE' in this case). `attributes.pm` checks if there is a subroutine called `MODIFY_<reftype>_ATTRIBUTES` in the caller's namespace (here: 'main'). In this case a subroutine `MODIFY_CODE_ATTRIBUTES` is required. Then this method is called to check if you have used a "bad attribute". The subroutine call in this example would look like
```
MODIFY_CODE_ATTRIBUTES( 'main', \&foo, 'method' );
```
`MODIFY_<reftype>_ATTRIBUTES` has to return a list of all "bad attributes". If there are any bad attributes `import` croaks.
(See ["Package-specific Attribute Handling"](#Package-specific-Attribute-Handling) below.)
###
Built-in Attributes
The following are the built-in attributes for subroutines:
lvalue Indicates that the referenced subroutine is a valid lvalue and can be assigned to. The subroutine must return a modifiable value such as a scalar variable, as described in <perlsub>.
This module allows one to set this attribute on a subroutine that is already defined. For Perl subroutines (XSUBs are fine), it may or may not do what you want, depending on the code inside the subroutine, with details subject to change in future Perl versions. You may run into problems with lvalue context not being propagated properly into the subroutine, or maybe even assertion failures. For this reason, a warning is emitted if warnings are enabled. In other words, you should only do this if you really know what you are doing. You have been warned.
method Indicates that the referenced subroutine is a method. A subroutine so marked will not trigger the "Ambiguous call resolved as CORE::%s" warning.
prototype(..) The "prototype" attribute is an alternate means of specifying a prototype on a sub. The desired prototype is within the parens.
The prototype from the attribute is assigned to the sub immediately after the prototype from the sub, which means that if both are declared at the same time, the traditionally defined prototype is ignored. In other words, `sub foo($$) : prototype(@) {}` is indistinguishable from `sub foo(@){}`.
If illegalproto warnings are enabled, the prototype declared inside this attribute will be sanity checked at compile time.
const This experimental attribute, introduced in Perl 5.22, only applies to anonymous subroutines. It causes the subroutine to be called as soon as the `sub` expression is evaluated. The return value is captured and turned into a constant subroutine.
The following are the built-in attributes for variables:
shared Indicates that the referenced variable can be shared across different threads when used in conjunction with the <threads> and <threads::shared> modules.
###
Available Subroutines
The following subroutines are available for general use once this module has been loaded:
get This routine expects a single parameter--a reference to a subroutine or variable. It returns a list of attributes, which may be empty. If passed invalid arguments, it uses die() (via [Carp::croak](carp)) to raise a fatal exception. If it can find an appropriate package name for a class method lookup, it will include the results from a `FETCH_*type*_ATTRIBUTES` call in its return list, as described in ["Package-specific Attribute Handling"](#Package-specific-Attribute-Handling) below. Otherwise, only [built-in attributes](#Built-in-Attributes) will be returned.
reftype This routine expects a single parameter--a reference to a subroutine or variable. It returns the built-in type of the referenced variable, ignoring any package into which it might have been blessed. This can be useful for determining the *type* value which forms part of the method names described in ["Package-specific Attribute Handling"](#Package-specific-Attribute-Handling) below.
Note that these routines are *not* exported by default.
###
Package-specific Attribute Handling
**WARNING**: the mechanisms described here are still experimental. Do not rely on the current implementation. In particular, there is no provision for applying package attributes to 'cloned' copies of subroutines used as closures. (See ["Making References" in perlref](perlref#Making-References) for information on closures.) Package-specific attribute handling may change incompatibly in a future release.
When an attribute list is present in a declaration, a check is made to see whether an attribute 'modify' handler is present in the appropriate package (or its @ISA inheritance tree). Similarly, when `attributes::get` is called on a valid reference, a check is made for an appropriate attribute 'fetch' handler. See ["EXAMPLES"](#EXAMPLES) to see how the "appropriate package" determination works.
The handler names are based on the underlying type of the variable being declared or of the reference passed. Because these attributes are associated with subroutine or variable declarations, this deliberately ignores any possibility of being blessed into some package. Thus, a subroutine declaration uses "CODE" as its *type*, and even a blessed hash reference uses "HASH" as its *type*.
The class methods invoked for modifying and fetching are these:
FETCH\_*type*\_ATTRIBUTES This method is called with two arguments: the relevant package name, and a reference to a variable or subroutine for which package-defined attributes are desired. The expected return value is a list of associated attributes. This list may be empty.
MODIFY\_*type*\_ATTRIBUTES This method is called with two fixed arguments, followed by the list of attributes from the relevant declaration. The two fixed arguments are the relevant package name and a reference to the declared subroutine or variable. The expected return value is a list of attributes which were not recognized by this handler. Note that this allows for a derived class to delegate a call to its base class, and then only examine the attributes which the base class didn't already handle for it.
The call to this method is currently made *during* the processing of the declaration. In particular, this means that a subroutine reference will probably be for an undefined subroutine, even if this declaration is actually part of the definition.
Calling `attributes::get()` from within the scope of a null package declaration `package ;` for an unblessed variable reference will not provide any starting package name for the 'fetch' method lookup. Thus, this circumstance will not result in a method call for package-defined attributes. A named subroutine knows to which symbol table entry it belongs (or originally belonged), and it will use the corresponding package. An anonymous subroutine knows the package name into which it was compiled (unless it was also compiled with a null package declaration), and so it will use that package name.
###
Syntax of Attribute Lists
An attribute list is a sequence of attribute specifications, separated by whitespace or a colon (with optional whitespace). Each attribute specification is a simple name, optionally followed by a parenthesised parameter list. If such a parameter list is present, it is scanned past as for the rules for the `q()` operator. (See ["Quote and Quote-like Operators" in perlop](perlop#Quote-and-Quote-like-Operators).) The parameter list is passed as it was found, however, and not as per `q()`.
Some examples of syntactically valid attribute lists:
```
switch(10,foo(7,3)) : expensive
Ugly('\(") :Bad
_5x5
lvalue method
```
Some examples of syntactically invalid attribute lists (with annotation):
```
switch(10,foo() # ()-string not balanced
Ugly('(') # ()-string not balanced
5x5 # "5x5" not a valid identifier
Y2::north # "Y2::north" not a simple identifier
foo + bar # "+" neither a colon nor whitespace
```
EXPORTS
-------
###
Default exports
None.
###
Available exports
The routines `get` and `reftype` are exportable.
###
Export tags defined
The `:ALL` tag will get all of the above exports.
EXAMPLES
--------
Here are some samples of syntactically valid declarations, with annotation as to how they resolve internally into `use attributes` invocations by perl. These examples are primarily useful to see how the "appropriate package" is found for the possible method lookups for package-defined attributes.
1. Code:
```
package Canine;
package Dog;
my Canine $spot : Watchful ;
```
Effect:
```
use attributes ();
attributes::->import(Canine => \$spot, "Watchful");
```
2. Code:
```
package Felis;
my $cat : Nervous;
```
Effect:
```
use attributes ();
attributes::->import(Felis => \$cat, "Nervous");
```
3. Code:
```
package X;
sub foo : lvalue ;
```
Effect:
```
use attributes X => \&foo, "lvalue";
```
4. Code:
```
package X;
sub Y::x : lvalue { 1 }
```
Effect:
```
use attributes Y => \&Y::x, "lvalue";
```
5. Code:
```
package X;
sub foo { 1 }
package Y;
BEGIN { *bar = \&X::foo; }
package Z;
sub Y::bar : lvalue ;
```
Effect:
```
use attributes X => \&X::foo, "lvalue";
```
This last example is purely for purposes of completeness. You should not be trying to mess with the attributes of something in a package that's not your own.
MORE EXAMPLES
--------------
1. ```
sub MODIFY_CODE_ATTRIBUTES {
my ($class,$code,@attrs) = @_;
my $allowed = 'MyAttribute';
my @bad = grep { $_ ne $allowed } @attrs;
return @bad;
}
sub foo : MyAttribute {
print "foo\n";
}
```
This example runs. At compile time `MODIFY_CODE_ATTRIBUTES` is called. In that subroutine, we check if any attribute is disallowed and we return a list of these "bad attributes".
As we return an empty list, everything is fine.
2. ```
sub MODIFY_CODE_ATTRIBUTES {
my ($class,$code,@attrs) = @_;
my $allowed = 'MyAttribute';
my @bad = grep{ $_ ne $allowed }@attrs;
return @bad;
}
sub foo : MyAttribute Test {
print "foo\n";
}
```
This example is aborted at compile time as we use the attribute "Test" which isn't allowed. `MODIFY_CODE_ATTRIBUTES` returns a list that contains a single element ('Test').
SEE ALSO
---------
["Private Variables via my()" in perlsub](perlsub#Private-Variables-via-my%28%29) and ["Subroutine Attributes" in perlsub](perlsub#Subroutine-Attributes) for details on the basic declarations; ["use" in perlfunc](perlfunc#use) for details on the normal invocation mechanism.
perl Pod::Simple::LinkSection Pod::Simple::LinkSection
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::LinkSection -- represent "section" attributes of L codes
SYNOPSIS
--------
```
# a long story
```
DESCRIPTION
-----------
This class is not of interest to general users.
Pod::Simple uses this class for representing the value of the "section" attribute of "L" start-element events. Most applications can just use the normal stringification of objects of this class; they stringify to just the text content of the section, such as "foo" for `L<Stuff/foo>`, and "bar" for `L<Stuff/bI<ar>>`.
However, anyone particularly interested in getting the full value of the treelet, can just traverse the content of the treeleet @$treelet\_object. To wit:
```
% perl -MData::Dumper -e
"use base qw(Pod::Simple::Methody);
sub start_L { print Dumper($_[1]{'section'} ) }
__PACKAGE__->new->parse_string_document('=head1 L<Foo/bI<ar>baz>>')
"
Output:
$VAR1 = bless( [
'',
{},
'b',
bless( [
'I',
{},
'ar'
], 'Pod::Simple::LinkSection' ),
'baz'
], 'Pod::Simple::LinkSection' );
```
But stringify it and you get just the text content:
```
% perl -MData::Dumper -e
"use base qw(Pod::Simple::Methody);
sub start_L { print Dumper( '' . $_[1]{'section'} ) }
__PACKAGE__->new->parse_string_document('=head1 L<Foo/bI<ar>baz>>')
"
Output:
$VAR1 = 'barbaz';
```
SEE ALSO
---------
<Pod::Simple>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2004 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
| programming_docs |
perl Digest Digest
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OO INTERFACE](#OO-INTERFACE)
* [Digest speed](#Digest-speed)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
Digest - Modules that calculate message digests
SYNOPSIS
--------
```
$md5 = Digest->new("MD5");
$sha1 = Digest->new("SHA-1");
$sha256 = Digest->new("SHA-256");
$sha384 = Digest->new("SHA-384");
$sha512 = Digest->new("SHA-512");
$hmac = Digest->HMAC_MD5($key);
```
DESCRIPTION
-----------
The `Digest::` modules calculate digests, also called "fingerprints" or "hashes", of some data, called a message. The digest is (usually) some small/fixed size string. The actual size of the digest depend of the algorithm used. The message is simply a sequence of arbitrary bytes or bits.
An important property of the digest algorithms is that the digest is *likely* to change if the message change in some way. Another property is that digest functions are one-way functions, that is it should be *hard* to find a message that correspond to some given digest. Algorithms differ in how "likely" and how "hard", as well as how efficient they are to compute.
Note that the properties of the algorithms change over time, as the algorithms are analyzed and machines grow faster. If your application for instance depends on it being "impossible" to generate the same digest for a different message it is wise to make it easy to plug in stronger algorithms as the one used grow weaker. Using the interface documented here should make it easy to change algorithms later.
All `Digest::` modules provide the same programming interface. A functional interface for simple use, as well as an object oriented interface that can handle messages of arbitrary length and which can read files directly.
The digest can be delivered in three formats:
*binary* This is the most compact form, but it is not well suited for printing or embedding in places that can't handle arbitrary data.
*hex* A twice as long string of lowercase hexadecimal digits.
*base64* A string of portable printable characters. This is the base64 encoded representation of the digest with any trailing padding removed. The string will be about 30% longer than the binary version. <MIME::Base64> tells you more about this encoding.
The functional interface is simply importable functions with the same name as the algorithm. The functions take the message as argument and return the digest. Example:
```
use Digest::MD5 qw(md5);
$digest = md5($message);
```
There are also versions of the functions with "\_hex" or "\_base64" appended to the name, which returns the digest in the indicated form.
OO INTERFACE
-------------
The following methods are available for all `Digest::` modules:
$ctx = Digest->XXX($arg,...)
$ctx = Digest->new(XXX => $arg,...)
$ctx = Digest::XXX->new($arg,...) The constructor returns some object that encapsulate the state of the message-digest algorithm. You can add data to the object and finally ask for the digest. The "XXX" should of course be replaced by the proper name of the digest algorithm you want to use.
The two first forms are simply syntactic sugar which automatically load the right module on first use. The second form allow you to use algorithm names which contains letters which are not legal perl identifiers, e.g. "SHA-1". If no implementation for the given algorithm can be found, then an exception is raised.
To know what arguments (if any) the constructor takes (the `$args,...` above) consult the docs for the specific digest implementation.
If new() is called as an instance method (i.e. $ctx->new) it will just reset the state the object to the state of a newly created object. No new object is created in this case, and the return value is the reference to the object (i.e. $ctx).
$other\_ctx = $ctx->clone The clone method creates a copy of the digest state object and returns a reference to the copy.
$ctx->reset This is just an alias for $ctx->new.
$ctx->add( $data )
$ctx->add( $chunk1, $chunk2, ... ) The string value of the $data provided as argument is appended to the message we calculate the digest for. The return value is the $ctx object itself.
If more arguments are provided then they are all appended to the message, thus all these lines will have the same effect on the state of the $ctx object:
```
$ctx->add("a"); $ctx->add("b"); $ctx->add("c");
$ctx->add("a")->add("b")->add("c");
$ctx->add("a", "b", "c");
$ctx->add("abc");
```
Most algorithms are only defined for strings of bytes and this method might therefore croak if the provided arguments contain chars with ordinal number above 255.
$ctx->addfile( $io\_handle ) The $io\_handle is read until EOF and the content is appended to the message we calculate the digest for. The return value is the $ctx object itself.
The addfile() method will croak() if it fails reading data for some reason. If it croaks it is unpredictable what the state of the $ctx object will be in. The addfile() method might have been able to read the file partially before it failed. It is probably wise to discard or reset the $ctx object if this occurs.
In most cases you want to make sure that the $io\_handle is in "binmode" before you pass it as argument to the addfile() method.
$ctx->add\_bits( $data, $nbits )
$ctx->add\_bits( $bitstring ) The add\_bits() method is an alternative to add() that allow partial bytes to be appended to the message. Most users can just ignore this method since typical applications involve only whole-byte data.
The two argument form of add\_bits() will add the first $nbits bits from $data. For the last potentially partial byte only the high order `$nbits % 8` bits are used. If $nbits is greater than `length($data) * 8`, then this method would do the same as `$ctx->add($data)`.
The one argument form of add\_bits() takes a $bitstring of "1" and "0" chars as argument. It's a shorthand for `$ctx->add_bits(pack("B*", $bitstring), length($bitstring))`.
The return value is the $ctx object itself.
This example shows two calls that should have the same effect:
```
$ctx->add_bits("111100001010");
$ctx->add_bits("\xF0\xA0", 12);
```
Most digest algorithms are byte based and for these it is not possible to add bits that are not a multiple of 8, and the add\_bits() method will croak if you try.
$ctx->digest Return the binary digest for the message.
Note that the `digest` operation is effectively a destructive, read-once operation. Once it has been performed, the $ctx object is automatically `reset` and can be used to calculate another digest value. Call $ctx->clone->digest if you want to calculate the digest without resetting the digest state.
$ctx->hexdigest Same as $ctx->digest, but will return the digest in hexadecimal form.
$ctx->b64digest Same as $ctx->digest, but will return the digest as a base64 encoded string without padding.
$ctx->base64\_padded\_digest Same as $ctx->digest, but will return the digest as a base64 encoded string.
Digest speed
-------------
This table should give some indication on the relative speed of different algorithms. It is sorted by throughput based on a benchmark done with of some implementations of this API:
```
Algorithm Size Implementation MB/s
MD4 128 Digest::MD4 v1.3 165.0
MD5 128 Digest::MD5 v2.33 98.8
SHA-256 256 Digest::SHA2 v1.1.0 66.7
SHA-1 160 Digest::SHA v4.3.1 58.9
SHA-1 160 Digest::SHA1 v2.10 48.8
SHA-256 256 Digest::SHA v4.3.1 41.3
Haval-256 256 Digest::Haval256 v1.0.4 39.8
SHA-384 384 Digest::SHA2 v1.1.0 19.6
SHA-512 512 Digest::SHA2 v1.1.0 19.3
SHA-384 384 Digest::SHA v4.3.1 19.2
SHA-512 512 Digest::SHA v4.3.1 19.2
Whirlpool 512 Digest::Whirlpool v1.0.2 13.0
MD2 128 Digest::MD2 v2.03 9.5
Adler-32 32 Digest::Adler32 v0.03 1.3
CRC-16 16 Digest::CRC v0.05 1.1
CRC-32 32 Digest::CRC v0.05 1.1
MD5 128 Digest::Perl::MD5 v1.5 1.0
CRC-CCITT 16 Digest::CRC v0.05 0.8
```
These numbers was achieved Apr 2004 with ActivePerl-5.8.3 running under Linux on a P4 2.8 GHz CPU. The last 5 entries differ by being pure perl implementations of the algorithms, which explains why they are so slow.
SEE ALSO
---------
<Digest::Adler32>, <Digest::CRC>, <Digest::Haval256>, <Digest::HMAC>, <Digest::MD2>, <Digest::MD4>, <Digest::MD5>, <Digest::SHA>, <Digest::SHA1>, <Digest::SHA2>, <Digest::Whirlpool>
New digest implementations should consider subclassing from <Digest::base>.
<MIME::Base64>
http://en.wikipedia.org/wiki/Cryptographic\_hash\_function
AUTHOR
------
Gisle Aas <[email protected]>
The `Digest::` interface is based on the interface originally developed by Neil Winton for his `MD5` module.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
```
Copyright 1998-2006 Gisle Aas.
Copyright 1995,1996 Neil Winton.
```
perl File::Copy File::Copy
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [RETURN](#RETURN)
* [NOTES](#NOTES)
* [AUTHOR](#AUTHOR)
NAME
----
File::Copy - Copy files or filehandles
SYNOPSIS
--------
```
use File::Copy;
copy("sourcefile","destinationfile") or die "Copy failed: $!";
copy("Copy.pm",\*STDOUT);
move("/dev1/sourcefile","/dev2/destinationfile");
use File::Copy "cp";
$n = FileHandle->new("/a/file","r");
cp($n,"x");
```
DESCRIPTION
-----------
The File::Copy module provides two basic functions, `copy` and `move`, which are useful for getting the contents of a file from one place to another.
copy The `copy` function takes two parameters: a file to copy from and a file to copy to. Either argument may be a string, a FileHandle reference or a FileHandle glob. Obviously, if the first argument is a filehandle of some sort, it will be read from, and if it is a file *name* it will be opened for reading. Likewise, the second argument will be written to. If the second argument does not exist but the parent directory does exist, then it will be created. Trying to copy a file into a non-existent directory is an error. Trying to copy a file on top of itself is also an error. `copy` will not overwrite read-only files.
If the destination (second argument) already exists and is a directory, and the source (first argument) is not a filehandle, then the source file will be copied into the directory specified by the destination, using the same base name as the source file. It's a failure to have a filehandle as the source when the destination is a directory.
**Note that passing in files as handles instead of names may lead to loss of information on some operating systems; it is recommended that you use file names whenever possible.** Files are opened in binary mode where applicable. To get a consistent behaviour when copying from a filehandle to a file, use `binmode` on the filehandle.
An optional third parameter can be used to specify the buffer size used for copying. This is the number of bytes from the first file, that will be held in memory at any given time, before being written to the second file. The default buffer size depends upon the file, but will generally be the whole file (up to 2MB), or 1k for filehandles that do not reference files (eg. sockets).
You may use the syntax `use File::Copy "cp"` to get at the `cp` alias for this function. The syntax is *exactly* the same. The behavior is nearly the same as well: as of version 2.15, `cp` will preserve the source file's permission bits like the shell utility `cp(1)` would do, while `copy` uses the default permissions for the target file (which may depend on the process' `umask`, file ownership, inherited ACLs, etc.). If an error occurs in setting permissions, `cp` will return 0, regardless of whether the file was successfully copied.
move The `move` function also takes two parameters: the current name and the intended name of the file to be moved. If the destination already exists and is a directory, and the source is not a directory, then the source file will be renamed into the directory specified by the destination.
If possible, move() will simply rename the file. Otherwise, it copies the file to the new location and deletes the original. If an error occurs during this copy-and-delete process, you may be left with a (possibly partial) copy of the file under the destination name.
You may use the `mv` alias for this function in the same way that you may use the `cp` alias for `copy`.
syscopy File::Copy also provides the `syscopy` routine, which copies the file specified in the first parameter to the file specified in the second parameter, preserving OS-specific attributes and file structure. For Unix systems, this is equivalent to the simple `copy` routine, which doesn't preserve OS-specific attributes. For VMS systems, this calls the `rmscopy` routine (see below). For OS/2 systems, this calls the `syscopy` XSUB directly. For Win32 systems, this calls `Win32::CopyFile`.
**Special behaviour if `syscopy` is defined (OS/2, VMS and Win32)**:
If both arguments to `copy` are not file handles, then `copy` will perform a "system copy" of the input file to a new output file, in order to preserve file attributes, indexed file structure, *etc.* The buffer size parameter is ignored. If either argument to `copy` is a handle to an opened file, then data is copied using Perl operators, and no effort is made to preserve file attributes or record structure.
The system copy routine may also be called directly under VMS and OS/2 as `File::Copy::syscopy` (or under VMS as `File::Copy::rmscopy`, which is the routine that does the actual work for syscopy).
rmscopy($from,$to[,$date\_flag]) The first and second arguments may be strings, typeglobs, typeglob references, or objects inheriting from IO::Handle; they are used in all cases to obtain the *filespec* of the input and output files, respectively. The name and type of the input file are used as defaults for the output file, if necessary.
A new version of the output file is always created, which inherits the structure and RMS attributes of the input file, except for owner and protections (and possibly timestamps; see below). All data from the input file is copied to the output file; if either of the first two parameters to `rmscopy` is a file handle, its position is unchanged. (Note that this means a file handle pointing to the output file will be associated with an old version of that file after `rmscopy` returns, not the newly created version.)
The third parameter is an integer flag, which tells `rmscopy` how to handle timestamps. If it is < 0, none of the input file's timestamps are propagated to the output file. If it is > 0, then it is interpreted as a bitmask: if bit 0 (the LSB) is set, then timestamps other than the revision date are propagated; if bit 1 is set, the revision date is propagated. If the third parameter to `rmscopy` is 0, then it behaves much like the DCL COPY command: if the name or type of the output file was explicitly specified, then no timestamps are propagated, but if they were taken implicitly from the input filespec, then all timestamps other than the revision date are propagated. If this parameter is not supplied, it defaults to 0.
`rmscopy` is VMS specific and cannot be exported; it must be referenced by its full name, e.g.:
```
File::Copy::rmscopy($from, $to) or die $!;
```
Like `copy`, `rmscopy` returns 1 on success. If an error occurs, it sets `$!`, deletes the output file, and returns 0.
RETURN
------
All functions return 1 on success, 0 on failure. $! will be set if an error was encountered.
NOTES
-----
Before calling copy() or move() on a filehandle, the caller should close or flush() the file to avoid writes being lost. Note that this is the case even for move(), because it may actually copy the file, depending on the OS-specific implementation, and the underlying filesystem(s).
AUTHOR
------
File::Copy was written by Aaron Sherman *<[email protected]>* in 1995, and updated by Charles Bailey *<[email protected]>* in 1996.
perl Test::More Test::More
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [I love it when a plan comes together](#I-love-it-when-a-plan-comes-together)
+ [Test names](#Test-names)
+ [I'm ok, you're not ok.](#I'm-ok,-you're-not-ok.)
+ [Module tests](#Module-tests)
+ [Complex data structures](#Complex-data-structures)
+ [Diagnostics](#Diagnostics)
+ [Conditional tests](#Conditional-tests)
+ [Test control](#Test-control)
+ [Discouraged comparison functions](#Discouraged-comparison-functions)
+ [Extending and Embedding Test::More](#Extending-and-Embedding-Test::More)
* [EXIT CODES](#EXIT-CODES)
* [COMPATIBILITY](#COMPATIBILITY)
* [CAVEATS and NOTES](#CAVEATS-and-NOTES)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
+ [ALTERNATIVES](#ALTERNATIVES)
+ [ADDITIONAL LIBRARIES](#ADDITIONAL-LIBRARIES)
+ [OTHER COMPONENTS](#OTHER-COMPONENTS)
+ [BUNDLES](#BUNDLES)
* [AUTHORS](#AUTHORS)
* [MAINTAINERS](#MAINTAINERS)
* [BUGS](#BUGS)
* [SOURCE](#SOURCE)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::More - yet another framework for writing test scripts
SYNOPSIS
--------
```
use Test::More tests => 23;
# or
use Test::More skip_all => $reason;
# or
use Test::More; # see done_testing()
require_ok( 'Some::Module' );
# Various ways to say "ok"
ok($got eq $expected, $test_name);
is ($got, $expected, $test_name);
isnt($got, $expected, $test_name);
# Rather than print STDERR "# here's what went wrong\n"
diag("here's what went wrong");
like ($got, qr/expected/, $test_name);
unlike($got, qr/expected/, $test_name);
cmp_ok($got, '==', $expected, $test_name);
is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
SKIP: {
skip $why, $how_many unless $have_some_feature;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
TODO: {
local $TODO = $why;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
can_ok($module, @methods);
isa_ok($object, $class);
pass($test_name);
fail($test_name);
BAIL_OUT($why);
# UNIMPLEMENTED!!!
my @status = Test::More::status;
```
DESCRIPTION
-----------
**STOP!** If you're just getting started writing tests, have a look at <Test2::Suite> first.
This is a drop in replacement for Test::Simple which you can switch to once you get the hang of basic testing.
The purpose of this module is to provide a wide range of testing utilities. Various ways to say "ok" with better diagnostics, facilities to skip tests, test future features and compare complicated data structures. While you can do almost anything with a simple `ok()` function, it doesn't provide good diagnostic output.
###
I love it when a plan comes together
Before anything else, you need a testing plan. This basically declares how many tests your script is going to run to protect against premature failure.
The preferred way to do this is to declare a plan when you `use Test::More`.
```
use Test::More tests => 23;
```
There are cases when you will not know beforehand how many tests your script is going to run. In this case, you can declare your tests at the end.
```
use Test::More;
... run your tests ...
done_testing( $number_of_tests_run );
```
**NOTE** `done_testing()` should never be called in an `END { ... }` block.
Sometimes you really don't know how many tests were run, or it's too difficult to calculate. In which case you can leave off $number\_of\_tests\_run.
In some cases, you'll want to completely skip an entire testing script.
```
use Test::More skip_all => $skip_reason;
```
Your script will declare a skip with the reason why you skipped and exit immediately with a zero (success). See <Test::Harness> for details.
If you want to control what functions Test::More will export, you have to use the 'import' option. For example, to import everything but 'fail', you'd do:
```
use Test::More tests => 23, import => ['!fail'];
```
Alternatively, you can use the `plan()` function. Useful for when you have to calculate the number of tests.
```
use Test::More;
plan tests => keys %Stuff * 3;
```
or for deciding between running the tests at all:
```
use Test::More;
if( $^O eq 'MacOS' ) {
plan skip_all => 'Test irrelevant on MacOS';
}
else {
plan tests => 42;
}
```
**done\_testing**
```
done_testing();
done_testing($number_of_tests);
```
If you don't know how many tests you're going to run, you can issue the plan when you're done running tests.
$number\_of\_tests is the same as `plan()`, it's the number of tests you expected to run. You can omit this, in which case the number of tests you ran doesn't matter, just the fact that your tests ran to conclusion.
This is safer than and replaces the "no\_plan" plan.
**Note:** You must never put `done_testing()` inside an `END { ... }` block. The plan is there to ensure your test does not exit before testing has completed. If you use an END block you completely bypass this protection.
###
Test names
By convention, each test is assigned a number in order. This is largely done automatically for you. However, it's often very useful to assign a name to each test. Which would you rather see:
```
ok 4
not ok 5
ok 6
```
or
```
ok 4 - basic multi-variable
not ok 5 - simple exponential
ok 6 - force == mass * acceleration
```
The later gives you some idea of what failed. It also makes it easier to find the test in your script, simply search for "simple exponential".
All test functions take a name argument. It's optional, but highly suggested that you use it.
###
I'm ok, you're not ok.
The basic purpose of this module is to print out either "ok #" or "not ok #" depending on if a given test succeeded or failed. Everything else is just gravy.
All of the following print "ok" or "not ok" depending on if the test succeeded or failed. They all also return true or false, respectively.
**ok**
```
ok($got eq $expected, $test_name);
```
This simply evaluates any expression (`$got eq $expected` is just a simple example) and uses that to determine if the test succeeded or failed. A true expression passes, a false one fails. Very simple.
For example:
```
ok( $exp{9} == 81, 'simple exponential' );
ok( Film->can('db_Main'), 'set_db()' );
ok( $p->tests == 4, 'saw tests' );
ok( !grep(!defined $_, @items), 'all items defined' );
```
(Mnemonic: "This is ok.")
$test\_name is a very short description of the test that will be printed out. It makes it very easy to find a test in your script when it fails and gives others an idea of your intentions. $test\_name is optional, but we **very** strongly encourage its use.
Should an `ok()` fail, it will produce some diagnostics:
```
not ok 18 - sufficient mucus
# Failed test 'sufficient mucus'
# in foo.t at line 42.
```
This is the same as <Test::Simple>'s `ok()` routine.
**is** **isnt**
```
is ( $got, $expected, $test_name );
isnt( $got, $expected, $test_name );
```
Similar to `ok()`, `is()` and `isnt()` compare their two arguments with `eq` and `ne` respectively and use the result of that to determine if the test succeeded or failed. So these:
```
# Is the ultimate answer 42?
is( ultimate_answer(), 42, "Meaning of Life" );
# $foo isn't empty
isnt( $foo, '', "Got some foo" );
```
are similar to these:
```
ok( ultimate_answer() eq 42, "Meaning of Life" );
ok( $foo ne '', "Got some foo" );
```
`undef` will only ever match `undef`. So you can test a value against `undef` like this:
```
is($not_defined, undef, "undefined as expected");
```
(Mnemonic: "This is that." "This isn't that.")
So why use these? They produce better diagnostics on failure. `ok()` cannot know what you are testing for (beyond the name), but `is()` and `isnt()` know what the test was and why it failed. For example this test:
```
my $foo = 'waffle'; my $bar = 'yarblokos';
is( $foo, $bar, 'Is foo the same as bar?' );
```
Will produce something like this:
```
not ok 17 - Is foo the same as bar?
# Failed test 'Is foo the same as bar?'
# in foo.t at line 139.
# got: 'waffle'
# expected: 'yarblokos'
```
So you can figure out what went wrong without rerunning the test.
You are encouraged to use `is()` and `isnt()` over `ok()` where possible, however do not be tempted to use them to find out if something is true or false!
```
# XXX BAD!
is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
```
This does not check if `exists $brooklyn{tree}` is true, it checks if it returns 1. Very different. Similar caveats exist for false and 0. In these cases, use `ok()`.
```
ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
```
A simple call to `isnt()` usually does not provide a strong test but there are cases when you cannot say much more about a value than that it is different from some other value:
```
new_ok $obj, "Foo";
my $clone = $obj->clone;
isa_ok $obj, "Foo", "Foo->clone";
isnt $obj, $clone, "clone() produces a different object";
```
For those grammatical pedants out there, there's an `isn't()` function which is an alias of `isnt()`.
**like**
```
like( $got, qr/expected/, $test_name );
```
Similar to `ok()`, `like()` matches $got against the regex `qr/expected/`.
So this:
```
like($got, qr/expected/, 'this is like that');
```
is similar to:
```
ok( $got =~ m/expected/, 'this is like that');
```
(Mnemonic "This is like that".)
The second argument is a regular expression. It may be given as a regex reference (i.e. `qr//`) or (for better compatibility with older perls) as a string that looks like a regex (alternative delimiters are currently not supported):
```
like( $got, '/expected/', 'this is like that' );
```
Regex options may be placed on the end (`'/expected/i'`).
Its advantages over `ok()` are similar to that of `is()` and `isnt()`. Better diagnostics on failure.
**unlike**
```
unlike( $got, qr/expected/, $test_name );
```
Works exactly as `like()`, only it checks if $got **does not** match the given pattern.
**cmp\_ok**
```
cmp_ok( $got, $op, $expected, $test_name );
```
Halfway between `ok()` and `is()` lies `cmp_ok()`. This allows you to compare two arguments using any binary perl operator. The test passes if the comparison is true and fails otherwise.
```
# ok( $got eq $expected );
cmp_ok( $got, 'eq', $expected, 'this eq that' );
# ok( $got == $expected );
cmp_ok( $got, '==', $expected, 'this == that' );
# ok( $got && $expected );
cmp_ok( $got, '&&', $expected, 'this && that' );
...etc...
```
Its advantage over `ok()` is when the test fails you'll know what $got and $expected were:
```
not ok 1
# Failed test in foo.t at line 12.
# '23'
# &&
# undef
```
It's also useful in those cases where you are comparing numbers and `is()`'s use of `eq` will interfere:
```
cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
```
It's especially useful when comparing greater-than or smaller-than relation between values:
```
cmp_ok( $some_value, '<=', $upper_limit );
```
**can\_ok**
```
can_ok($module, @methods);
can_ok($object, @methods);
```
Checks to make sure the $module or $object can do these @methods (works with functions, too).
```
can_ok('Foo', qw(this that whatever));
```
is almost exactly like saying:
```
ok( Foo->can('this') &&
Foo->can('that') &&
Foo->can('whatever')
);
```
only without all the typing and with a better interface. Handy for quickly testing an interface.
No matter how many @methods you check, a single `can_ok()` call counts as one test. If you desire otherwise, use:
```
foreach my $meth (@methods) {
can_ok('Foo', $meth);
}
```
**isa\_ok**
```
isa_ok($object, $class, $object_name);
isa_ok($subclass, $class, $object_name);
isa_ok($ref, $type, $ref_name);
```
Checks to see if the given `$object->isa($class)`. Also checks to make sure the object was defined in the first place. Handy for this sort of thing:
```
my $obj = Some::Module->new;
isa_ok( $obj, 'Some::Module' );
```
where you'd otherwise have to write
```
my $obj = Some::Module->new;
ok( defined $obj && $obj->isa('Some::Module') );
```
to safeguard against your test script blowing up.
You can also test a class, to make sure that it has the right ancestor:
```
isa_ok( 'Vole', 'Rodent' );
```
It works on references, too:
```
isa_ok( $array_ref, 'ARRAY' );
```
The diagnostics of this test normally just refer to 'the object'. If you'd like them to be more specific, you can supply an $object\_name (for example 'Test customer').
**new\_ok**
```
my $obj = new_ok( $class );
my $obj = new_ok( $class => \@args );
my $obj = new_ok( $class => \@args, $object_name );
```
A convenience function which combines creating an object and calling `isa_ok()` on that object.
It is basically equivalent to:
```
my $obj = $class->new(@args);
isa_ok $obj, $class, $object_name;
```
If @args is not given, an empty list will be used.
This function only works on `new()` and it assumes `new()` will return just a single object which isa `$class`.
**subtest**
```
subtest $name => \&code, @args;
```
`subtest()` runs the &code as its own little test with its own plan and its own result. The main test counts this as a single test using the result of the whole subtest to determine if its ok or not ok.
For example...
```
use Test::More tests => 3;
pass("First test");
subtest 'An example subtest' => sub {
plan tests => 2;
pass("This is a subtest");
pass("So is this");
};
pass("Third test");
```
This would produce.
```
1..3
ok 1 - First test
# Subtest: An example subtest
1..2
ok 1 - This is a subtest
ok 2 - So is this
ok 2 - An example subtest
ok 3 - Third test
```
A subtest may call `skip_all`. No tests will be run, but the subtest is considered a skip.
```
subtest 'skippy' => sub {
plan skip_all => 'cuz I said so';
pass('this test will never be run');
};
```
Returns true if the subtest passed, false otherwise.
Due to how subtests work, you may omit a plan if you desire. This adds an implicit `done_testing()` to the end of your subtest. The following two subtests are equivalent:
```
subtest 'subtest with implicit done_testing()', sub {
ok 1, 'subtests with an implicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
};
subtest 'subtest with explicit done_testing()', sub {
ok 1, 'subtests with an explicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
done_testing();
};
```
Extra arguments given to `subtest` are passed to the callback. For example:
```
sub my_subtest {
my $range = shift;
...
}
for my $range (1, 10, 100, 1000) {
subtest "testing range $range", \&my_subtest, $range;
}
```
**pass** **fail**
```
pass($test_name);
fail($test_name);
```
Sometimes you just want to say that the tests have passed. Usually the case is you've got some complicated condition that is difficult to wedge into an `ok()`. In this case, you can simply use `pass()` (to declare the test ok) or fail (for not ok). They are synonyms for `ok(1)` and `ok(0)`.
Use these very, very, very sparingly.
###
Module tests
Sometimes you want to test if a module, or a list of modules, can successfully load. For example, you'll often want a first test which simply loads all the modules in the distribution to make sure they work before going on to do more complicated testing.
For such purposes we have `use_ok` and `require_ok`.
**require\_ok**
```
require_ok($module);
require_ok($file);
```
Tries to `require` the given $module or $file. If it loads successfully, the test will pass. Otherwise it fails and displays the load error.
`require_ok` will guess whether the input is a module name or a filename.
No exception will be thrown if the load fails.
```
# require Some::Module
require_ok "Some::Module";
# require "Some/File.pl";
require_ok "Some/File.pl";
# stop testing if any of your modules will not load
for my $module (@module) {
require_ok $module or BAIL_OUT "Can't load $module";
}
```
**use\_ok**
```
BEGIN { use_ok($module); }
BEGIN { use_ok($module, @imports); }
```
Like `require_ok`, but it will `use` the $module in question and only loads modules, not files.
If you just want to test a module can be loaded, use `require_ok`.
If you just want to load a module in a test, we recommend simply using `use` directly. It will cause the test to stop.
It's recommended that you run `use_ok()` inside a BEGIN block so its functions are exported at compile-time and prototypes are properly honored.
If @imports are given, they are passed through to the use. So this:
```
BEGIN { use_ok('Some::Module', qw(foo bar)) }
```
is like doing this:
```
use Some::Module qw(foo bar);
```
Version numbers can be checked like so:
```
# Just like "use Some::Module 1.02"
BEGIN { use_ok('Some::Module', 1.02) }
```
Don't try to do this:
```
BEGIN {
use_ok('Some::Module');
...some code that depends on the use...
...happening at compile time...
}
```
because the notion of "compile-time" is relative. Instead, you want:
```
BEGIN { use_ok('Some::Module') }
BEGIN { ...some code that depends on the use... }
```
If you want the equivalent of `use Foo ()`, use a module but not import anything, use `require_ok`.
```
BEGIN { require_ok "Foo" }
```
###
Complex data structures
Not everything is a simple eq check or regex. There are times you need to see if two data structures are equivalent. For these instances Test::More provides a handful of useful functions.
**NOTE** I'm not quite sure what will happen with filehandles.
**is\_deeply**
```
is_deeply( $got, $expected, $test_name );
```
Similar to `is()`, except that if $got and $expected are references, it does a deep comparison walking each data structure to see if they are equivalent. If the two structures are different, it will display the place where they start differing.
`is_deeply()` compares the dereferenced values of references, the references themselves (except for their type) are ignored. This means aspects such as blessing and ties are not considered "different".
`is_deeply()` currently has very limited handling of function reference and globs. It merely checks if they have the same referent. This may improve in the future.
<Test::Differences> and <Test::Deep> provide more in-depth functionality along these lines.
**NOTE** is\_deeply() has limitations when it comes to comparing strings and refs:
```
my $path = path('.');
my $hash = {};
is_deeply( $path, "$path" ); # ok
is_deeply( $hash, "$hash" ); # fail
```
This happens because is\_deeply will unoverload all arguments unconditionally. It is probably best not to use is\_deeply with overloading. For legacy reasons this is not likely to ever be fixed. If you would like a much better tool for this you should see <Test2::Suite> Specifically <Test2::Tools::Compare> has an `is()` function that works like `is_deeply` with many improvements.
### Diagnostics
If you pick the right test function, you'll usually get a good idea of what went wrong when it failed. But sometimes it doesn't work out that way. So here we have ways for you to write your own diagnostic messages which are safer than just `print STDERR`.
**diag**
```
diag(@diagnostic_message);
```
Prints a diagnostic message which is guaranteed not to interfere with test output. Like `print` @diagnostic\_message is simply concatenated together.
Returns false, so as to preserve failure.
Handy for this sort of thing:
```
ok( grep(/foo/, @users), "There's a foo user" ) or
diag("Since there's no foo, check that /etc/bar is set up right");
```
which would produce:
```
not ok 42 - There's a foo user
# Failed test 'There's a foo user'
# in foo.t at line 52.
# Since there's no foo, check that /etc/bar is set up right.
```
You might remember `ok() or diag()` with the mnemonic `open() or die()`.
**NOTE** The exact formatting of the diagnostic output is still changing, but it is guaranteed that whatever you throw at it won't interfere with the test.
**note**
```
note(@diagnostic_message);
```
Like `diag()`, except the message will not be seen when the test is run in a harness. It will only be visible in the verbose TAP stream.
Handy for putting in notes which might be useful for debugging, but don't indicate a problem.
```
note("Tempfile is $tempfile");
```
**explain**
```
my @dump = explain @diagnostic_message;
```
Will dump the contents of any references in a human readable format. Usually you want to pass this into `note` or `diag`.
Handy for things like...
```
is_deeply($have, $want) || diag explain $have;
```
or
```
note explain \%args;
Some::Class->method(%args);
```
###
Conditional tests
Sometimes running a test under certain conditions will cause the test script to die. A certain function or method isn't implemented (such as `fork()` on MacOS), some resource isn't available (like a net connection) or a module isn't available. In these cases it's necessary to skip tests, or declare that they are supposed to fail but will work in the future (a todo test).
For more details on the mechanics of skip and todo tests see <Test::Harness>.
The way Test::More handles this is with a named block. Basically, a block of tests which can be skipped over or made todo. It's best if I just show you...
**SKIP: BLOCK**
```
SKIP: {
skip $why, $how_many if $condition;
...normal testing code goes here...
}
```
This declares a block of tests that might be skipped, $how\_many tests there are, $why and under what $condition to skip them. An example is the easiest way to illustrate:
```
SKIP: {
eval { require HTML::Lint };
skip "HTML::Lint not installed", 2 if $@;
my $lint = new HTML::Lint;
isa_ok( $lint, "HTML::Lint" );
$lint->parse( $html );
is( $lint->errors, 0, "No errors found in HTML" );
}
```
If the user does not have HTML::Lint installed, the whole block of code *won't be run at all*. Test::More will output special ok's which Test::Harness interprets as skipped, but passing, tests.
It's important that $how\_many accurately reflects the number of tests in the SKIP block so the # of tests run will match up with your plan. If your plan is `no_plan` $how\_many is optional and will default to 1.
It's perfectly safe to nest SKIP blocks. Each SKIP block must have the label `SKIP`, or Test::More can't work its magic.
You don't skip tests which are failing because there's a bug in your program, or for which you don't yet have code written. For that you use TODO. Read on.
**TODO: BLOCK**
```
TODO: {
local $TODO = $why if $condition;
...normal testing code goes here...
}
```
Declares a block of tests you expect to fail and $why. Perhaps it's because you haven't fixed a bug or haven't finished a new feature:
```
TODO: {
local $TODO = "URI::Geller not finished";
my $card = "Eight of clubs";
is( URI::Geller->your_card, $card, 'Is THIS your card?' );
my $spoon;
URI::Geller->bend_spoon;
is( $spoon, 'bent', "Spoon bending, that's original" );
}
```
With a todo block, the tests inside are expected to fail. Test::More will run the tests normally, but print out special flags indicating they are "todo". <Test::Harness> will interpret failures as being ok. Should anything succeed, it will report it as an unexpected success. You then know the thing you had todo is done and can remove the TODO flag.
The nice part about todo tests, as opposed to simply commenting out a block of tests, is that it is like having a programmatic todo list. You know how much work is left to be done, you're aware of what bugs there are, and you'll know immediately when they're fixed.
Once a todo test starts succeeding, simply move it outside the block. When the block is empty, delete it.
Note that, if you leave $TODO unset or undef, Test::More reports failures as normal. This can be useful to mark the tests as expected to fail only in certain conditions, e.g.:
```
TODO: {
local $TODO = "$^O doesn't work yet. :(" if !_os_is_supported($^O);
...
}
```
**todo\_skip**
```
TODO: {
todo_skip $why, $how_many if $condition;
...normal testing code...
}
```
With todo tests, it's best to have the tests actually run. That way you'll know when they start passing. Sometimes this isn't possible. Often a failing test will cause the whole program to die or hang, even inside an `eval BLOCK` with and using `alarm`. In these extreme cases you have no choice but to skip over the broken tests entirely.
The syntax and behavior is similar to a `SKIP: BLOCK` except the tests will be marked as failing but todo. <Test::Harness> will interpret them as passing.
When do I use SKIP vs. TODO? **If it's something the user might not be able to do**, use SKIP. This includes optional modules that aren't installed, running under an OS that doesn't have some feature (like `fork()` or symlinks), or maybe you need an Internet connection and one isn't available.
**If it's something the programmer hasn't done yet**, use TODO. This is for any code you haven't written yet, or bugs you have yet to fix, but want to put tests in your testing script (always a good idea).
###
Test control
**BAIL\_OUT**
```
BAIL_OUT($reason);
```
Indicates to the harness that things are going so badly all testing should terminate. This includes the running of any additional test scripts.
This is typically used when testing cannot continue such as a critical module failing to compile or a necessary external utility not being available such as a database connection failing.
The test will exit with 255.
For even better control look at <Test::Most>.
###
Discouraged comparison functions
The use of the following functions is discouraged as they are not actually testing functions and produce no diagnostics to help figure out what went wrong. They were written before `is_deeply()` existed because I couldn't figure out how to display a useful diff of two arbitrary data structures.
These functions are usually used inside an `ok()`.
```
ok( eq_array(\@got, \@expected) );
```
`is_deeply()` can do that better and with diagnostics.
```
is_deeply( \@got, \@expected );
```
They may be deprecated in future versions.
**eq\_array**
```
my $is_eq = eq_array(\@got, \@expected);
```
Checks if two arrays are equivalent. This is a deep check, so multi-level structures are handled correctly.
**eq\_hash**
```
my $is_eq = eq_hash(\%got, \%expected);
```
Determines if the two hashes contain the same keys and values. This is a deep check.
**eq\_set**
```
my $is_eq = eq_set(\@got, \@expected);
```
Similar to `eq_array()`, except the order of the elements is **not** important. This is a deep check, but the irrelevancy of order only applies to the top level.
```
ok( eq_set(\@got, \@expected) );
```
Is better written:
```
is_deeply( [sort @got], [sort @expected] );
```
**NOTE** By historical accident, this is not a true set comparison. While the order of elements does not matter, duplicate elements do.
**NOTE** `eq_set()` does not know how to deal with references at the top level. The following is an example of a comparison which might not work:
```
eq_set([\1, \2], [\2, \1]);
```
<Test::Deep> contains much better set comparison functions.
###
Extending and Embedding Test::More
Sometimes the Test::More interface isn't quite enough. Fortunately, Test::More is built on top of <Test::Builder> which provides a single, unified backend for any test library to use. This means two test libraries which both use <Test::Builder> **can** be used together in the same program>.
If you simply want to do a little tweaking of how the tests behave, you can access the underlying <Test::Builder> object like so:
**builder**
```
my $test_builder = Test::More->builder;
```
Returns the <Test::Builder> object underlying Test::More for you to play with.
EXIT CODES
-----------
If all your tests passed, <Test::Builder> will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run <Test::Builder> will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255.
So the exit codes are...
```
0 all tests successful
255 test died or all passed but wrong # of tests run
any other number how many failed (including missing or extras)
```
If you fail more than 254 tests, it will be reported as 254.
**NOTE** This behavior may go away in future versions.
COMPATIBILITY
-------------
Test::More works with Perls as old as 5.8.1.
Thread support is not very reliable before 5.10.1, but that's because threads are not very reliable before 5.10.1.
Although Test::More has been a core module in versions of Perl since 5.6.2, Test::More has evolved since then, and not all of the features you're used to will be present in the shipped version of Test::More. If you are writing a module, don't forget to indicate in your package metadata the minimum version of Test::More that you require. For instance, if you want to use `done_testing()` but want your test script to run on Perl 5.10.0, you will need to explicitly require Test::More > 0.88.
Key feature milestones include:
subtests Subtests were released in Test::More 0.94, which came with Perl 5.12.0. Subtests did not implicitly call `done_testing()` until 0.96; the first Perl with that fix was Perl 5.14.0 with 0.98.
`done_testing()`
This was released in Test::More 0.88 and first shipped with Perl in 5.10.1 as part of Test::More 0.92.
`cmp_ok()`
Although `cmp_ok()` was introduced in 0.40, 0.86 fixed an important bug to make it safe for overloaded objects; the fixed first shipped with Perl in 5.10.1 as part of Test::More 0.92.
`new_ok()` `note()` and `explain()`
These were was released in Test::More 0.82, and first shipped with Perl in 5.10.1 as part of Test::More 0.92.
There is a full version history in the Changes file, and the Test::More versions included as core can be found using <Module::CoreList>:
```
$ corelist -a Test::More
```
CAVEATS and NOTES
------------------
utf8 / "Wide character in print" If you use utf8 or other non-ASCII characters with Test::More you might get a "Wide character in print" warning. Using `binmode STDOUT, ":utf8"` will not fix it. <Test::Builder> (which powers Test::More) duplicates STDOUT and STDERR. So any changes to them, including changing their output disciplines, will not be seen by Test::More.
One work around is to apply encodings to STDOUT and STDERR as early as possible and before Test::More (or any other Test module) loads.
```
use open ':std', ':encoding(utf8)';
use Test::More;
```
A more direct work around is to change the filehandles used by <Test::Builder>.
```
my $builder = Test::More->builder;
binmode $builder->output, ":encoding(utf8)";
binmode $builder->failure_output, ":encoding(utf8)";
binmode $builder->todo_output, ":encoding(utf8)";
```
Overloaded objects String overloaded objects are compared **as strings** (or in `cmp_ok()`'s case, strings or numbers as appropriate to the comparison op). This prevents Test::More from piercing an object's interface allowing better blackbox testing. So if a function starts returning overloaded objects instead of bare strings your tests won't notice the difference. This is good.
However, it does mean that functions like `is_deeply()` cannot be used to test the internals of string overloaded objects. In this case I would suggest <Test::Deep> which contains more flexible testing functions for complex data structures.
Threads Test::More will only be aware of threads if `use threads` has been done *before* Test::More is loaded. This is ok:
```
use threads;
use Test::More;
```
This may cause problems:
```
use Test::More
use threads;
```
5.8.1 and above are supported. Anything below that has too many bugs.
HISTORY
-------
This is a case of convergent evolution with Joshua Pritikin's [Test](test) module. I was largely unaware of its existence when I'd first written my own `ok()` routines. This module exists because I can't figure out how to easily wedge test names into Test's interface (along with a few other problems).
The goal here is to have a testing utility that's simple to learn, quick to use and difficult to trip yourself up with while still providing more flexibility than the existing Test.pm. As such, the names of the most common routines are kept tiny, special cases and magic side-effects are kept to a minimum. WYSIWYG.
SEE ALSO
---------
### ALTERNATIVES
<Test2::Suite> is the most recent and modern set of tools for testing.
<Test::Simple> if all this confuses you and you just want to write some tests. You can upgrade to Test::More later (it's forward compatible).
<Test::Legacy> tests written with Test.pm, the original testing module, do not play well with other testing libraries. Test::Legacy emulates the Test.pm interface and does play well with others.
###
ADDITIONAL LIBRARIES
<Test::Differences> for more ways to test complex data structures. And it plays well with Test::More.
<Test::Class> is like xUnit but more perlish.
<Test::Deep> gives you more powerful complex data structure testing.
<Test::Inline> shows the idea of embedded testing.
<Mock::Quick> The ultimate mocking library. Easily spawn objects defined on the fly. Can also override, block, or reimplement packages as needed.
<Test::FixtureBuilder> Quickly define fixture data for unit tests.
###
OTHER COMPONENTS
<Test::Harness> is the test runner and output interpreter for Perl. It's the thing that powers `make test` and where the `prove` utility comes from.
### BUNDLES
<Test::Most> Most commonly needed test functions and features.
AUTHORS
-------
Michael G Schwern <[email protected]> with much inspiration from Joshua Pritikin's Test module and lots of help from Barrie Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and the perl-qa gang.
MAINTAINERS
-----------
Chad Granum <[email protected]> BUGS
----
See *https://github.com/Test-More/test-more/issues* to report and view bugs.
SOURCE
------
The source code repository for Test::More can be found at *http://github.com/Test-More/test-more/*.
COPYRIGHT
---------
Copyright 2001-2008 by Michael G Schwern <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://www.perl.com/perl/misc/Artistic.html*
| programming_docs |
perl CPAN::Meta::Converter CPAN::Meta::Converter
=====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [convert](#convert)
+ [upgrade\_fragment](#upgrade_fragment)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Converter - Convert CPAN distribution metadata structures
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
my $struct = decode_json_file('META.json');
my $cmc = CPAN::Meta::Converter->new( $struct );
my $new_struct = $cmc->convert( version => "2" );
```
DESCRIPTION
-----------
This module converts CPAN Meta structures from one form to another. The primary use is to convert older structures to the most modern version of the specification, but other transformations may be implemented in the future as needed. (E.g. stripping all custom fields or stripping all optional fields.)
METHODS
-------
### new
```
my $cmc = CPAN::Meta::Converter->new( $struct );
```
The constructor should be passed a valid metadata structure but invalid structures are accepted. If no meta-spec version is provided, version 1.0 will be assumed.
Optionally, you can provide a `default_version` argument after `$struct`:
```
my $cmc = CPAN::Meta::Converter->new( $struct, default_version => "1.4" );
```
This is only needed when converting a metadata fragment that does not include a `meta-spec` field.
### convert
```
my $new_struct = $cmc->convert( version => "2" );
```
Returns a new hash reference with the metadata converted to a different form. `convert` will die if any conversion/standardization still results in an invalid structure.
Valid parameters include:
* `version` -- Indicates the desired specification version (e.g. "1.0", "1.1" ... "1.4", "2"). Defaults to the latest version of the CPAN Meta Spec.
Conversion proceeds through each version in turn. For example, a version 1.2 structure might be converted to 1.3 then 1.4 then finally to version 2. The conversion process attempts to clean-up simple errors and standardize data. For example, if `author` is given as a scalar, it will converted to an array reference containing the item. (Converting a structure to its own version will also clean-up and standardize.)
When data are cleaned and standardized, missing or invalid fields will be replaced with sensible defaults when possible. This may be lossy or imprecise. For example, some badly structured META.yml files on CPAN have prerequisite modules listed as both keys and values:
```
requires => { 'Foo::Bar' => 'Bam::Baz' }
```
These would be split and each converted to a prerequisite with a minimum version of zero.
When some mandatory fields are missing or invalid, the conversion will attempt to provide a sensible default or will fill them with a value of 'unknown'. For example a missing or unrecognized `license` field will result in a `license` field of 'unknown'. Fields that may get an 'unknown' include:
* abstract
* author
* license
### upgrade\_fragment
```
my $new_struct = $cmc->upgrade_fragment;
```
Returns a new hash reference with the metadata converted to the latest version of the CPAN Meta Spec. No validation is done on the result -- you must validate after merging fragments into a complete metadata document.
Available since version 2.141170.
BUGS
----
Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at <http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
AUTHORS
-------
* David Golden <[email protected]>
* Ricardo Signes <[email protected]>
* Adam Kennedy <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by David Golden, Ricardo Signes, Adam Kennedy and Contributors.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl TAP::Parser::IteratorFactory TAP::Parser::IteratorFactory
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [register\_handler](#register_handler)
- [handlers](#handlers)
+ [Instance Methods](#Instance-Methods)
- [config](#config)
- [load\_handlers](#load_handlers)
- [make\_iterator](#make_iterator)
- [detect\_source](#detect_source)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [AUTHORS](#AUTHORS)
* [ATTRIBUTION](#ATTRIBUTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::IteratorFactory - Figures out which SourceHandler objects to use for a given Source
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::IteratorFactory;
my $factory = TAP::Parser::IteratorFactory->new({ %config });
my $iterator = $factory->make_iterator( $filename );
```
DESCRIPTION
-----------
This is a factory class that takes a <TAP::Parser::Source> and runs it through all the registered <TAP::Parser::SourceHandler>s to see which one should handle the source.
If you're a plugin author, you'll be interested in how to ["register\_handler"](#register_handler)s, how ["detect\_source"](#detect_source) works.
METHODS
-------
###
Class Methods
#### `new`
Creates a new factory class:
```
my $sf = TAP::Parser::IteratorFactory->new( $config );
```
`$config` is optional. If given, sets ["config"](#config) and calls ["load\_handlers"](#load_handlers).
#### `register_handler`
Registers a new <TAP::Parser::SourceHandler> with this factory.
```
__PACKAGE__->register_handler( $handler_class );
```
#### `handlers`
List of handlers that have been registered.
###
Instance Methods
#### `config`
```
my $cfg = $sf->config;
$sf->config({ Perl => { %config } });
```
Chaining getter/setter for the configuration of the available source handlers. This is a hashref keyed on handler class whose values contain config to be passed onto the handlers during detection & creation. Class names may be fully qualified or abbreviated, eg:
```
# these are equivalent
$sf->config({ 'TAP::Parser::SourceHandler::Perl' => { %config } });
$sf->config({ 'Perl' => { %config } });
```
#### `load_handlers`
```
$sf->load_handlers;
```
Loads the handler classes defined in ["config"](#config). For example, given a config:
```
$sf->config({
MySourceHandler => { some => 'config' },
});
```
`load_handlers` will attempt to load the `MySourceHandler` class by looking in `@INC` for it in this order:
```
TAP::Parser::SourceHandler::MySourceHandler
MySourceHandler
```
`croak`s on error.
#### `make_iterator`
```
my $iterator = $src_factory->make_iterator( $source );
```
Given a <TAP::Parser::Source>, finds the most suitable <TAP::Parser::SourceHandler> to use to create a <TAP::Parser::Iterator> (see ["detect\_source"](#detect_source)). Dies on error.
#### `detect_source`
Given a <TAP::Parser::Source>, detects what kind of source it is and returns *one* <TAP::Parser::SourceHandler> (the most confident one). Dies on error.
The detection algorithm works something like this:
```
for (@registered_handlers) {
# ask them how confident they are about handling this source
$confidence{$handler} = $handler->can_handle( $source )
}
# choose the most confident handler
```
Ties are handled by choosing the first handler.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
### Example
If we've done things right, you'll probably want to write a new source, rather than sub-classing this (see <TAP::Parser::SourceHandler> for that).
But in case you find the need to...
```
package MyIteratorFactory;
use strict;
use base 'TAP::Parser::IteratorFactory';
# override source detection algorithm
sub detect_source {
my ($self, $raw_source_ref, $meta) = @_;
# do detective work, using $meta and whatever else...
}
1;
```
AUTHORS
-------
Steve Purkis
ATTRIBUTION
-----------
Originally ripped off from <Test::Harness>.
Moved out of <TAP::Parser> & converted to a factory class to support extensible TAP source detective work by Steve Purkis.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::SourceHandler>, <TAP::Parser::SourceHandler::File>, <TAP::Parser::SourceHandler::Perl>, <TAP::Parser::SourceHandler::RawTAP>, <TAP::Parser::SourceHandler::Handle>, <TAP::Parser::SourceHandler::Executable>
perl Test2::Tools::Tiny Test2::Tools::Tiny
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [USE Test2::Suite INSTEAD](#USE-Test2::Suite-INSTEAD)
* [EXPORTS](#EXPORTS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Tools::Tiny - Tiny set of tools for unfortunate souls who cannot use <Test2::Suite>.
DESCRIPTION
-----------
You should really look at <Test2::Suite>. This package is some very basic essential tools implemented using [Test2](test2). This exists only so that [Test2](test2) and other tools required by <Test2::Suite> can be tested. This is the package [Test2](test2) uses to test itself.
USE Test2::Suite INSTEAD
-------------------------
Use <Test2::Suite> if at all possible.
EXPORTS
-------
ok($bool, $name)
ok($bool, $name, @diag) Run a simple assertion.
is($got, $want, $name)
is($got, $want, $name, @diag) Assert that 2 strings are the same.
isnt($got, $do\_not\_want, $name)
isnt($got, $do\_not\_want, $name, @diag) Assert that 2 strings are not the same.
like($got, $regex, $name)
like($got, $regex, $name, @diag) Check that the input string matches the regex.
unlike($got, $regex, $name)
unlike($got, $regex, $name, @diag) Check that the input string does not match the regex.
is\_deeply($got, $want, $name)
is\_deeply($got, $want, $name, @diag) Check 2 data structures. Please note that this is a *DUMB* implementation that compares the output of <Data::Dumper> against both structures.
diag($msg) Issue a diagnostics message to STDERR.
note($msg) Issue a diagnostics message to STDOUT.
skip\_all($reason) Skip all tests.
todo $reason => sub { ... } Run a block in TODO mode.
plan($count) Set the plan.
done\_testing() Set the plan to the current test count.
$warnings = warnings { ... } Capture an arrayref of warnings from the block.
$exception = exception { ... } Capture an exception.
tests $name => sub { ... } Run a subtest.
$output = capture { ... } Capture STDOUT and STDERR output.
Result looks like this:
```
{
STDOUT => "...",
STDERR => "...",
}
```
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Test2::Event::Generic Test2::Event::Generic
=====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Generic - Generic event type.
DESCRIPTION
-----------
This is a generic event that lets you customize all fields in the event API. This is useful if you have need for a custom event that does not make sense as a published reusable event subclass.
SYNOPSIS
--------
```
use Test2::API qw/context/;
sub send_custom_fail {
my $ctx = shift;
$ctx->send_event('Generic', causes_fail => 1, summary => 'The sky is falling');
$ctx->release;
}
send_custom_fail();
```
METHODS
-------
$e->facet\_data($data)
$data = $e->facet\_data Get or set the facet data (see <Test2::Event>). If no facet\_data is set then `Test2::Event->facet_data` will be called to produce facets from the other data.
$e->callback($hub) Call the custom callback if one is set, otherwise this does nothing.
$e->set\_callback(sub { ... }) Set the custom callback. The custom callback must be a coderef. The first argument to your callback will be the event itself, the second will be the <Test2::Event::Hub> that is using the callback.
$bool = $e->causes\_fail
$e->set\_causes\_fail($bool) Get/Set the `causes_fail` attribute. This defaults to `0`.
$bool = $e->diagnostics
$e->set\_diagnostics($bool) Get/Set the `diagnostics` attribute. This defaults to `0`.
$bool\_or\_undef = $e->global
@bool\_or\_empty = $e->global
$e->set\_global($bool\_or\_undef) Get/Set the `diagnostics` attribute. This defaults to an empty list which is undef in scalar context.
$bool = $e->increments\_count
$e->set\_increments\_count($bool) Get/Set the `increments_count` attribute. This defaults to `0`.
$bool = $e->no\_display
$e->set\_no\_display($bool) Get/Set the `no_display` attribute. This defaults to `0`.
@plan = $e->sets\_plan Get the plan if this event sets one. The plan is a list of up to 3 items: `($count, $directive, $reason)`. `$count` must be defined, the others may be undef, or may not exist at all.
$e->set\_sets\_plan(\@plan) Set the plan. You must pass in an arrayref with up to 3 elements.
$summary = $e->summary
$e->set\_summary($summary\_or\_undef) Get/Set the summary. This will default to the event package `'Test2::Event::Generic'`. You can set it to any value. Setting this to `undef` will reset it to the default.
$int\_or\_undef = $e->terminate
@int\_or\_empty = $e->terminate
$e->set\_terminate($int\_or\_undef) This will get/set the `terminate` attribute. This defaults to undef in scalar context, or an empty list in list context. Setting this to undef will clear it completely. This must be set to a positive integer (0 or larger).
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl bigrat bigrat
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Options](#Options)
+ [Math Library](#Math-Library)
+ [Method calls](#Method-calls)
+ [Methods](#Methods)
* [CAVEATS](#CAVEATS)
* [EXAMPLES](#EXAMPLES)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
bigrat - transparent big rational number support for Perl
SYNOPSIS
--------
```
use bigrat;
print 2 + 4.5; # Math::BigRat 13/2
print 1/3 + 1/4; # Math::BigRat 7/12
print inf + 42; # Math::BigRat inf
print NaN * 7; # Math::BigRat NaN
print hex("0x1234567890123490"); # Perl v5.10.0 or later
{
no bigrat;
print 1/3; # 0.33333...
}
# for older Perls, import into current package:
use bigrat qw/hex oct/;
print hex("0x1234567890123490");
print oct("01234567890123490");
```
DESCRIPTION
-----------
All numeric literal in the given scope are converted to Math::BigRat objects.
All operators (including basic math operations) except the range operator `..` are overloaded.
So, the following:
```
use bigrat;
$x = 1234;
```
creates a Math::BigRat and stores a reference to in $x. This happens transparently and behind your back, so to speak.
You can see this with the following:
```
perl -Mbigrat -le 'print ref(1234)'
```
Since numbers are actually objects, you can call all the usual methods from Math::BigRat on them. This even works to some extent on expressions:
```
perl -Mbigrat -le '$x = 1234; print $x->bdec()'
perl -Mbigrat -le 'print 1234->copy()->binc();'
perl -Mbigrat -le 'print 1234->copy()->binc->badd(6);'
perl -Mbigrat -le 'print +(1234)->copy()->binc()'
```
(Note that print doesn't do what you expect if the expression starts with '(' hence the `+`)
You can even chain the operations together as usual:
```
perl -Mbigrat -le 'print 1234->copy()->binc->badd(6);'
1241
```
Please note the following does not work as expected (prints nothing), since overloading of '..' is not yet possible in Perl (as of v5.8.0):
```
perl -Mbigrat -le 'for (1..2) { print ref($_); }'
```
### Options
`bigrat` recognizes some options that can be passed while loading it via `use`. The following options exist:
a or accuracy This sets the accuracy for all math operations. The argument must be greater than or equal to zero. See Math::BigInt's bround() method for details.
```
perl -Mbigrat=a,50 -le 'print sqrt(20)'
```
Note that setting precision and accuracy at the same time is not possible.
p or precision This sets the precision for all math operations. The argument can be any integer. Negative values mean a fixed number of digits after the dot, while a positive value rounds to this digit left from the dot. 0 means round to integer. See Math::BigInt's bfround() method for details.
```
perl -Mbigrat=p,-50 -le 'print sqrt(20)'
```
Note that setting precision and accuracy at the same time is not possible.
t or trace This enables a trace mode and is primarily for debugging.
l, lib, try, or only Load a different math lib, see ["Math Library"](#Math-Library).
```
perl -Mbigrat=l,GMP -e 'print 2 ** 512'
perl -Mbigrat=lib,GMP -e 'print 2 ** 512'
perl -Mbigrat=try,GMP -e 'print 2 ** 512'
perl -Mbigrat=only,GMP -e 'print 2 ** 512'
```
hex Override the built-in hex() method with a version that can handle big numbers. This overrides it by exporting it to the current package. Under Perl v5.10.0 and higher, this is not so necessary, as hex() is lexically overridden in the current scope whenever the `bigrat` pragma is active.
oct Override the built-in oct() method with a version that can handle big numbers. This overrides it by exporting it to the current package. Under Perl v5.10.0 and higher, this is not so necessary, as oct() is lexically overridden in the current scope whenever the `bigrat` pragma is active.
v or version this prints out the name and version of the modules and then exits.
```
perl -Mbigrat=v
```
###
Math Library
Math with the numbers is done (by default) by a backend library module called Math::BigInt::Calc. The default is equivalent to saying:
```
use bigrat lib => 'Calc';
```
you can change this by using:
```
use bigrat lib => 'GMP';
```
The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and if this also fails, revert to Math::BigInt::Calc:
```
use bigrat lib => 'Foo,Math::BigInt::Bar';
```
Using c<lib> warns if none of the specified libraries can be found and <Math::BigInt> fell back to one of the default libraries. To suppress this warning, use c<try> instead:
```
use bigrat try => 'GMP';
```
If you want the code to die instead of falling back, use `only` instead:
```
use bigrat only => 'GMP';
```
Please see the respective module documentation for further details.
###
Method calls
Since all numbers are now objects, you can use all methods that are part of the Math::BigRat API.
But a warning is in order. When using the following to make a copy of a number, only a shallow copy will be made.
```
$x = 9; $y = $x;
$x = $y = 7;
```
Using the copy or the original with overloaded math is okay, e.g., the following work:
```
$x = 9; $y = $x;
print $x + 1, " ", $y,"\n"; # prints 10 9
```
but calling any method that modifies the number directly will result in **both** the original and the copy being destroyed:
```
$x = 9; $y = $x;
print $x->badd(1), " ", $y,"\n"; # prints 10 10
$x = 9; $y = $x;
print $x->binc(1), " ", $y,"\n"; # prints 10 10
$x = 9; $y = $x;
print $x->bmul(2), " ", $y,"\n"; # prints 18 18
```
Using methods that do not modify, but test that the contents works:
```
$x = 9; $y = $x;
$z = 9 if $x->is_zero(); # works fine
```
See the documentation about the copy constructor and `=` in overload, as well as the documentation in Math::BigFloat for further details.
### Methods
inf() A shortcut to return Math::BigRat->binf(). Useful because Perl does not always handle bareword `inf` properly.
NaN() A shortcut to return Math::BigRat->bnan(). Useful because Perl does not always handle bareword `NaN` properly.
e
```
# perl -Mbigrat=e -wle 'print e'
```
Returns Euler's number `e`, aka exp(1).
PI
```
# perl -Mbigrat=PI -wle 'print PI'
```
Returns PI.
bexp()
```
bexp($power, $accuracy);
```
Returns Euler's number `e` raised to the appropriate power, to the wanted accuracy.
Example:
```
# perl -Mbigrat=bexp -wle 'print bexp(1,80)'
```
bpi()
```
bpi($accuracy);
```
Returns PI to the wanted accuracy.
Example:
```
# perl -Mbigrat=bpi -wle 'print bpi(80)'
```
accuracy() Set or get the accuracy.
precision() Set or get the precision.
round\_mode() Set or get the rounding mode.
div\_scale() Set or get the division scale.
in\_effect()
```
use bigrat;
print "in effect\n" if bigrat::in_effect; # true
{
no bigrat;
print "in effect\n" if bigrat::in_effect; # false
}
```
Returns true or false if `bigrat` is in effect in the current scope.
This method only works on Perl v5.9.4 or later.
CAVEATS
-------
Hexadecimal, octal, and binary floating point literals Perl (and this module) accepts hexadecimal, octal, and binary floating point literals, but use them with care with Perl versions before v5.32.0, because some versions of Perl silently give the wrong result.
Operator vs literal overloading `bigrat` works by overloading handling of integer and floating point literals, converting them to <Math::BigRat> objects.
This means that arithmetic involving only string values or string literals are performed using Perl's built-in operators.
For example:
```
use bigrat;
my $x = "900000000000000009";
my $y = "900000000000000007";
print $x - $y;
```
outputs `0` on default 32-bit builds, since `bigrat` never sees the string literals. To ensure the expression is all treated as `Math::BigRat` objects, use a literal number in the expression:
```
print +(0+$x) - $y;
```
Ranges Perl does not allow overloading of ranges, so you can neither safely use ranges with `bigrat` endpoints, nor is the iterator variable a `Math::BigRat`.
```
use 5.010;
for my $i (12..13) {
for my $j (20..21) {
say $i ** $j; # produces a floating-point number,
# not an object
}
}
```
in\_effect() This method only works on Perl v5.9.4 or later.
hex()/oct() `bigrat` overrides these routines with versions that can also handle big integer values. Under Perl prior to version v5.9.4, however, this will not happen unless you specifically ask for it with the two import tags "hex" and "oct" - and then it will be global and cannot be disabled inside a scope with `no bigrat`:
```
use bigrat qw/hex oct/;
print hex("0x1234567890123456");
{
no bigrat;
print hex("0x1234567890123456");
}
```
The second call to hex() will warn about a non-portable constant.
Compare this to:
```
use bigrat;
# will warn only under Perl older than v5.9.4
print hex("0x1234567890123456");
```
EXAMPLES
--------
```
perl -Mbigrat -le 'print sqrt(33)'
perl -Mbigrat -le 'print 2**255'
perl -Mbigrat -le 'print 4.5+2**255'
perl -Mbigrat -le 'print 3/7 + 5/7 + 8/3'
perl -Mbigrat -le 'print 12->is_odd()';
perl -Mbigrat=l,GMP -le 'print 7 ** 7777'
```
BUGS
----
Please report any bugs or feature requests to `bug-bignum at rt.cpan.org`, or through the web interface at <https://rt.cpan.org/Ticket/Create.html?Queue=bignum> (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
-------
You can find documentation for this module with the perldoc command.
```
perldoc bigrat
```
You can also look for information at:
* GitHub
<https://github.com/pjacklam/p5-bignum>
* RT: CPAN's request tracker
<https://rt.cpan.org/Dist/Display.html?Name=bignum>
* MetaCPAN
<https://metacpan.org/release/bignum>
* CPAN Testers Matrix
<http://matrix.cpantesters.org/?dist=bignum>
* CPAN Ratings
<https://cpanratings.perl.org/dist/bignum>
LICENSE
-------
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<bignum> and <bigint>.
<Math::BigInt>, <Math::BigFloat>, <Math::BigRat> and <Math::Big> as well as <Math::BigInt::FastCalc>, <Math::BigInt::Pari> and <Math::BigInt::GMP>.
AUTHORS
-------
* (C) by Tels <http://bloodgate.com/> in early 2002 - 2007.
* Maintained by Peter John Acklam <[email protected]>, 2014-.
| programming_docs |
perl Test2::Event::Subtest Test2::Event::Subtest
=====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [ACCESSORS](#ACCESSORS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Subtest - Event for subtest types
DESCRIPTION
-----------
This class represents a subtest. This class is a subclass of <Test2::Event::Ok>.
ACCESSORS
---------
This class inherits from <Test2::Event::Ok>.
$arrayref = $e->subevents Returns the arrayref containing all the events from the subtest
$bool = $e->buffered True if the subtest is buffered, that is all subevents render at once. If this is false it means all subevents render as they are produced.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl ExtUtils::Typemaps::Cmd ExtUtils::Typemaps::Cmd
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTED FUNCTIONS](#EXPORTED-FUNCTIONS)
+ [embeddable\_typemap](#embeddable_typemap)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
ExtUtils::Typemaps::Cmd - Quick commands for handling typemaps
SYNOPSIS
--------
From XS:
```
INCLUDE_COMMAND: $^X -MExtUtils::Typemaps::Cmd \
-e "print embeddable_typemap(q{Excommunicated})"
```
Loads `ExtUtils::Typemaps::Excommunicated`, instantiates an object, and dumps it as an embeddable typemap for use directly in your XS file.
DESCRIPTION
-----------
This is a helper module for <ExtUtils::Typemaps> for quick one-liners, specifically for inclusion of shared typemaps that live on CPAN into an XS file (see SYNOPSIS).
For this reason, the following functions are exported by default:
EXPORTED FUNCTIONS
-------------------
### embeddable\_typemap
Given a list of identifiers, `embeddable_typemap` tries to load typemaps from a file of the given name(s), or from a module that is an `ExtUtils::Typemaps` subclass.
Returns a string representation of the merged typemaps that can be included verbatim into XS. Example:
```
print embeddable_typemap(
"Excommunicated", "ExtUtils::Typemaps::Basic", "./typemap"
);
```
This will try to load a module `ExtUtils::Typemaps::Excommunicated` and use it as an `ExtUtils::Typemaps` subclass. If that fails, it'll try loading `Excommunicated` as a module, if that fails, it'll try to read a file called *Excommunicated*. It'll work similarly for the second argument, but the third will be loaded as a file first.
After loading all typemap files or modules, it will merge them in the specified order and dump the result as an embeddable typemap.
SEE ALSO
---------
<ExtUtils::Typemaps>
<perlxs>
AUTHOR
------
Steffen Mueller `<[email protected]`>
COPYRIGHT & LICENSE
--------------------
Copyright 2012 Steffen Mueller
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Memoize::Storable Memoize::Storable
=================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Memoize::Storable - store Memoized data in Storable database
DESCRIPTION
-----------
See [Memoize](memoize).
perl builtin builtin
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Lexical Import](#Lexical-Import)
* [FUNCTIONS](#FUNCTIONS)
+ [true](#true)
+ [false](#false)
+ [is\_bool](#is_bool)
+ [weaken](#weaken)
+ [unweaken](#unweaken)
+ [is\_weak](#is_weak)
+ [blessed](#blessed)
+ [refaddr](#refaddr)
+ [reftype](#reftype)
+ [created\_as\_string](#created_as_string)
+ [created\_as\_number](#created_as_number)
+ [ceil](#ceil)
+ [floor](#floor)
+ [indexed](#indexed)
+ [trim](#trim)
* [SEE ALSO](#SEE-ALSO)
NAME
----
builtin - Perl pragma to import built-in utility functions
SYNOPSIS
--------
```
use builtin qw(
true false is_bool
weaken unweaken is_weak
blessed refaddr reftype
created_as_string created_as_number
ceil floor
trim
);
```
DESCRIPTION
-----------
Perl provides several utility functions in the `builtin` package. These are plain functions, and look and behave just like regular user-defined functions do. They do not provide new syntax or require special parsing. These functions are always present in the interpreter and can be called at any time by their fully-qualified names. By default they are not available as short names, but can be requested for convenience.
Individual named functions can be imported by listing them as import parameters on the `use` statement for this pragma.
The overall `builtin` mechanism, as well as every individual function it provides, are currently **experimental**.
**Warning**: At present, the entire `builtin` namespace is experimental. Calling functions in it will trigger warnings of the `experimental::builtin` category.
###
Lexical Import
This pragma module creates *lexical* aliases in the currently-compiling scope to these builtin functions. This is similar to the lexical effect of other pragmas such as <strict> and <feature>.
```
sub classify
{
my $val = shift;
use builtin 'is_bool';
return is_bool($val) ? "boolean" : "not a boolean";
}
# the is_bool() function is no longer visible here
# but may still be called by builtin::is_bool()
```
Because these functions are imported lexically, rather than by package symbols, the user does not need to take any special measures to ensure they don't accidentally appear as object methods from a class.
```
package An::Object::Class {
use builtin 'true', 'false';
...
}
# does not appear as a method
An::Object::Class->true;
# Can't locate object method "true" via package "An::Object::Class"
# at ...
```
FUNCTIONS
---------
### true
```
$val = true;
```
Returns the boolean truth value. While any scalar value can be tested for truth and most defined, non-empty and non-zero values are considered "true" by perl, this one is special in that ["is\_bool"](#is_bool) considers it to be a distinguished boolean value.
This gives an equivalent value to expressions like `!!1` or `!0`.
### false
```
$val = false;
```
Returns the boolean fiction value. While any non-true scalar value is considered "false" by perl, this one is special in that ["is\_bool"](#is_bool) considers it to be a distinguished boolean value.
This gives an equivalent value to expressions like `!!0` or `!1`.
### is\_bool
```
$bool = is_bool($val);
```
Returns true when given a distinguished boolean value, or false if not. A distinguished boolean value is the result of any boolean-returning builtin function (such as `true` or `is_bool` itself), boolean-returning operator (such as the `eq` or `==` comparison tests or the `!` negation operator), or any variable containing one of these results.
This function used to be named `isbool`. A compatibility alias is provided currently but will be removed in a later version.
### weaken
```
weaken($ref);
```
Weakens a reference. A weakened reference does not contribute to the reference count of its referent. If only weakened references to a referent remain, it will be disposed of, and all remaining weak references to it will have their value set to `undef`.
### unweaken
```
unweaken($ref);
```
Strengthens a reference, undoing the effects of a previous call to ["weaken"](#weaken).
### is\_weak
```
$bool = is_weak($ref);
```
Returns true when given a weakened reference, or false if not a reference or not weak.
This function used to be named `isweak`. A compatibility alias is provided currently but will be removed in a later version.
### blessed
```
$str = blessed($ref);
```
Returns the package name for an object reference, or `undef` for a non-reference or reference that is not an object.
### refaddr
```
$num = refaddr($ref);
```
Returns the memory address for a reference, or `undef` for a non-reference. This value is not likely to be very useful for pure Perl code, but is handy as a means to test for referential identity or uniqueness.
### reftype
```
$str = reftype($ref);
```
Returns the basic container type of the referent of a reference, or `undef` for a non-reference. This is returned as a string in all-capitals, such as `ARRAY` for array references, or `HASH` for hash references.
### created\_as\_string
```
$bool = created_as_string($val);
```
Returns a boolean representing if the argument value was originally created as a string. It will return true for any scalar expression whose most recent assignment or modification was of a string-like nature - such as assignment from a string literal, or the result of a string operation such as concatenation or regexp. It will return false for references (including any object), numbers, booleans and undef.
It is unlikely that you will want to use this for regular data validation within Perl, as it will not return true for regular numbers that are still perfectly usable as strings, nor for any object reference - especially objects that overload the stringification operator in an attempt to behave more like strings. For example
```
my $val = URI->new( "https://metacpan.org/" );
if( created_as_string $val ) { ... } # this will not execute
```
### created\_as\_number
```
$bool = created_as_number($val);
```
Returns a boolean representing if the argument value was originally created as a number. It will return true for any scalar expression whose most recent assignment or modification was of a numerical nature - such as assignment from a number literal, or the result of a numerical operation such as addition. It will return false for references (including any object), strings, booleans and undef.
It is unlikely that you will want to use this for regular data validation within Perl, as it will not return true for regular strings of decimal digits that are still perfectly usable as numbers, nor for any object reference - especially objects that overload the numification operator in an attempt to behave more like numbers. For example
```
my $val = Math::BigInt->new( 123 );
if( created_as_number $val ) { ... } # this will not execute
```
While most Perl code should operate on scalar values without needing to know their creation history, these two functions are intended to be used by data serialisation modules such as JSON encoders or similar situations, where language interoperability concerns require making a distinction between values that are fundamentally stringlike versus numberlike in nature.
### ceil
```
$num = ceil($num);
```
Returns the smallest integer value greater than or equal to the given numerical argument.
### floor
```
$num = floor($num);
```
Returns the largest integer value less than or equal to the given numerical argument.
### indexed
```
@ivpairs = indexed(@items)
```
Returns an even-sized list of number/value pairs, where each pair is formed of a number giving an index in the original list followed by the value at that position in it. I.e. returns a list twice the size of the original, being equal to
```
(0, $items[0], 1, $items[1], 2, $items[2], ...)
```
Note that unlike the core `values` function, this function returns copies of its original arguments, not aliases to them. Any modifications of these copies are *not* reflected in modifications to the original.
```
my @x = ...;
$_++ for indexed @x; # The @x array remains unaffected
```
This function is primarily intended to be useful combined with multi-variable `foreach` loop syntax; as
```
foreach my ($index, $value) (indexed LIST) {
...
}
```
In scalar context this function returns the size of the list that it would otherwise have returned, and provokes a warning in the `scalar` category.
### trim
```
$stripped = trim($string);
```
Returns the input string with whitespace stripped from the beginning and end. trim() will remove these characters:
" ", an ordinary space.
"\t", a tab.
"\n", a new line (line feed).
"\r", a carriage return.
and all other Unicode characters that are flagged as whitespace. A complete list is in ["Whitespace" in perlrecharclass](perlrecharclass#Whitespace).
```
$var = " Hello world "; # "Hello world"
$var = "\t\t\tHello world"; # "Hello world"
$var = "Hello world\n"; # "Hello world"
$var = "\x{2028}Hello world\x{3000}"; # "Hello world"
```
`trim` is equivalent to:
```
$str =~ s/\A\s+|\s+\z//urg;
```
For Perl versions where this feature is not available look at the <String::Util> module for a comparable implementation.
SEE ALSO
---------
<perlop>, <perlfunc>, <Scalar::Util>
perl Pod::Text::Color Pod::Text::Color
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Text::Color - Convert POD data to formatted color ASCII text
SYNOPSIS
--------
```
use Pod::Text::Color;
my $parser = Pod::Text::Color->new (sentence => 0, width => 78);
# Read POD from STDIN and write to STDOUT.
$parser->parse_from_filehandle;
# Read POD from file.pod and write to file.txt.
$parser->parse_from_file ('file.pod', 'file.txt');
```
DESCRIPTION
-----------
Pod::Text::Color is a simple subclass of Pod::Text that highlights output text using ANSI color escape sequences. Apart from the color, it in all ways functions like Pod::Text. See <Pod::Text> for details and available options.
Term::ANSIColor is used to get colors and therefore must be installed to use this module.
BUGS
----
This is just a basic proof of concept. It should be seriously expanded to support configurable coloration via options passed to the constructor, and **pod2text** should be taught about those.
AUTHOR
------
Russ Allbery <[email protected]>.
COPYRIGHT AND LICENSE
----------------------
Copyright 1999, 2001, 2004, 2006, 2008, 2009, 2018-2019 Russ Allbery <[email protected]>
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<Pod::Text>, <Pod::Simple>
The current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>. It is also part of the Perl core distribution as of 5.6.0.
perl deprecate deprecate
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Important Caveat](#Important-Caveat)
* [EXPORT](#EXPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
deprecate - Perl pragma for deprecating the inclusion of a module in core
SYNOPSIS
--------
```
use deprecate; # warn about future absence if loaded from core
```
DESCRIPTION
-----------
This pragma simplifies the maintenance of dual-life modules that will no longer be included in the Perl core in a future Perl release, but are still included currently.
The purpose of the pragma is to alert users to the status of such a module by issuing a warning that encourages them to install the module from CPAN, so that a future upgrade to a perl which omits the module will not break their code.
This warning will only be issued if the module was loaded from a core library directory, which allows the `use deprecate` line to be included in the CPAN version of the module. Because the pragma remains silent when the module is run from a non-core library directory, the pragma call does not need to be patched into or out of either the core or CPAN version of the module. The exact same code can be shipped for either purpose.
###
Important Caveat
Note that when a module installs from CPAN to a core library directory rather than the site library directories, the user gains no protection from having installed it.
At the same time, this pragma cannot detect when such a module has installed from CPAN to the core library, and so it would endlessly and uselessly exhort the user to upgrade.
Therefore modules that can install from CPAN to the core library must make sure not to call this pragma when they have done so. Generally this means that the exact logic from the installer must be mirrored inside the module. E.g.:
```
# Makefile.PL
WriteMakefile(
# ...
INSTALLDIRS => ( "$]" >= 5.011 ? 'site' : 'perl' ),
);
# lib/Foo/Bar.pm
use if "$]" >= 5.011, 'deprecate';
```
(The above example shows the most important case of this: when the target is a Perl older than 5.12 (where the core library directories take precedence over the site library directories) and the module being installed was included in core in that Perl version. Under those circumstances, an upgrade of the module from CPAN is only possible by installing to the core library.)
EXPORT
------
None by default. The only method is `import`, called by `use deprecate;`.
SEE ALSO
---------
First example to `use deprecate;` was [Switch](switch).
AUTHOR
------
Original version by Nicholas Clark
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2009, 2011
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.
perl re re
==
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ ['taint' mode](#'taint'-mode)
+ ['eval' mode](#'eval'-mode)
+ ['strict' mode](#'strict'-mode)
+ ['/flags' mode](#'/flags'-mode)
+ ['debug' mode](#'debug'-mode)
+ ['Debug' mode](#'Debug'-mode)
+ [Exportable Functions](#Exportable-Functions)
* [SEE ALSO](#SEE-ALSO)
NAME
----
re - Perl pragma to alter regular expression behaviour
SYNOPSIS
--------
```
use re 'taint';
($x) = ($^X =~ /^(.*)$/s); # $x is tainted here
$pat = '(?{ $foo = 1 })';
use re 'eval';
/foo${pat}bar/; # won't fail (when not under -T
# switch)
{
no re 'taint'; # the default
($x) = ($^X =~ /^(.*)$/s); # $x is not tainted here
no re 'eval'; # the default
/foo${pat}bar/; # disallowed (with or without -T
# switch)
}
use re 'strict'; # Raise warnings for more conditions
use re '/ix';
"FOO" =~ / foo /; # /ix implied
no re '/x';
"FOO" =~ /foo/; # just /i implied
use re 'debug'; # output debugging info during
/^(.*)$/s; # compile and run time
use re 'debugcolor'; # same as 'debug', but with colored
# output
...
use re qw(Debug All); # Same as "use re 'debug'", but you
# can use "Debug" with things other
# than 'All'
use re qw(Debug More); # 'All' plus output more details
no re qw(Debug ALL); # Turn on (almost) all re debugging
# in this scope
use re qw(is_regexp regexp_pattern); # import utility functions
my ($pat,$mods)=regexp_pattern(qr/foo/i);
if (is_regexp($obj)) {
print "Got regexp: ",
scalar regexp_pattern($obj); # just as perl would stringify
} # it but no hassle with blessed
# re's.
```
(We use $^X in these examples because it's tainted by default.)
DESCRIPTION
-----------
###
'taint' mode
When `use re 'taint'` is in effect, and a tainted string is the target of a regexp, the regexp memories (or values returned by the m// operator in list context) are tainted. This feature is useful when regexp operations on tainted data aren't meant to extract safe substrings, but to perform other transformations.
###
'eval' mode
When `use re 'eval'` is in effect, a regexp is allowed to contain `(?{ ... })` zero-width assertions and `(??{ ... })` postponed subexpressions that are derived from variable interpolation, rather than appearing literally within the regexp. That is normally disallowed, since it is a potential security risk. Note that this pragma is ignored when the regular expression is obtained from tainted data, i.e. evaluation is always disallowed with tainted regular expressions. See ["(?{ code })" in perlre](perlre#%28%3F%7B-code-%7D%29) and ["(??{ code })" in perlre](perlre#%28%3F%3F%7B-code-%7D%29).
For the purpose of this pragma, interpolation of precompiled regular expressions (i.e., the result of `qr//`) is *not* considered variable interpolation. Thus:
```
/foo${pat}bar/
```
*is* allowed if $pat is a precompiled regular expression, even if $pat contains `(?{ ... })` assertions or `(??{ ... })` subexpressions.
###
'strict' mode
Note that this is an experimental feature which may be changed or removed in a future Perl release.
When `use re 'strict'` is in effect, stricter checks are applied than otherwise when compiling regular expressions patterns. These may cause more warnings to be raised than otherwise, and more things to be fatal instead of just warnings. The purpose of this is to find and report at compile time some things, which may be legal, but have a reasonable possibility of not being the programmer's actual intent. This automatically turns on the `"regexp"` warnings category (if not already on) within its scope.
As an example of something that is caught under `"strict'`, but not otherwise, is the pattern
```
qr/\xABC/
```
The `"\x"` construct without curly braces should be followed by exactly two hex digits; this one is followed by three. This currently evaluates as equivalent to
```
qr/\x{AB}C/
```
that is, the character whose code point value is `0xAB`, followed by the letter `C`. But since `C` is a hex digit, there is a reasonable chance that the intent was
```
qr/\x{ABC}/
```
that is the single character at `0xABC`. Under `'strict'` it is an error to not follow `\x` with exactly two hex digits. When not under `'strict'` a warning is generated if there is only one hex digit, and no warning is raised if there are more than two.
It is expected that what exactly `'strict'` does will evolve over time as we gain experience with it. This means that programs that compile under it in today's Perl may not compile, or may have more or fewer warnings, in future Perls. There is no backwards compatibility promises with regards to it. Also there are already proposals for an alternate syntax for enabling it. For these reasons, using it will raise a `experimental::re_strict` class warning, unless that category is turned off.
Note that if a pattern compiled within `'strict'` is recompiled, say by interpolating into another pattern, outside of `'strict'`, it is not checked again for strictness. This is because if it works under strict it must work under non-strict.
###
'/flags' mode
When `use re '/*flags*'` is specified, the given *flags* are automatically added to every regular expression till the end of the lexical scope. *flags* can be any combination of `'a'`, `'aa'`, `'d'`, `'i'`, `'l'`, `'m'`, `'n'`, `'p'`, `'s'`, `'u'`, `'x'`, and/or `'xx'`.
`no re '/*flags*'` will turn off the effect of `use re '/*flags*'` for the given flags.
For example, if you want all your regular expressions to have /msxx on by default, simply put
```
use re '/msxx';
```
at the top of your code.
The character set `/adul` flags cancel each other out. So, in this example,
```
use re "/u";
"ss" =~ /\xdf/;
use re "/d";
"ss" =~ /\xdf/;
```
the second `use re` does an implicit `no re '/u'`.
Similarly,
```
use re "/xx"; # Doubled-x
...
use re "/x"; # Single x from here on
...
```
Turning on one of the character set flags with `use re` takes precedence over the `locale` pragma and the 'unicode\_strings' `feature`, for regular expressions. Turning off one of these flags when it is active reverts to the behaviour specified by whatever other pragmata are in scope. For example:
```
use feature "unicode_strings";
no re "/u"; # does nothing
use re "/l";
no re "/l"; # reverts to unicode_strings behaviour
```
###
'debug' mode
When `use re 'debug'` is in effect, perl emits debugging messages when compiling and using regular expressions. The output is the same as that obtained by running a `-DDEBUGGING`-enabled perl interpreter with the **-Dr** switch. It may be quite voluminous depending on the complexity of the match. Using `debugcolor` instead of `debug` enables a form of output that can be used to get a colorful display on terminals that understand termcap color sequences. Set `$ENV{PERL_RE_TC}` to a comma-separated list of `termcap` properties to use for highlighting strings on/off, pre-point part on/off. See ["Debugging Regular Expressions" in perldebug](perldebug#Debugging-Regular-Expressions) for additional info.
**NOTE** that the exact format of the `debug` mode is **NOT** considered to be an officially supported API of Perl. It is intended for debugging only and may change as the core development team deems appropriate without notice or deprecation in any release of Perl, major or minor. Any documentation of the output is purely advisory.
As of 5.9.5 the directive `use re 'debug'` and its equivalents are lexically scoped, as the other directives are. However they have both compile-time and run-time effects.
See ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules).
###
'Debug' mode
Similarly `use re 'Debug'` produces debugging output, the difference being that it allows the fine tuning of what debugging output will be emitted. Options are divided into three groups, those related to compilation, those related to execution and those related to special purposes.
**NOTE** that the options provided under the `Debug` mode and the exact format of the output they create is **NOT** considered to be an officially supported API of Perl. It is intended for debugging only and may change as the core development team deems appropriate without notice or deprecation in any release of Perl, major or minor. Any documentation of the format or options available is advisory only and is subject to change without notice.
The options are as follows:
Compile related options COMPILE Turns on all non-extra compile related debug options.
PARSE Turns on debug output related to the process of parsing the pattern.
OPTIMISE Enables output related to the optimisation phase of compilation.
TRIEC Detailed info about trie compilation.
DUMP Dump the final program out after it is compiled and optimised.
FLAGS Dump the flags associated with the program
TEST Print output intended for testing the internals of the compile process
Execute related options EXECUTE Turns on all non-extra execute related debug options.
MATCH Turns on debugging of the main matching loop.
TRIEE Extra debugging of how tries execute.
INTUIT Enable debugging of start-point optimisations.
Extra debugging options EXTRA Turns on all "extra" debugging options.
BUFFERS Enable debugging the capture group storage during match. Warning, this can potentially produce extremely large output.
TRIEM Enable enhanced TRIE debugging. Enhances both TRIEE and TRIEC.
STATE Enable debugging of states in the engine.
STACK Enable debugging of the recursion stack in the engine. Enabling or disabling this option automatically does the same for debugging states as well. This output from this can be quite large.
GPOS Enable debugging of the \G modifier.
OPTIMISEM Enable enhanced optimisation debugging and start-point optimisations. Probably not useful except when debugging the regexp engine itself.
DUMP\_PRE\_OPTIMIZE Enable the dumping of the compiled pattern before the optimization phase.
WILDCARD When Perl encounters a wildcard subpattern, (see ["Wildcards in Property Values" in perlunicode](perlunicode#Wildcards-in-Property-Values)), it suspends compilation of the main pattern, compiles the subpattern, and then matches that against all legal possibilities to determine the actual code points the subpattern matches. After that it adds these to the main pattern, and continues its compilation.
You may very well want to see how your subpattern gets compiled, but it is likely of less use to you to see how Perl matches that against all the legal possibilities, as that is under control of Perl, not you. Therefore, the debugging information of the compilation portion is as specified by the other options, but the debugging output of the matching portion is normally suppressed.
You can use the WILDCARD option to enable the debugging output of this subpattern matching. Careful! This can lead to voluminous outputs, and it may not make much sense to you what and why Perl is doing what it is. But it may be helpful to you to see why things aren't going the way you expect.
Note that this option alone doesn't cause any debugging information to be output. What it does is stop the normal suppression of execution-related debugging information during the matching portion of the compilation of wildcards. You also have to specify which execution debugging information you want, such as by also including the EXECUTE option.
Other useful flags These are useful shortcuts to save on the typing.
ALL Enable all options at once except BUFFERS, WILDCARD, and DUMP\_PRE\_OPTIMIZE. (To get every single option without exception, use both ALL and EXTRA, or starting in 5.30 on a `-DDEBUGGING`-enabled perl interpreter, use the **-Drv** command-line switches.)
All Enable DUMP and all non-extra execute options. Equivalent to:
```
use re 'debug';
```
MORE More Enable the options enabled by "All", plus STATE, TRIEC, and TRIEM.
As of 5.9.5 the directive `use re 'debug'` and its equivalents are lexically scoped, as are the other directives. However they have both compile-time and run-time effects.
###
Exportable Functions
As of perl 5.9.5 're' debug contains a number of utility functions that may be optionally exported into the caller's namespace. They are listed below.
is\_regexp($ref) Returns true if the argument is a compiled regular expression as returned by `qr//`, false if it is not.
This function will not be confused by overloading or blessing. In internals terms, this extracts the regexp pointer out of the PERL\_MAGIC\_qr structure so it cannot be fooled.
regexp\_pattern($ref) If the argument is a compiled regular expression as returned by `qr//`, then this function returns the pattern.
In list context it returns a two element list, the first element containing the pattern and the second containing the modifiers used when the pattern was compiled.
```
my ($pat, $mods) = regexp_pattern($ref);
```
In scalar context it returns the same as perl would when stringifying a raw `qr//` with the same pattern inside. If the argument is not a compiled reference then this routine returns false but defined in scalar context, and the empty list in list context. Thus the following
```
if (regexp_pattern($ref) eq '(?^i:foo)')
```
will be warning free regardless of what $ref actually is.
Like `is_regexp` this function will not be confused by overloading or blessing of the object.
regname($name,$all) Returns the contents of a named buffer of the last successful match. If $all is true, then returns an array ref containing one entry per buffer, otherwise returns the first defined buffer.
regnames($all) Returns a list of all of the named buffers defined in the last successful match. If $all is true, then it returns all names defined, if not it returns only names which were involved in the match.
regnames\_count() Returns the number of distinct names defined in the pattern used for the last successful match.
**Note:** this result is always the actual number of distinct named buffers defined, it may not actually match that which is returned by `regnames()` and related routines when those routines have not been called with the $all parameter set.
regmust($ref) If the argument is a compiled regular expression as returned by `qr//`, then this function returns what the optimiser considers to be the longest anchored fixed string and longest floating fixed string in the pattern.
A *fixed string* is defined as being a substring that must appear for the pattern to match. An *anchored fixed string* is a fixed string that must appear at a particular offset from the beginning of the match. A *floating fixed string* is defined as a fixed string that can appear at any point in a range of positions relative to the start of the match. For example,
```
my $qr = qr/here .* there/x;
my ($anchored, $floating) = regmust($qr);
print "anchored:'$anchored'\nfloating:'$floating'\n";
```
results in
```
anchored:'here'
floating:'there'
```
Because the `here` is before the `.*` in the pattern, its position can be determined exactly. That's not true, however, for the `there`; it could appear at any point after where the anchored string appeared. Perl uses both for its optimisations, preferring the longer, or, if they are equal, the floating.
**NOTE:** This may not necessarily be the definitive longest anchored and floating string. This will be what the optimiser of the Perl that you are using thinks is the longest. If you believe that the result is wrong please report it via the <perlbug> utility.
optimization($ref) If the argument is a compiled regular expression as returned by `qr//`, then this function returns a hashref of the optimization information discovered at compile time, so we can write tests around it. If any other argument is given, returns `undef`.
The hash contents are expected to change from time to time as we develop new ways to optimize - no assumption of stability should be made, not even between minor versions of perl.
For the current version, the hash will have the following contents:
minlen An integer, the least number of characters in any string that can match.
minlenret An integer, the least number of characters that can be in `$&` after a match. (Consider eg `/ns(?=\d)/` .)
gofs An integer, the number of characters before `pos()` to start match at.
noscan A boolean, `TRUE` to indicate that any anchored/floating substrings found should not be used. (CHECKME: apparently this is set for an anchored pattern with no floating substring, but never used.)
isall A boolean, `TRUE` to indicate that the optimizer information is all that the regular expression contains, and thus one does not need to enter the regexp runtime engine at all.
anchor SBOL A boolean, `TRUE` if the pattern is anchored to start of string.
anchor MBOL A boolean, `TRUE` if the pattern is anchored to any start of line within the string.
anchor GPOS A boolean, `TRUE` if the pattern is anchored to the end of the previous match.
skip A boolean, `TRUE` if the start class can match only the first of a run.
implicit A boolean, `TRUE` if a `/.*/` has been turned implicitly into a `/^.*/`.
anchored/floating A byte string representing an anchored or floating substring respectively that any match must contain, or undef if no such substring was found, or if the substring would require utf8 to represent.
anchored utf8/floating utf8 A utf8 string representing an anchored or floating substring respectively that any match must contain, or undef if no such substring was found, or if the substring contains only 7-bit ASCII characters.
anchored min offset/floating min offset An integer, the first offset in characters from a match location at which we should look for the corresponding substring.
anchored max offset/floating max offset An integer, the last offset in characters from a match location at which we should look for the corresponding substring.
Ignored for anchored, so may be 0 or same as min.
anchored end shift/floating end shift FIXME: not sure what this is, something to do with lookbehind. regcomp.c says: When the final pattern is compiled and the data is moved from the scan\_data\_t structure into the regexp structure the information about lookbehind is factored in, with the information that would have been lost precalculated in the end\_shift field for the associated string.
checking A constant string, one of "anchored", "floating" or "none" to indicate which substring (if any) should be checked for first.
stclass A string representation of a character class ("start class") that must be the first character of any match.
TODO: explain the representations.
SEE ALSO
---------
["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules).
| programming_docs |
perl perlfaq6 perlfaq6
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [How can I hope to use regular expressions without creating illegible and unmaintainable code?](#How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code?)
+ [I'm having trouble matching over more than one line. What's wrong?](#I'm-having-trouble-matching-over-more-than-one-line.-What's-wrong?)
+ [How can I pull out lines between two patterns that are themselves on different lines?](#How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines?)
+ [How do I match XML, HTML, or other nasty, ugly things with a regex?](#How-do-I-match-XML,-HTML,-or-other-nasty,-ugly-things-with-a-regex?)
+ [I put a regular expression into $/ but it didn't work. What's wrong?](#I-put-a-regular-expression-into-%24/-but-it-didn't-work.-What's-wrong?)
+ [How do I substitute case-insensitively on the LHS while preserving case on the RHS?](#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS?)
+ [How can I make \w match national character sets?](#How-can-I-make-%5Cw-match-national-character-sets?)
+ [How can I match a locale-smart version of /[a-zA-Z]/?](#How-can-I-match-a-locale-smart-version-of-/%5Ba-zA-Z%5D/?)
+ [How can I quote a variable to use in a regex?](#How-can-I-quote-a-variable-to-use-in-a-regex?)
+ [What is /o really for?](#What-is-/o-really-for?)
+ [How do I use a regular expression to strip C-style comments from a file?](#How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file?)
+ [Can I use Perl regular expressions to match balanced text?](#Can-I-use-Perl-regular-expressions-to-match-balanced-text?)
+ [What does it mean that regexes are greedy? How can I get around it?](#What-does-it-mean-that-regexes-are-greedy?-How-can-I-get-around-it?)
+ [How do I process each word on each line?](#How-do-I-process-each-word-on-each-line?)
+ [How can I print out a word-frequency or line-frequency summary?](#How-can-I-print-out-a-word-frequency-or-line-frequency-summary?)
+ [How can I do approximate matching?](#How-can-I-do-approximate-matching?)
+ [How do I efficiently match many regular expressions at once?](#How-do-I-efficiently-match-many-regular-expressions-at-once?)
+ [Why don't word-boundary searches with \b work for me?](#Why-don't-word-boundary-searches-with-%5Cb-work-for-me?)
+ [Why does using $&, $`, or $' slow my program down?](#Why-does-using-%24&,-%24%60,-or-%24'-slow-my-program-down?)
+ [What good is \G in a regular expression?](#What-good-is-%5CG-in-a-regular-expression?)
+ [Are Perl regexes DFAs or NFAs? Are they POSIX compliant?](#Are-Perl-regexes-DFAs-or-NFAs?-Are-they-POSIX-compliant?)
+ [What's wrong with using grep in a void context?](#What's-wrong-with-using-grep-in-a-void-context?)
+ [How can I match strings with multibyte characters?](#How-can-I-match-strings-with-multibyte-characters?)
+ [How do I match a regular expression that's in a variable?](#How-do-I-match-a-regular-expression-that's-in-a-variable?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq6 - Regular Expressions
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number can be handled with regular expressions, but those answers are found elsewhere in this document (in <perlfaq9>: "How do I decode or create those %-encodings on the web" and <perlfaq4>: "How do I determine whether a scalar is a number/whole/integer/float", to be precise).
###
How can I hope to use regular expressions without creating illegible and unmaintainable code?
Three techniques can make regular expressions maintainable and understandable.
Comments Outside the Regex Describe what you're doing and how you're doing it, using normal Perl comments.
```
# turn the line into the first word, a colon, and the
# number of characters on the rest of the line
s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
```
Comments Inside the Regex The `/x` modifier causes whitespace to be ignored in a regex pattern (except in a character class and a few other places), and also allows you to use normal comments there, too. As you can imagine, whitespace and comments help a lot.
`/x` lets you turn this:
```
s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
```
into this:
```
s{ < # opening angle bracket
(?: # Non-backreffing grouping paren
[^>'"] * # 0 or more things that are neither > nor ' nor "
| # or else
".*?" # a section between double quotes (stingy match)
| # or else
'.*?' # a section between single quotes (stingy match)
) + # all occurring one or more times
> # closing angle bracket
}{}gsx; # replace with nothing, i.e. delete
```
It's still not quite so clear as prose, but it is very useful for describing the meaning of each part of the pattern.
Different Delimiters While we normally think of patterns as being delimited with `/` characters, they can be delimited by almost any character. <perlre> describes this. For example, the `s///` above uses braces as delimiters. Selecting another delimiter can avoid quoting the delimiter within the pattern:
```
s/\/usr\/local/\/usr\/share/g; # bad delimiter choice
s#/usr/local#/usr/share#g; # better
```
Using logically paired delimiters can be even more readable:
```
s{/usr/local/}{/usr/share}g; # better still
```
###
I'm having trouble matching over more than one line. What's wrong?
Either you don't have more than one line in the string you're looking at (probably), or else you aren't using the correct modifier(s) on your pattern (possibly).
There are many ways to get multiline data into a string. If you want it to happen automatically while reading input, you'll want to set $/ (probably to '' for paragraphs or `undef` for the whole file) to allow you to read more than one line at a time.
Read <perlre> to help you decide which of `/s` and `/m` (or both) you might want to use: `/s` allows dot to include newline, and `/m` allows caret and dollar to match next to a newline, not just at the end of the string. You do need to make sure that you've actually got a multiline string in there.
For example, this program detects duplicate words, even when they span line breaks (but not paragraph ones). For this example, we don't need `/s` because we aren't using dot in a regular expression that we want to cross line boundaries. Neither do we need `/m` because we don't want caret or dollar to match at any point inside the record next to newlines. But it's imperative that $/ be set to something other than the default, or else we won't actually ever have a multiline record read in.
```
$/ = ''; # read in whole paragraph, not just one line
while ( <> ) {
while ( /\b([\w'-]+)(\s+\g1)+\b/gi ) { # word starts alpha
print "Duplicate $1 at paragraph $.\n";
}
}
```
Here's some code that finds sentences that begin with "From " (which would be mangled by many mailers):
```
$/ = ''; # read in whole paragraph, not just one line
while ( <> ) {
while ( /^From /gm ) { # /m makes ^ match next to \n
print "leading From in paragraph $.\n";
}
}
```
Here's code that finds everything between START and END in a paragraph:
```
undef $/; # read in whole file, not just one line or paragraph
while ( <> ) {
while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
print "$1\n";
}
}
```
###
How can I pull out lines between two patterns that are themselves on different lines?
You can use Perl's somewhat exotic `..` operator (documented in <perlop>):
```
perl -ne 'print if /START/ .. /END/' file1 file2 ...
```
If you wanted text and not lines, you would use
```
perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
```
But if you want nested occurrences of `START` through `END`, you'll run up against the problem described in the question in this section on matching balanced text.
Here's another example of using `..`:
```
while (<>) {
my $in_header = 1 .. /^$/;
my $in_body = /^$/ .. eof;
# now choose between them
} continue {
$. = 0 if eof; # fix $.
}
```
###
How do I match XML, HTML, or other nasty, ugly things with a regex?
Do not use regexes. Use a module and forget about the regular expressions. The <XML::LibXML>, <HTML::TokeParser> and <HTML::TreeBuilder> modules are good starts, although each namespace has other parsing modules specialized for certain tasks and different ways of doing it. Start at CPAN Search ( <http://metacpan.org/> ) and wonder at all the work people have done for you already! :)
###
I put a regular expression into $/ but it didn't work. What's wrong?
$/ has to be a string. You can use these examples if you really need to do this.
If you have <File::Stream>, this is easy.
```
use File::Stream;
my $stream = File::Stream->new(
$filehandle,
separator => qr/\s*,\s*/,
);
print "$_\n" while <$stream>;
```
If you don't have File::Stream, you have to do a little more work.
You can use the four-argument form of sysread to continually add to a buffer. After you add to the buffer, you check if you have a complete line (using your regular expression).
```
local $_ = "";
while( sysread FH, $_, 8192, length ) {
while( s/^((?s).*?)your_pattern// ) {
my $record = $1;
# do stuff here.
}
}
```
You can do the same thing with foreach and a match using the c flag and the \G anchor, if you do not mind your entire file being in memory at the end.
```
local $_ = "";
while( sysread FH, $_, 8192, length ) {
foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
# do stuff here.
}
substr( $_, 0, pos ) = "" if pos;
}
```
###
How do I substitute case-insensitively on the LHS while preserving case on the RHS?
Here's a lovely Perlish solution by Larry Rosler. It exploits properties of bitwise xor on ASCII strings.
```
$_= "this is a TEsT case";
$old = 'test';
$new = 'success';
s{(\Q$old\E)}
{ uc $new | (uc $1 ^ $1) .
(uc(substr $1, -1) ^ substr $1, -1) x
(length($new) - length $1)
}egi;
print;
```
And here it is as a subroutine, modeled after the above:
```
sub preserve_case {
my ($old, $new) = @_;
my $mask = uc $old ^ $old;
uc $new | $mask .
substr($mask, -1) x (length($new) - length($old))
}
$string = "this is a TEsT case";
$string =~ s/(test)/preserve_case($1, "success")/egi;
print "$string\n";
```
This prints:
```
this is a SUcCESS case
```
As an alternative, to keep the case of the replacement word if it is longer than the original, you can use this code, by Jeff Pinyan:
```
sub preserve_case {
my ($from, $to) = @_;
my ($lf, $lt) = map length, @_;
if ($lt < $lf) { $from = substr $from, 0, $lt }
else { $from .= substr $to, $lf }
return uc $to | ($from ^ uc $from);
}
```
This changes the sentence to "this is a SUcCess case."
Just to show that C programmers can write C in any programming language, if you prefer a more C-like solution, the following script makes the substitution have the same case, letter by letter, as the original. (It also happens to run about 240% slower than the Perlish solution runs.) If the substitution has more characters than the string being substituted, the case of the last character is used for the rest of the substitution.
```
# Original by Nathan Torkington, massaged by Jeffrey Friedl
#
sub preserve_case
{
my ($old, $new) = @_;
my $state = 0; # 0 = no change; 1 = lc; 2 = uc
my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
my $len = $oldlen < $newlen ? $oldlen : $newlen;
for ($i = 0; $i < $len; $i++) {
if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
$state = 0;
} elsif (lc $c eq $c) {
substr($new, $i, 1) = lc(substr($new, $i, 1));
$state = 1;
} else {
substr($new, $i, 1) = uc(substr($new, $i, 1));
$state = 2;
}
}
# finish up with any remaining new (for when new is longer than old)
if ($newlen > $oldlen) {
if ($state == 1) {
substr($new, $oldlen) = lc(substr($new, $oldlen));
} elsif ($state == 2) {
substr($new, $oldlen) = uc(substr($new, $oldlen));
}
}
return $new;
}
```
###
How can I make `\w` match national character sets?
Put `use locale;` in your script. The \w character class is taken from the current locale.
See <perllocale> for details.
###
How can I match a locale-smart version of `/[a-zA-Z]/`?
You can use the POSIX character class syntax `/[[:alpha:]]/` documented in <perlre>.
No matter which locale you are in, the alphabetic characters are the characters in \w without the digits and the underscore. As a regex, that looks like `/[^\W\d_]/`. Its complement, the non-alphabetics, is then everything in \W along with the digits and the underscore, or `/[\W\d_]/`.
###
How can I quote a variable to use in a regex?
The Perl parser will expand $variable and @variable references in regular expressions unless the delimiter is a single quote. Remember, too, that the right-hand side of a `s///` substitution is considered a double-quoted string (see <perlop> for more details). Remember also that any regex special characters will be acted on unless you precede the substitution with \Q. Here's an example:
```
$string = "Placido P. Octopus";
$regex = "P.";
$string =~ s/$regex/Polyp/;
# $string is now "Polypacido P. Octopus"
```
Because `.` is special in regular expressions, and can match any single character, the regex `P.` here has matched the <Pl> in the original string.
To escape the special meaning of `.`, we use `\Q`:
```
$string = "Placido P. Octopus";
$regex = "P.";
$string =~ s/\Q$regex/Polyp/;
# $string is now "Placido Polyp Octopus"
```
The use of `\Q` causes the `.` in the regex to be treated as a regular character, so that `P.` matches a `P` followed by a dot.
###
What is `/o` really for?
(contributed by brian d foy)
The `/o` option for regular expressions (documented in <perlop> and <perlreref>) tells Perl to compile the regular expression only once. This is only useful when the pattern contains a variable. Perls 5.6 and later handle this automatically if the pattern does not change.
Since the match operator `m//`, the substitution operator `s///`, and the regular expression quoting operator `qr//` are double-quotish constructs, you can interpolate variables into the pattern. See the answer to "How can I quote a variable to use in a regex?" for more details.
This example takes a regular expression from the argument list and prints the lines of input that match it:
```
my $pattern = shift @ARGV;
while( <> ) {
print if m/$pattern/;
}
```
Versions of Perl prior to 5.6 would recompile the regular expression for each iteration, even if `$pattern` had not changed. The `/o` would prevent this by telling Perl to compile the pattern the first time, then reuse that for subsequent iterations:
```
my $pattern = shift @ARGV;
while( <> ) {
print if m/$pattern/o; # useful for Perl < 5.6
}
```
In versions 5.6 and later, Perl won't recompile the regular expression if the variable hasn't changed, so you probably don't need the `/o` option. It doesn't hurt, but it doesn't help either. If you want any version of Perl to compile the regular expression only once even if the variable changes (thus, only using its initial value), you still need the `/o`.
You can watch Perl's regular expression engine at work to verify for yourself if Perl is recompiling a regular expression. The `use re 'debug'` pragma (comes with Perl 5.005 and later) shows the details. With Perls before 5.6, you should see `re` reporting that its compiling the regular expression on each iteration. With Perl 5.6 or later, you should only see `re` report that for the first iteration.
```
use re 'debug';
my $regex = 'Perl';
foreach ( qw(Perl Java Ruby Python) ) {
print STDERR "-" x 73, "\n";
print STDERR "Trying $_...\n";
print STDERR "\t$_ is good!\n" if m/$regex/;
}
```
###
How do I use a regular expression to strip C-style comments from a file?
While this actually can be done, it's much harder than you'd think. For example, this one-liner
```
perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
```
will work in many but not all cases. You see, it's too simple-minded for certain kinds of C programs, in particular, those with what appear to be comments in quoted strings. For that, you'd need something like this, created by Jeffrey Friedl and later modified by Fred Curtis.
```
$/ = undef;
$_ = <>;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
print;
```
This could, of course, be more legibly written with the `/x` modifier, adding whitespace and comments. Here it is expanded, courtesy of Fred Curtis.
```
s{
/\* ## Start of /* ... */ comment
[^*]*\*+ ## Non-* followed by 1-or-more *'s
(
[^/*][^*]*\*+
)* ## 0-or-more things which don't start with /
## but do end with '*'
/ ## End of /* ... */ comment
| ## OR various things which aren't comments:
(
" ## Start of " ... " string
(
\\. ## Escaped char
| ## OR
[^"\\] ## Non "\
)*
" ## End of " ... " string
| ## OR
' ## Start of ' ... ' string
(
\\. ## Escaped char
| ## OR
[^'\\] ## Non '\
)*
' ## End of ' ... ' string
| ## OR
. ## Anything other char
[^/"'\\]* ## Chars which doesn't start a comment, string or escape
)
}{defined $2 ? $2 : ""}gxse;
```
A slight modification also removes C++ comments, possibly spanning multiple lines using a continuation character:
```
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $3 ? $3 : ""#gse;
```
###
Can I use Perl regular expressions to match balanced text?
(contributed by brian d foy)
Your first try should probably be the <Text::Balanced> module, which is in the Perl standard library since Perl 5.8. It has a variety of functions to deal with tricky text. The <Regexp::Common> module can also help by providing canned patterns you can use.
As of Perl 5.10, you can match balanced text with regular expressions using recursive patterns. Before Perl 5.10, you had to resort to various tricks such as using Perl code in `(??{})` sequences.
Here's an example using a recursive regular expression. The goal is to capture all of the text within angle brackets, including the text in nested angle brackets. This sample text has two "major" groups: a group with one level of nesting and a group with two levels of nesting. There are five total groups in angle brackets:
```
I have some <brackets in <nested brackets> > and
<another group <nested once <nested twice> > >
and that's it.
```
The regular expression to match the balanced text uses two new (to Perl 5.10) regular expression features. These are covered in <perlre> and this example is a modified version of one in that documentation.
First, adding the new possessive `+` to any quantifier finds the longest match and does not backtrack. That's important since you want to handle any angle brackets through the recursion, not backtracking. The group `[^<>]++` finds one or more non-angle brackets without backtracking.
Second, the new `(?PARNO)` refers to the sub-pattern in the particular capture group given by `PARNO`. In the following regex, the first capture group finds (and remembers) the balanced text, and you need that same pattern within the first buffer to get past the nested text. That's the recursive part. The `(?1)` uses the pattern in the outer capture group as an independent part of the regex.
Putting it all together, you have:
```
#!/usr/local/bin/perl5.10.0
my $string =<<"HERE";
I have some <brackets in <nested brackets> > and
<another group <nested once <nested twice> > >
and that's it.
HERE
my @groups = $string =~ m/
( # start of capture group 1
< # match an opening angle bracket
(?:
[^<>]++ # one or more non angle brackets, non backtracking
|
(?1) # found < or >, so recurse to capture group 1
)*
> # match a closing angle bracket
) # end of capture group 1
/xg;
$" = "\n\t";
print "Found:\n\t@groups\n";
```
The output shows that Perl found the two major groups:
```
Found:
<brackets in <nested brackets> >
<another group <nested once <nested twice> > >
```
With a little extra work, you can get all of the groups in angle brackets even if they are in other angle brackets too. Each time you get a balanced match, remove its outer delimiter (that's the one you just matched so don't match it again) and add it to a queue of strings to process. Keep doing that until you get no matches:
```
#!/usr/local/bin/perl5.10.0
my @queue =<<"HERE";
I have some <brackets in <nested brackets> > and
<another group <nested once <nested twice> > >
and that's it.
HERE
my $regex = qr/
( # start of bracket 1
< # match an opening angle bracket
(?:
[^<>]++ # one or more non angle brackets, non backtracking
|
(?1) # recurse to bracket 1
)*
> # match a closing angle bracket
) # end of bracket 1
/x;
$" = "\n\t";
while( @queue ) {
my $string = shift @queue;
my @groups = $string =~ m/$regex/g;
print "Found:\n\t@groups\n\n" if @groups;
unshift @queue, map { s/^<//; s/>$//; $_ } @groups;
}
```
The output shows all of the groups. The outermost matches show up first and the nested matches show up later:
```
Found:
<brackets in <nested brackets> >
<another group <nested once <nested twice> > >
Found:
<nested brackets>
Found:
<nested once <nested twice> >
Found:
<nested twice>
```
###
What does it mean that regexes are greedy? How can I get around it?
Most people mean that greedy regexes match as much as they can. Technically speaking, it's actually the quantifiers (`?`, `*`, `+`, `{}`) that are greedy rather than the whole pattern; Perl prefers local greed and immediate gratification to overall greed. To get non-greedy versions of the same quantifiers, use (`??`, `*?`, `+?`, `{}?`).
An example:
```
my $s1 = my $s2 = "I am very very cold";
$s1 =~ s/ve.*y //; # I am cold
$s2 =~ s/ve.*?y //; # I am very cold
```
Notice how the second substitution stopped matching as soon as it encountered "y ". The `*?` quantifier effectively tells the regular expression engine to find a match as quickly as possible and pass control on to whatever is next in line, as you would if you were playing hot potato.
###
How do I process each word on each line?
Use the split function:
```
while (<>) {
foreach my $word ( split ) {
# do something with $word here
}
}
```
Note that this isn't really a word in the English sense; it's just chunks of consecutive non-whitespace characters.
To work with only alphanumeric sequences (including underscores), you might consider
```
while (<>) {
foreach $word (m/(\w+)/g) {
# do something with $word here
}
}
```
###
How can I print out a word-frequency or line-frequency summary?
To do this, you have to parse out each word in the input stream. We'll pretend that by word you mean chunk of alphabetics, hyphens, or apostrophes, rather than the non-whitespace chunk idea of a word given in the previous question:
```
my (%seen);
while (<>) {
while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'"
$seen{$1}++;
}
}
while ( my ($word, $count) = each %seen ) {
print "$count $word\n";
}
```
If you wanted to do the same thing for lines, you wouldn't need a regular expression:
```
my (%seen);
while (<>) {
$seen{$_}++;
}
while ( my ($line, $count) = each %seen ) {
print "$count $line";
}
```
If you want these output in a sorted order, see <perlfaq4>: "How do I sort a hash (optionally by value instead of key)?".
###
How can I do approximate matching?
See the module <String::Approx> available from CPAN.
###
How do I efficiently match many regular expressions at once?
(contributed by brian d foy)
You want to avoid compiling a regular expression every time you want to match it. In this example, perl must recompile the regular expression for every iteration of the `foreach` loop since `$pattern` can change:
```
my @patterns = qw( fo+ ba[rz] );
LINE: while( my $line = <> ) {
foreach my $pattern ( @patterns ) {
if( $line =~ m/\b$pattern\b/i ) {
print $line;
next LINE;
}
}
}
```
The `qr//` operator compiles a regular expression, but doesn't apply it. When you use the pre-compiled version of the regex, perl does less work. In this example, I inserted a `map` to turn each pattern into its pre-compiled form. The rest of the script is the same, but faster:
```
my @patterns = map { qr/\b$_\b/i } qw( fo+ ba[rz] );
LINE: while( my $line = <> ) {
foreach my $pattern ( @patterns ) {
if( $line =~ m/$pattern/ ) {
print $line;
next LINE;
}
}
}
```
In some cases, you may be able to make several patterns into a single regular expression. Beware of situations that require backtracking though. In this example, the regex is only compiled once because `$regex` doesn't change between iterations:
```
my $regex = join '|', qw( fo+ ba[rz] );
while( my $line = <> ) {
print if $line =~ m/\b(?:$regex)\b/i;
}
```
The function ["list2re" in Data::Munge](Data::Munge#list2re) on CPAN can also be used to form a single regex that matches a list of literal strings (not regexes).
For more details on regular expression efficiency, see *Mastering Regular Expressions* by Jeffrey Friedl. He explains how the regular expressions engine works and why some patterns are surprisingly inefficient. Once you understand how perl applies regular expressions, you can tune them for individual situations.
###
Why don't word-boundary searches with `\b` work for me?
(contributed by brian d foy)
Ensure that you know what \b really does: it's the boundary between a word character, \w, and something that isn't a word character. That thing that isn't a word character might be \W, but it can also be the start or end of the string.
It's not (not!) the boundary between whitespace and non-whitespace, and it's not the stuff between words we use to create sentences.
In regex speak, a word boundary (\b) is a "zero width assertion", meaning that it doesn't represent a character in the string, but a condition at a certain position.
For the regular expression, /\bPerl\b/, there has to be a word boundary before the "P" and after the "l". As long as something other than a word character precedes the "P" and succeeds the "l", the pattern will match. These strings match /\bPerl\b/.
```
"Perl" # no word char before "P" or after "l"
"Perl " # same as previous (space is not a word char)
"'Perl'" # the "'" char is not a word char
"Perl's" # no word char before "P", non-word char after "l"
```
These strings do not match /\bPerl\b/.
```
"Perl_" # "_" is a word char!
"Perler" # no word char before "P", but one after "l"
```
You don't have to use \b to match words though. You can look for non-word characters surrounded by word characters. These strings match the pattern /\b'\b/.
```
"don't" # the "'" char is surrounded by "n" and "t"
"qep'a'" # the "'" char is surrounded by "p" and "a"
```
These strings do not match /\b'\b/.
```
"foo'" # there is no word char after non-word "'"
```
You can also use the complement of \b, \B, to specify that there should not be a word boundary.
In the pattern /\Bam\B/, there must be a word character before the "a" and after the "m". These patterns match /\Bam\B/:
```
"llama" # "am" surrounded by word chars
"Samuel" # same
```
These strings do not match /\Bam\B/
```
"Sam" # no word boundary before "a", but one after "m"
"I am Sam" # "am" surrounded by non-word chars
```
###
Why does using $&, $`, or $' slow my program down?
(contributed by Anno Siegel)
Once Perl sees that you need one of these variables anywhere in the program, it provides them on each and every pattern match. That means that on every pattern match the entire string will be copied, part of it to $`, part to $&, and part to $'. Thus the penalty is most severe with long strings and patterns that match often. Avoid $&, $', and $` if you can, but if you can't, once you've used them at all, use them at will because you've already paid the price. Remember that some algorithms really appreciate them. As of the 5.005 release, the $& variable is no longer "expensive" the way the other two are.
Since Perl 5.6.1 the special variables @- and @+ can functionally replace $`, $& and $'. These arrays contain pointers to the beginning and end of each match (see perlvar for the full story), so they give you essentially the same information, but without the risk of excessive string copying.
Perl 5.10 added three specials, `${^MATCH}`, `${^PREMATCH}`, and `${^POSTMATCH}` to do the same job but without the global performance penalty. Perl 5.10 only sets these variables if you compile or execute the regular expression with the `/p` modifier.
###
What good is `\G` in a regular expression?
You use the `\G` anchor to start the next match on the same string where the last match left off. The regular expression engine cannot skip over any characters to find the next match with this anchor, so `\G` is similar to the beginning of string anchor, `^`. The `\G` anchor is typically used with the `g` modifier. It uses the value of `pos()` as the position to start the next match. As the match operator makes successive matches, it updates `pos()` with the position of the next character past the last match (or the first character of the next match, depending on how you like to look at it). Each string has its own `pos()` value.
Suppose you want to match all of consecutive pairs of digits in a string like "1122a44" and stop matching when you encounter non-digits. You want to match `11` and `22` but the letter `a` shows up between `22` and `44` and you want to stop at `a`. Simply matching pairs of digits skips over the `a` and still matches `44`.
```
$_ = "1122a44";
my @pairs = m/(\d\d)/g; # qw( 11 22 44 )
```
If you use the `\G` anchor, you force the match after `22` to start with the `a`. The regular expression cannot match there since it does not find a digit, so the next match fails and the match operator returns the pairs it already found.
```
$_ = "1122a44";
my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
```
You can also use the `\G` anchor in scalar context. You still need the `g` modifier.
```
$_ = "1122a44";
while( m/\G(\d\d)/g ) {
print "Found $1\n";
}
```
After the match fails at the letter `a`, perl resets `pos()` and the next match on the same string starts at the beginning.
```
$_ = "1122a44";
while( m/\G(\d\d)/g ) {
print "Found $1\n";
}
print "Found $1 after while" if m/(\d\d)/g; # finds "11"
```
You can disable `pos()` resets on fail with the `c` modifier, documented in <perlop> and <perlreref>. Subsequent matches start where the last successful match ended (the value of `pos()`) even if a match on the same string has failed in the meantime. In this case, the match after the `while()` loop starts at the `a` (where the last match stopped), and since it does not use any anchor it can skip over the `a` to find `44`.
```
$_ = "1122a44";
while( m/\G(\d\d)/gc ) {
print "Found $1\n";
}
print "Found $1 after while" if m/(\d\d)/g; # finds "44"
```
Typically you use the `\G` anchor with the `c` modifier when you want to try a different match if one fails, such as in a tokenizer. Jeffrey Friedl offers this example which works in 5.004 or later.
```
while (<>) {
chomp;
PARSER: {
m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; };
m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; };
m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; };
m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; };
}
}
```
For each line, the `PARSER` loop first tries to match a series of digits followed by a word boundary. This match has to start at the place the last match left off (or the beginning of the string on the first match). Since `m/ \G( \d+\b )/gcx` uses the `c` modifier, if the string does not match that regular expression, perl does not reset pos() and the next match starts at the same position to try a different pattern.
###
Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
While it's true that Perl's regular expressions resemble the DFAs (deterministic finite automata) of the egrep(1) program, they are in fact implemented as NFAs (non-deterministic finite automata) to allow backtracking and backreferencing. And they aren't POSIX-style either, because those guarantee worst-case behavior for all cases. (It seems that some people prefer guarantees of consistency, even when what's guaranteed is slowness.) See the book "Mastering Regular Expressions" (from O'Reilly) by Jeffrey Friedl for all the details you could ever hope to know on these matters (a full citation appears in <perlfaq2>).
###
What's wrong with using grep in a void context?
The problem is that grep builds a return list, regardless of the context. This means you're making Perl go to the trouble of building a list that you then just throw away. If the list is large, you waste both time and space. If your intent is to iterate over the list, then use a for loop for this purpose.
In perls older than 5.8.1, map suffers from this problem as well. But since 5.8.1, this has been fixed, and map is context aware - in void context, no lists are constructed.
###
How can I match strings with multibyte characters?
Starting from Perl 5.6 Perl has had some level of multibyte character support. Perl 5.8 or later is recommended. Supported multibyte character repertoires include Unicode, and legacy encodings through the Encode module. See <perluniintro>, <perlunicode>, and [Encode](encode).
If you are stuck with older Perls, you can do Unicode with the <Unicode::String> module, and character conversions using the <Unicode::Map8> and <Unicode::Map> modules. If you are using Japanese encodings, you might try using the jperl 5.005\_03.
Finally, the following set of approaches was offered by Jeffrey Friedl, whose article in issue #5 of The Perl Journal talks about this very matter.
Let's suppose you have some weird Martian encoding where pairs of ASCII uppercase letters encode single Martian letters (i.e. the two bytes "CV" make a single Martian letter, as do the two bytes "SG", "VS", "XX", etc.). Other bytes represent single characters, just like ASCII.
So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
Now, say you want to search for the single character `/GX/`. Perl doesn't know about Martian, so it'll find the two bytes "GX" in the "I am CVSGXX!" string, even though that character isn't there: it just looks like it is because "SG" is next to "XX", but there's no real "GX". This is a big problem.
Here are a few ways, all painful, to deal with it:
```
# Make sure adjacent "martian" bytes are no longer adjacent.
$martian =~ s/([A-Z][A-Z])/ $1 /g;
print "found GX!\n" if $martian =~ /GX/;
```
Or like this:
```
my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
# above is conceptually similar to: my @chars = $text =~ m/(.)/g;
#
foreach my $char (@chars) {
print "found GX!\n", last if $char eq 'GX';
}
```
Or like this:
```
while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded
if ($1 eq 'GX') {
print "found GX!\n";
last;
}
}
```
Here's another, slightly less painful, way to do it from Benjamin Goldberg, who uses a zero-width negative look-behind assertion.
```
print "found GX!\n" if $martian =~ m/
(?<![A-Z])
(?:[A-Z][A-Z])*?
GX
/x;
```
This succeeds if the "martian" character GX is in the string, and fails otherwise. If you don't like using (?<!), a zero-width negative look-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
It does have the drawback of putting the wrong thing in $-[0] and $+[0], but this usually can be worked around.
###
How do I match a regular expression that's in a variable?
(contributed by brian d foy)
We don't have to hard-code patterns into the match operator (or anything else that works with regular expressions). We can put the pattern in a variable for later use.
The match operator is a double quote context, so you can interpolate your variable just like a double quoted string. In this case, you read the regular expression as user input and store it in `$regex`. Once you have the pattern in `$regex`, you use that variable in the match operator.
```
chomp( my $regex = <STDIN> );
if( $string =~ m/$regex/ ) { ... }
```
Any regular expression special characters in `$regex` are still special, and the pattern still has to be valid or Perl will complain. For instance, in this pattern there is an unpaired parenthesis.
```
my $regex = "Unmatched ( paren";
"Two parens to bind them all" =~ m/$regex/;
```
When Perl compiles the regular expression, it treats the parenthesis as the start of a memory match. When it doesn't find the closing parenthesis, it complains:
```
Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE paren/ at script line 3.
```
You can get around this in several ways depending on our situation. First, if you don't want any of the characters in the string to be special, you can escape them with `quotemeta` before you use the string.
```
chomp( my $regex = <STDIN> );
$regex = quotemeta( $regex );
if( $string =~ m/$regex/ ) { ... }
```
You can also do this directly in the match operator using the `\Q` and `\E` sequences. The `\Q` tells Perl where to start escaping special characters, and the `\E` tells it where to stop (see <perlop> for more details).
```
chomp( my $regex = <STDIN> );
if( $string =~ m/\Q$regex\E/ ) { ... }
```
Alternately, you can use `qr//`, the regular expression quote operator (see <perlop> for more details). It quotes and perhaps compiles the pattern, and you can apply regular expression flags to the pattern.
```
chomp( my $input = <STDIN> );
my $regex = qr/$input/is;
$string =~ m/$regex/ # same as m/$input/is;
```
You might also want to trap any errors by wrapping an `eval` block around the whole thing.
```
chomp( my $input = <STDIN> );
eval {
if( $string =~ m/\Q$input\E/ ) { ... }
};
warn $@ if $@;
```
Or...
```
my $regex = eval { qr/$input/is };
if( defined $regex ) {
$string =~ m/$regex/;
}
else {
warn $@;
}
```
AUTHOR AND COPYRIGHT
---------------------
Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.
| programming_docs |
perl Pod::Simple::Text Pod::Simple::Text
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Text -- format Pod as plaintext
SYNOPSIS
--------
```
perl -MPod::Simple::Text -e \
"exit Pod::Simple::Text->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
This class is a formatter that takes Pod and renders it as wrapped plaintext.
Its wrapping is done by <Text::Wrap>, so you can change `$Text::Wrap::columns` as you like.
This is a subclass of <Pod::Simple> and inherits all its methods.
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::TextContent>, <Pod::Text>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl TAP::Parser::Aggregator TAP::Parser::Aggregator
=======================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [add](#add)
- [parsers](#parsers)
- [descriptions](#descriptions)
- [start](#start)
- [stop](#stop)
- [elapsed](#elapsed)
- [elapsed\_timestr](#elapsed_timestr)
- [all\_passed](#all_passed)
- [get\_status](#get_status)
+ [Summary methods](#Summary-methods)
- [total](#total)
- [has\_problems](#has_problems)
- [has\_errors](#has_errors)
- [todo\_failed](#todo_failed)
* [See Also](#See-Also)
NAME
----
TAP::Parser::Aggregator - Aggregate TAP::Parser results
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Aggregator;
my $aggregate = TAP::Parser::Aggregator->new;
$aggregate->add( 't/00-load.t', $load_parser );
$aggregate->add( 't/10-lex.t', $lex_parser );
my $summary = <<'END_SUMMARY';
Passed: %s
Failed: %s
Unexpectedly succeeded: %s
END_SUMMARY
printf $summary,
scalar $aggregate->passed,
scalar $aggregate->failed,
scalar $aggregate->todo_passed;
```
DESCRIPTION
-----------
`TAP::Parser::Aggregator` collects parser objects and allows reporting/querying their aggregate results.
METHODS
-------
###
Class Methods
#### `new`
```
my $aggregate = TAP::Parser::Aggregator->new;
```
Returns a new `TAP::Parser::Aggregator` object.
###
Instance Methods
#### `add`
```
$aggregate->add( $description => $parser );
```
The `$description` is usually a test file name (but only by convention.) It is used as a unique identifier (see e.g. ["parsers"](#parsers).) Reusing a description is a fatal error.
The `$parser` is a <TAP::Parser> object.
#### `parsers`
```
my $count = $aggregate->parsers;
my @parsers = $aggregate->parsers;
my @parsers = $aggregate->parsers(@descriptions);
```
In scalar context without arguments, this method returns the number of parsers aggregated. In list context without arguments, returns the parsers in the order they were added.
If `@descriptions` is given, these correspond to the keys used in each call to the add() method. Returns an array of the requested parsers (in the requested order) in list context or an array reference in scalar context.
Requesting an unknown identifier is a fatal error.
#### `descriptions`
Get an array of descriptions in the order in which they were added to the aggregator.
#### `start`
Call `start` immediately before adding any results to the aggregator. Among other times it records the start time for the test run.
#### `stop`
Call `stop` immediately after adding all test results to the aggregator.
#### `elapsed`
Elapsed returns a [Benchmark](benchmark) object that represents the running time of the aggregated tests. In order for `elapsed` to be valid you must call `start` before running the tests and `stop` immediately afterwards.
#### `elapsed_timestr`
Returns a formatted string representing the runtime returned by `elapsed()`. This lets the caller not worry about Benchmark.
#### `all_passed`
Return true if all the tests passed and no parse errors were detected.
#### `get_status`
Get a single word describing the status of the aggregated tests. Depending on the outcome of the tests returns 'PASS', 'FAIL' or 'NOTESTS'. This token is understood by <CPAN::Reporter>.
###
Summary methods
Each of the following methods will return the total number of corresponding tests if called in scalar context. If called in list context, returns the descriptions of the parsers which contain the corresponding tests (see `add` for an explanation of description.
* failed
* parse\_errors
* passed
* planned
* skipped
* todo
* todo\_passed
* wait
* exit
For example, to find out how many tests unexpectedly succeeded (TODO tests which passed when they shouldn't):
```
my $count = $aggregate->todo_passed;
my @descriptions = $aggregate->todo_passed;
```
Note that `wait` and `exit` are the totals of the wait and exit statuses of each of the tests. These values are totalled only to provide a true value if any of them are non-zero.
#### `total`
```
my $tests_run = $aggregate->total;
```
Returns the total number of tests run.
#### `has_problems`
```
if ( $parser->has_problems ) {
...
}
```
Identical to `has_errors`, but also returns true if any TODO tests unexpectedly succeeded. This is more akin to "warnings".
#### `has_errors`
```
if ( $parser->has_errors ) {
...
}
```
Returns true if *any* of the parsers failed. This includes:
* Failed tests
* Parse errors
* Bad exit or wait status
#### `todo_failed`
```
# deprecated in favor of 'todo_passed'. This method was horribly misnamed.
```
This was a badly misnamed method. It indicates which TODO tests unexpectedly succeeded. Will now issue a warning and call `todo_passed`.
See Also
---------
<TAP::Parser>
<TAP::Harness>
perl Net::Domain Net::Domain
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Functions](#Functions)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::Domain - Attempt to evaluate the current host's internet name and domain
SYNOPSIS
--------
```
use Net::Domain qw(hostname hostfqdn hostdomain domainname);
```
DESCRIPTION
-----------
Using various methods **attempt** to find the Fully Qualified Domain Name (FQDN) of the current host. From this determine the host-name and the host-domain.
Each of the functions will return *undef* if the FQDN cannot be determined.
### Functions
`hostfqdn()`
Identify and return the FQDN of the current host.
`domainname()`
An alias for hostfqdn().
`hostname()`
Returns the smallest part of the FQDN which can be used to identify the host.
`hostdomain()`
Returns the remainder of the FQDN after the *hostname* has been removed.
EXPORTS
-------
The following symbols are, or can be, exported by this module:
Default Exports *None*.
Optional Exports `hostname`, `hostdomain`, `hostfqdn`, `domainname`.
Export Tags *None*.
KNOWN BUGS
-----------
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Adapted from Sys::Hostname by David Sundstrom <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 1995-1998 Graham Barr. All rights reserved.
Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
perl Time::Piece Time::Piece
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
+ [Local Locales](#Local-Locales)
+ [Date Calculations](#Date-Calculations)
+ [Truncation](#Truncation)
+ [Date Comparisons](#Date-Comparisons)
+ [Date Parsing](#Date-Parsing)
- [CAVEAT %A, %a, %B, %b, and friends](#CAVEAT-%25A,-%25a,-%25B,-%25b,-and-friends)
+ [YYYY-MM-DDThh:mm:ss](#YYYY-MM-DDThh:mm:ss)
+ [Week Number](#Week-Number)
+ [Global Overriding](#Global-Overriding)
* [CAVEATS](#CAVEATS)
+ [Setting $ENV{TZ} in Threads on Win32](#Setting-%24ENV%7BTZ%7D-in-Threads-on-Win32)
+ [Use of epoch seconds](#Use-of-epoch-seconds)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
NAME
----
Time::Piece - Object Oriented time objects
SYNOPSIS
--------
```
use Time::Piece;
my $t = localtime;
print "Time is $t\n";
print "Year is ", $t->year, "\n";
```
DESCRIPTION
-----------
This module replaces the standard `localtime` and `gmtime` functions with implementations that return objects. It does so in a backwards compatible manner, so that using localtime/gmtime in the way documented in perlfunc will still return what you expect.
The module actually implements most of an interface described by Larry Wall on the perl5-porters mailing list here: <https://www.nntp.perl.org/group/perl.perl5.porters/2000/01/msg5283.html>
USAGE
-----
After importing this module, when you use localtime or gmtime in a scalar context, rather than getting an ordinary scalar string representing the date and time, you get a Time::Piece object, whose stringification happens to produce the same effect as the localtime and gmtime functions. There is also a new() constructor provided, which is the same as localtime(), except when passed a Time::Piece object, in which case it's a copy constructor. The following methods are available on the object:
```
$t->sec # also available as $t->second
$t->min # also available as $t->minute
$t->hour # 24 hour
$t->mday # also available as $t->day_of_month
$t->mon # 1 = January
$t->_mon # 0 = January
$t->monname # Feb
$t->month # same as $t->monname
$t->fullmonth # February
$t->year # based at 0 (year 0 AD is, of course 1 BC)
$t->_year # year minus 1900
$t->yy # 2 digit year
$t->wday # 1 = Sunday
$t->_wday # 0 = Sunday
$t->day_of_week # 0 = Sunday
$t->wdayname # Tue
$t->day # same as wdayname
$t->fullday # Tuesday
$t->yday # also available as $t->day_of_year, 0 = Jan 01
$t->isdst # also available as $t->daylight_savings
$t->hms # 12:34:56
$t->hms(".") # 12.34.56
$t->time # same as $t->hms
$t->ymd # 2000-02-29
$t->date # same as $t->ymd
$t->mdy # 02-29-2000
$t->mdy("/") # 02/29/2000
$t->dmy # 29-02-2000
$t->dmy(".") # 29.02.2000
$t->datetime # 2000-02-29T12:34:56 (ISO 8601)
$t->cdate # Tue Feb 29 12:34:56 2000
"$t" # same as $t->cdate
$t->epoch # seconds since the epoch
$t->tzoffset # timezone offset in a Time::Seconds object
$t->julian_day # number of days since Julian period began
$t->mjd # modified Julian date (JD-2400000.5 days)
$t->week # week number (ISO 8601)
$t->is_leap_year # true if it's a leap year
$t->month_last_day # 28-31
$t->time_separator($s) # set the default separator (default ":")
$t->date_separator($s) # set the default separator (default "-")
$t->day_list(@days) # set the default weekdays
$t->mon_list(@days) # set the default months
$t->strftime(FORMAT) # same as POSIX::strftime (without the overhead
# of the full POSIX extension)
$t->strftime() # "Tue, 29 Feb 2000 12:34:56 GMT"
Time::Piece->strptime(STRING, FORMAT)
# see strptime man page. Creates a new
# Time::Piece object
```
Note that `localtime` and `gmtime` are not listed above. If called as methods on a Time::Piece object, they act as constructors, returning a new Time::Piece object for the current time. In other words: they're not useful as methods.
###
Local Locales
Both wdayname (day) and monname (month) allow passing in a list to use to index the name of the days against. This can be useful if you need to implement some form of localisation without actually installing or using locales. Note that this is a global override and will affect all Time::Piece instances.
```
my @days = qw( Dimanche Lundi Merdi Mercredi Jeudi Vendredi Samedi );
my $french_day = localtime->day(@days);
```
These settings can be overridden globally too:
```
Time::Piece::day_list(@days);
```
Or for months:
```
Time::Piece::mon_list(@months);
```
And locally for months:
```
print localtime->month(@months);
```
Or to populate with your current system locale call: Time::Piece->use\_locale();
###
Date Calculations
It's possible to use simple addition and subtraction of objects:
```
use Time::Seconds;
my $seconds = $t1 - $t2;
$t1 += ONE_DAY; # add 1 day (constant from Time::Seconds)
```
The following are valid ($t1 and $t2 are Time::Piece objects):
```
$t1 - $t2; # returns Time::Seconds object
$t1 - 42; # returns Time::Piece object
$t1 + 533; # returns Time::Piece object
```
However adding a Time::Piece object to another Time::Piece object will cause a runtime error.
Note that the first of the above returns a Time::Seconds object, so while examining the object will print the number of seconds (because of the overloading), you can also get the number of minutes, hours, days, weeks and years in that delta, using the Time::Seconds API.
In addition to adding seconds, there are two APIs for adding months and years:
```
$t = $t->add_months(6);
$t = $t->add_years(5);
```
The months and years can be negative for subtractions. Note that there is some "strange" behaviour when adding and subtracting months at the ends of months. Generally when the resulting month is shorter than the starting month then the number of overlap days is added. For example subtracting a month from 2008-03-31 will not result in 2008-02-31 as this is an impossible date. Instead you will get 2008-03-02. This appears to be consistent with other date manipulation tools.
### Truncation
Calling the `truncate` method returns a copy of the object but with the time truncated to the start of the supplied unit.
```
$t = $t->truncate(to => 'day');
```
This example will set the time to midnight on the same date which `$t` had previously. Allowed values for the "to" parameter are: "year", "quarter", "month", "day", "hour", "minute" and "second".
###
Date Comparisons
Date comparisons are also possible, using the full suite of "<", ">", "<=", ">=", "<=>", "==" and "!=".
###
Date Parsing
Time::Piece has a built-in strptime() function (from FreeBSD), allowing you incredibly flexible date parsing routines. For example:
```
my $t = Time::Piece->strptime("Sunday 3rd Nov, 1943",
"%A %drd %b, %Y");
print $t->strftime("%a, %d %b %Y");
```
Outputs:
```
Wed, 03 Nov 1943
```
(see, it's even smart enough to fix my obvious date bug)
For more information see "man strptime", which should be on all unix systems.
Alternatively look here: <http://www.unix.com/man-page/FreeBSD/3/strftime/>
####
CAVEAT %A, %a, %B, %b, and friends
Time::Piece::strptime by default can only parse American English date names. Meanwhile, Time::Piece->strftime() will return date names that use the current configured system locale. This means dates returned by strftime might not be able to be parsed by strptime. This is the default behavior and can be overridden by calling Time::Piece->use\_locale(). This builds a list of the current locale's day and month names which strptime will use to parse with. Note this is a global override and will affect all Time::Piece instances.
For instance with a German locale:
```
localtime->day_list();
```
Returns
```
( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' )
```
While:
```
Time::Piece->use_locale();
localtime->day_list();
```
Returns
```
( 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' )
```
###
YYYY-MM-DDThh:mm:ss
The ISO 8601 standard defines the date format to be YYYY-MM-DD, and the time format to be hh:mm:ss (24 hour clock), and if combined, they should be concatenated with date first and with a capital 'T' in front of the time.
###
Week Number
The *week number* may be an unknown concept to some readers. The ISO 8601 standard defines that weeks begin on a Monday and week 1 of the year is the week that includes both January 4th and the first Thursday of the year. In other words, if the first Monday of January is the 2nd, 3rd, or 4th, the preceding days of the January are part of the last week of the preceding year. Week numbers range from 1 to 53.
###
Global Overriding
Finally, it's possible to override localtime and gmtime everywhere, by including the ':override' tag in the import list:
```
use Time::Piece ':override';
```
CAVEATS
-------
###
Setting $ENV{TZ} in Threads on Win32
Note that when using perl in the default build configuration on Win32 (specifically, when perl is built with PERL\_IMPLICIT\_SYS), each perl interpreter maintains its own copy of the environment and only the main interpreter will update the process environment seen by strftime.
Therefore, if you make changes to $ENV{TZ} from inside a thread other than the main thread then those changes will not be seen by strftime if you subsequently call that with the %Z formatting code. You must change $ENV{TZ} in the main thread to have the desired effect in this case (and you must also call \_tzset() in the main thread to register the environment change).
Furthermore, remember that this caveat also applies to fork(), which is emulated by threads on Win32.
###
Use of epoch seconds
This module internally uses the epoch seconds system that is provided via the perl `time()` function and supported by `gmtime()` and `localtime()`.
If your perl does not support times larger than `2^31` seconds then this module is likely to fail at processing dates beyond the year 2038. There are moves afoot to fix that in perl. Alternatively use 64 bit perl. Or if none of those are options, use the [DateTime](datetime) module which has support for years well into the future and past.
Also, the internal representation of Time::Piece->strftime deviates from the standard POSIX implementation in that is uses the epoch (instead of separate year, month, day parts). This change was added in version 1.30. If you must have a more traditional strftime (which will normally never calculate day light saving times correctly), you can pass the date parts from Time::Piece into the strftime function provided by the POSIX module (see strftime in [POSIX](posix) ).
AUTHOR
------
Matt Sergeant, [email protected] Jarkko Hietaniemi, [email protected] (while creating Time::Piece for core perl)
COPYRIGHT AND LICENSE
----------------------
Copyright 2001, Larry Wall.
This module is free software, you may distribute it under the same terms as Perl.
SEE ALSO
---------
The excellent Calendar FAQ at <http://www.tondering.dk/claus/calendar.html>
BUGS
----
The test harness leaves much to be desired. Patches welcome.
| programming_docs |
perl Pod::ParseLink Pod::ParseLink
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::ParseLink - Parse an L<> formatting code in POD text
SYNOPSIS
--------
```
use Pod::ParseLink;
my $link = get_link();
my ($text, $inferred, $name, $section, $type) = parselink($link);
```
DESCRIPTION
-----------
This module only provides a single function, parselink(), which takes the text of an L<> formatting code and parses it. It returns the anchor text for the link (if any was given), the anchor text possibly inferred from the name and section, the name or URL, the section if any, and the type of link. The type will be one of `url`, `pod`, or `man`, indicating a URL, a link to a POD page, or a link to a Unix manual page.
Parsing is implemented per <perlpodspec>. For backward compatibility, links where there is no section and name contains spaces, or links where the entirety of the link (except for the anchor text if given) is enclosed in double-quotes are interpreted as links to a section (L</section>).
The inferred anchor text is implemented per <perlpodspec>:
```
L<name> => L<name|name>
L</section> => L<"section"|/section>
L<name/section> => L<"section" in name|name/section>
```
The name may contain embedded E<> and Z<> formatting codes, and the section, anchor text, and inferred anchor text may contain any formatting codes. Any double quotes around the section are removed as part of the parsing, as is any leading or trailing whitespace.
If the text of the L<> escape is entirely enclosed in double quotes, it's interpreted as a link to a section for backward compatibility.
No attempt is made to resolve formatting codes. This must be done after calling parselink() (since E<> formatting codes can be used to escape characters that would otherwise be significant to the parser and resolving them before parsing would result in an incorrect parse of a formatting code like:
```
L<verticalE<verbar>barE<sol>slash>
```
which should be interpreted as a link to the `vertical|bar/slash` POD page and not as a link to the `slash` section of the `bar` POD page with an anchor text of `vertical`. Note that not only the anchor text will need to have formatting codes expanded, but so will the target of the link (to deal with E<> and Z<> formatting codes), and special handling of the section may be necessary depending on whether the translator wants to consider markup in sections to be significant when resolving links. See <perlpodspec> for more information.
AUTHOR
------
Russ Allbery <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright 2001, 2008, 2009, 2014, 2018-2019 Russ Allbery <[email protected]>
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<Pod::Parser>
The current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>.
perl Safe Safe
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [WARNING](#WARNING)
* [METHODS](#METHODS)
+ [permit (OP, ...)](#permit-(OP,-...))
+ [permit\_only (OP, ...)](#permit_only-(OP,-...))
+ [deny (OP, ...)](#deny-(OP,-...))
+ [deny\_only (OP, ...)](#deny_only-(OP,-...))
+ [trap (OP, ...), untrap (OP, ...)](#trap-(OP,-...),-untrap-(OP,-...))
+ [share (NAME, ...)](#share-(NAME,-...))
+ [share\_from (PACKAGE, ARRAYREF)](#share_from-(PACKAGE,-ARRAYREF))
+ [varglob (VARNAME)](#varglob-(VARNAME))
+ [reval (STRING, STRICT)](#reval-(STRING,-STRICT))
+ [rdo (FILENAME)](#rdo-(FILENAME))
+ [root (NAMESPACE)](#root-(NAMESPACE))
+ [mask (MASK)](#mask-(MASK))
+ [wrap\_code\_ref (CODEREF)](#wrap_code_ref-(CODEREF))
+ [wrap\_code\_refs\_within (...)](#wrap_code_refs_within-(...))
* [RISKS](#RISKS)
* [AUTHOR](#AUTHOR)
NAME
----
Safe - Compile and execute code in restricted compartments
SYNOPSIS
--------
```
use Safe;
$compartment = new Safe;
$compartment->permit(qw(time sort :browse));
$result = $compartment->reval($unsafe_code);
```
DESCRIPTION
-----------
The Safe extension module allows the creation of compartments in which perl code can be evaluated. Each compartment has
a new namespace The "root" of the namespace (i.e. "main::") is changed to a different package and code evaluated in the compartment cannot refer to variables outside this namespace, even with run-time glob lookups and other tricks.
Code which is compiled outside the compartment can choose to place variables into (or *share* variables with) the compartment's namespace and only that data will be visible to code evaluated in the compartment.
By default, the only variables shared with compartments are the "underscore" variables $\_ and @\_ (and, technically, the less frequently used %\_, the \_ filehandle and so on). This is because otherwise perl operators which default to $\_ will not work and neither will the assignment of arguments to @\_ on subroutine entry.
an operator mask Each compartment has an associated "operator mask". Recall that perl code is compiled into an internal format before execution. Evaluating perl code (e.g. via "eval" or "do 'file'") causes the code to be compiled into an internal format and then, provided there was no error in the compilation, executed. Code evaluated in a compartment compiles subject to the compartment's operator mask. Attempting to evaluate code in a compartment which contains a masked operator will cause the compilation to fail with an error. The code will not be executed.
The default operator mask for a newly created compartment is the ':default' optag.
It is important that you read the [Opcode](opcode) module documentation for more information, especially for detailed definitions of opnames, optags and opsets.
Since it is only at the compilation stage that the operator mask applies, controlled access to potentially unsafe operations can be achieved by having a handle to a wrapper subroutine (written outside the compartment) placed into the compartment. For example,
```
$cpt = new Safe;
sub wrapper {
# vet arguments and perform potentially unsafe operations
}
$cpt->share('&wrapper');
```
WARNING
-------
The Safe module does not implement an effective sandbox for evaluating untrusted code with the perl interpreter.
Bugs in the perl interpreter that could be abused to bypass Safe restrictions are not treated as vulnerabilities. See <perlsecpolicy> for additional information.
The authors make **no warranty**, implied or otherwise, about the suitability of this software for safety or security purposes.
The authors shall not in any case be liable for special, incidental, consequential, indirect or other similar damages arising from the use of this software.
Your mileage will vary. If in any doubt **do not use it**.
METHODS
-------
To create a new compartment, use
```
$cpt = new Safe;
```
Optional argument is (NAMESPACE), where NAMESPACE is the root namespace to use for the compartment (defaults to "Safe::Root0", incremented for each new compartment).
Note that version 1.00 of the Safe module supported a second optional parameter, MASK. That functionality has been withdrawn pending deeper consideration. Use the permit and deny methods described below.
The following methods can then be used on the compartment object returned by the above constructor. The object argument is implicit in each case.
###
permit (OP, ...)
Permit the listed operators to be used when compiling code in the compartment (in *addition* to any operators already permitted).
You can list opcodes by names, or use a tag name; see ["Predefined Opcode Tags" in Opcode](opcode#Predefined-Opcode-Tags).
###
permit\_only (OP, ...)
Permit *only* the listed operators to be used when compiling code in the compartment (*no* other operators are permitted).
###
deny (OP, ...)
Deny the listed operators from being used when compiling code in the compartment (other operators may still be permitted).
###
deny\_only (OP, ...)
Deny *only* the listed operators from being used when compiling code in the compartment (*all* other operators will be permitted, so you probably don't want to use this method).
###
trap (OP, ...), untrap (OP, ...)
The trap and untrap methods are synonyms for deny and permit respectfully.
###
share (NAME, ...)
This shares the variable(s) in the argument list with the compartment. This is almost identical to exporting variables using the [Exporter](exporter) module.
Each NAME must be the **name** of a non-lexical variable, typically with the leading type identifier included. A bareword is treated as a function name.
Examples of legal names are '$foo' for a scalar, '@foo' for an array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '\*foo' for a glob (i.e. all symbol table entries associated with "foo", including scalar, array, hash, sub and filehandle).
Each NAME is assumed to be in the calling package. See share\_from for an alternative method (which `share` uses).
###
share\_from (PACKAGE, ARRAYREF)
This method is similar to share() but allows you to explicitly name the package that symbols should be shared from. The symbol names (including type characters) are supplied as an array reference.
```
$safe->share_from('main', [ '$foo', '%bar', 'func' ]);
```
Names can include package names, which are relative to the specified PACKAGE. So these two calls have the same effect:
```
$safe->share_from('Scalar::Util', [ 'reftype' ]);
$safe->share_from('main', [ 'Scalar::Util::reftype' ]);
```
###
varglob (VARNAME)
This returns a glob reference for the symbol table entry of VARNAME in the package of the compartment. VARNAME must be the **name** of a variable without any leading type marker. For example:
```
${$cpt->varglob('foo')} = "Hello world";
```
has the same effect as:
```
$cpt = new Safe 'Root';
$Root::foo = "Hello world";
```
but avoids the need to know $cpt's package name.
###
reval (STRING, STRICT)
This evaluates STRING as perl code inside the compartment.
The code can only see the compartment's namespace (as returned by the **root** method). The compartment's root package appears to be the `main::` package to the code inside the compartment.
Any attempt by the code in STRING to use an operator which is not permitted by the compartment will cause an error (at run-time of the main program but at compile-time for the code in STRING). The error is of the form "'%s' trapped by operation mask...".
If an operation is trapped in this way, then the code in STRING will not be executed. If such a trapped operation occurs or any other compile-time or return error, then $@ is set to the error message, just as with an eval().
If there is no error, then the method returns the value of the last expression evaluated, or a return statement may be used, just as with subroutines and **eval()**. The context (list or scalar) is determined by the caller as usual.
If the return value of reval() is (or contains) any code reference, those code references are wrapped to be themselves executed always in the compartment. See ["wrap\_code\_refs\_within"](#wrap_code_refs_within).
The formerly undocumented STRICT argument sets strictness: if true 'use strict;' is used, otherwise it uses 'no strict;'. **Note**: if STRICT is omitted 'no strict;' is the default.
Some points to note:
If the entereval op is permitted then the code can use eval "..." to 'hide' code which might use denied ops. This is not a major problem since when the code tries to execute the eval it will fail because the opmask is still in effect. However this technique would allow clever, and possibly harmful, code to 'probe' the boundaries of what is possible.
Any string eval which is executed by code executing in a compartment, or by code called from code executing in a compartment, will be eval'd in the namespace of the compartment. This is potentially a serious problem.
Consider a function foo() in package pkg compiled outside a compartment but shared with it. Assume the compartment has a root package called 'Root'. If foo() contains an eval statement like eval '$foo = 1' then, normally, $pkg::foo will be set to 1. If foo() is called from the compartment (by whatever means) then instead of setting $pkg::foo, the eval will actually set $Root::pkg::foo.
This can easily be demonstrated by using a module, such as the Socket module, which uses eval "..." as part of an AUTOLOAD function. You can 'use' the module outside the compartment and share an (autoloaded) function with the compartment. If an autoload is triggered by code in the compartment, or by any code anywhere that is called by any means from the compartment, then the eval in the Socket module's AUTOLOAD function happens in the namespace of the compartment. Any variables created or used by the eval'd code are now under the control of the code in the compartment.
A similar effect applies to *all* runtime symbol lookups in code called from a compartment but not compiled within it.
###
rdo (FILENAME)
This evaluates the contents of file FILENAME inside the compartment. It uses the same rules as perl's built-in `do` to locate the file, poossibly using `@INC`.
See above documentation on the **reval** method for further details.
###
root (NAMESPACE)
This method returns the name of the package that is the root of the compartment's namespace.
Note that this behaviour differs from version 1.00 of the Safe module where the root module could be used to change the namespace. That functionality has been withdrawn pending deeper consideration.
###
mask (MASK)
This is a get-or-set method for the compartment's operator mask.
With no MASK argument present, it returns the current operator mask of the compartment.
With the MASK argument present, it sets the operator mask for the compartment (equivalent to calling the deny\_only method).
###
wrap\_code\_ref (CODEREF)
Returns a reference to an anonymous subroutine that, when executed, will call CODEREF with the Safe compartment 'in effect'. In other words, with the package namespace adjusted and the opmask enabled.
Note that the opmask doesn't affect the already compiled code, it only affects any *further* compilation that the already compiled code may try to perform.
This is particularly useful when applied to code references returned from reval().
(It also provides a kind of workaround for RT#60374: "Safe.pm sort {} bug with -Dusethreads". See <https://rt.perl.org/rt3//Public/Bug/Display.html?id=60374> for *much* more detail.)
###
wrap\_code\_refs\_within (...)
Wraps any CODE references found within the arguments by replacing each with the result of calling ["wrap\_code\_ref"](#wrap_code_ref) on the CODE reference. Any ARRAY or HASH references in the arguments are inspected recursively.
Returns nothing.
RISKS
-----
This section is just an outline of some of the things code in a compartment might do (intentionally or unintentionally) which can have an effect outside the compartment.
Memory Consuming all (or nearly all) available memory.
CPU Causing infinite loops etc.
Snooping Copying private information out of your system. Even something as simple as your user name is of value to others. Much useful information could be gleaned from your environment variables for example.
Signals Causing signals (especially SIGFPE and SIGALARM) to affect your process.
Setting up a signal handler will need to be carefully considered and controlled. What mask is in effect when a signal handler gets called? If a user can get an imported function to get an exception and call the user's signal handler, does that user's restricted mask get re-instated before the handler is called? Does an imported handler get called with its original mask or the user's one?
State Changes Ops such as chdir obviously effect the process as a whole and not just the code in the compartment. Ops such as rand and srand have a similar but more subtle effect.
AUTHOR
------
Originally designed and implemented by Malcolm Beattie.
Reworked to use the Opcode module and other changes added by Tim Bunce.
Currently maintained by the Perl 5 Porters, <[email protected]>.
perl File::DosGlob File::DosGlob
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTS (by request only)](#EXPORTS-(by-request-only))
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::DosGlob - DOS like globbing and then some
SYNOPSIS
--------
```
require 5.004;
# override CORE::glob in current package
use File::DosGlob 'glob';
# override CORE::glob in ALL packages (use with extreme caution!)
use File::DosGlob 'GLOBAL_glob';
@perlfiles = glob "..\\pe?l/*.p?";
print <..\\pe?l/*.p?>;
# from the command line (overrides only in main::)
> perl -MFile::DosGlob=glob -e "print <../pe*/*p?>"
```
DESCRIPTION
-----------
A module that implements DOS-like globbing with a few enhancements. It is largely compatible with perlglob.exe (the M$ setargv.obj version) in all but one respect--it understands wildcards in directory components.
For example, `<..\\l*b\\file/*glob.p?>` will work as expected (in that it will find something like '..\lib\File/DosGlob.pm' alright). Note that all path components are case-insensitive, and that backslashes and forward slashes are both accepted, and preserved. You may have to double the backslashes if you are putting them in literally, due to double-quotish parsing of the pattern by perl.
Spaces in the argument delimit distinct patterns, so `glob('*.exe *.dll')` globs all filenames that end in `.exe` or `.dll`. If you want to put in literal spaces in the glob pattern, you can escape them with either double quotes, or backslashes. e.g. `glob('c:/"Program Files"/*/*.dll')`, or `glob('c:/Program\ Files/*/*.dll')`. The argument is tokenized using `Text::ParseWords::parse_line()`, so see <Text::ParseWords> for details of the quoting rules used.
Extending it to csh patterns is left as an exercise to the reader.
EXPORTS (by request only)
--------------------------
glob()
BUGS
----
Should probably be built into the core, and needs to stop pandering to DOS habits. Needs a dose of optimization too.
AUTHOR
------
Gurusamy Sarathy <[email protected]>
HISTORY
-------
* Support for globally overriding glob() (GSAR 3-JUN-98)
* Scalar context, independent iterator context fixes (GSAR 15-SEP-97)
* A few dir-vs-file optimizations result in glob importation being 10 times faster than using perlglob.exe, and using perlglob.bat is only twice as slow as perlglob.exe (GSAR 28-MAY-97)
* Several cleanups prompted by lack of compatible perlglob.exe under Borland (GSAR 27-MAY-97)
* Initial version (GSAR 20-FEB-97)
SEE ALSO
---------
perl
perlglob.bat
Text::ParseWords
perl ExtUtils::Packlist ExtUtils::Packlist
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [FUNCTIONS](#FUNCTIONS)
* [EXAMPLE](#EXAMPLE)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Packlist - manage .packlist files
SYNOPSIS
--------
```
use ExtUtils::Packlist;
my ($pl) = ExtUtils::Packlist->new('.packlist');
$pl->read('/an/old/.packlist');
my @missing_files = $pl->validate();
$pl->write('/a/new/.packlist');
$pl->{'/some/file/name'}++;
or
$pl->{'/some/other/file/name'} = { type => 'file',
from => '/some/file' };
```
DESCRIPTION
-----------
ExtUtils::Packlist provides a standard way to manage .packlist files. Functions are provided to read and write .packlist files. The original .packlist format is a simple list of absolute pathnames, one per line. In addition, this package supports an extended format, where as well as a filename each line may contain a list of attributes in the form of a space separated list of key=value pairs. This is used by the installperl script to differentiate between files and links, for example.
USAGE
-----
The hash reference returned by the new() function can be used to examine and modify the contents of the .packlist. Items may be added/deleted from the .packlist by modifying the hash. If the value associated with a hash key is a scalar, the entry written to the .packlist by any subsequent write() will be a simple filename. If the value is a hash, the entry written will be the filename followed by the key=value pairs from the hash. Reading back the .packlist will recreate the original entries.
FUNCTIONS
---------
new() This takes an optional parameter, the name of a .packlist. If the file exists, it will be opened and the contents of the file will be read. The new() method returns a reference to a hash. This hash holds an entry for each line in the .packlist. In the case of old-style .packlists, the value associated with each key is undef. In the case of new-style .packlists, the value associated with each key is a hash containing the key=value pairs following the filename in the .packlist.
read() This takes an optional parameter, the name of the .packlist to be read. If no file is specified, the .packlist specified to new() will be read. If the .packlist does not exist, Carp::croak will be called.
write() This takes an optional parameter, the name of the .packlist to be written. If no file is specified, the .packlist specified to new() will be overwritten.
validate() This checks that every file listed in the .packlist actually exists. If an argument which evaluates to true is given, any missing files will be removed from the internal hash. The return value is a list of the missing files, which will be empty if they all exist.
packlist\_file() This returns the name of the associated .packlist file
EXAMPLE
-------
Here's `modrm`, a little utility to cleanly remove an installed module.
```
#!/usr/local/bin/perl -w
use strict;
use IO::Dir;
use ExtUtils::Packlist;
use ExtUtils::Installed;
sub emptydir($) {
my ($dir) = @_;
my $dh = IO::Dir->new($dir) || return(0);
my @count = $dh->read();
$dh->close();
return(@count == 2 ? 1 : 0);
}
# Find all the installed packages
print("Finding all installed modules...\n");
my $installed = ExtUtils::Installed->new();
foreach my $module (grep(!/^Perl$/, $installed->modules())) {
my $version = $installed->version($module) || "???";
print("Found module $module Version $version\n");
print("Do you want to delete $module? [n] ");
my $r = <STDIN>; chomp($r);
if ($r && $r =~ /^y/i) {
# Remove all the files
foreach my $file (sort($installed->files($module))) {
print("rm $file\n");
unlink($file);
}
my $pf = $installed->packlist($module)->packlist_file();
print("rm $pf\n");
unlink($pf);
foreach my $dir (sort($installed->directory_tree($module))) {
if (emptydir($dir)) {
print("rmdir $dir\n");
rmdir($dir);
}
}
}
}
```
AUTHOR
------
Alan Burlison <[email protected]>
| programming_docs |
perl CPAN::Tarzip CPAN::Tarzip
============
CONTENTS
--------
* [NAME](#NAME)
* [LICENSE](#LICENSE)
NAME
----
CPAN::Tarzip - internal handling of tar archives for CPAN.pm
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl IO::Uncompress::Bunzip2 IO::Uncompress::Bunzip2
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [bunzip2 $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#bunzip2-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [read](#read)
+ [read](#read1)
+ [getline](#getline)
+ [getc](#getc)
+ [ungetc](#ungetc)
+ [getHeaderInfo](#getHeaderInfo)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [nextStream](#nextStream)
+ [trailingData](#trailingData)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
+ [Working with Net::FTP](#Working-with-Net::FTP)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::Bunzip2 - Read bzip2 files/buffers
SYNOPSIS
--------
```
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
my $status = bunzip2 $input => $output [,OPTS]
or die "bunzip2 failed: $Bunzip2Error\n";
my $z = IO::Uncompress::Bunzip2->new( $input [OPTS] )
or die "bunzip2 failed: $Bunzip2Error\n";
$status = $z->read($buffer)
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$line = $z->getline()
$char = $z->getc()
$char = $z->ungetc()
$char = $z->opened()
$data = $z->trailingData()
$status = $z->nextStream()
$data = $z->getHeaderInfo()
$z->tell()
$z->seek($position, $whence)
$z->binmode()
$z->fileno()
$z->eof()
$z->close()
$Bunzip2Error ;
# IO::File mode
<$z>
read($z, $buffer);
read($z, $buffer, $length);
read($z, $buffer, $length, $offset);
tell($z)
seek($z, $position, $whence)
binmode($z)
fileno($z)
eof($z)
close($z)
```
DESCRIPTION
-----------
This module provides a Perl interface that allows the reading of bzip2 files/buffers.
For writing bzip2 files/buffers, see the companion module IO::Compress::Bzip2.
Functional Interface
---------------------
A top-level function, `bunzip2`, is provided to carry out "one-shot" uncompression between buffers and/or files. For finer control over the uncompression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
bunzip2 $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "bunzip2 failed: $Bunzip2Error\n";
```
The functional interface needs Perl5.005 or better.
###
bunzip2 $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`bunzip2` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the compressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is uncompressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `bunzip2` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the uncompressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the uncompressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the uncompressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the uncompressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the uncompressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `bunzip2` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple compressed files/buffers and `$output_filename_or_reference` is a single file/buffer, after uncompression `$output_filename_or_reference` will contain a concatenation of all the uncompressed data from each of the input files/buffers.
###
Optional Parameters
The optional parameters for the one-shot function `bunzip2` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `bunzip2` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `bunzip2` has completed.
This parameter defaults to 0.
`BinModeOut => 0|1`
This option is now a no-op. All files will be written in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all uncompressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any uncompressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any uncompressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any uncompressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all uncompressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any uncompressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all uncompressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any uncompressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any uncompressed data is output.
Defaults to 0.
`MultiStream => 0|1`
If the input file/buffer contains multiple compressed data streams, this option will uncompress the whole lot as a single data stream.
Defaults to 0.
`TrailingData => $scalar`
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option.
### Examples
To read the contents of the file `file1.txt.bz2` and write the uncompressed data to the file `file1.txt`.
```
use strict ;
use warnings ;
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
my $input = "file1.txt.bz2";
my $output = "file1.txt";
bunzip2 $input => $output
or die "bunzip2 failed: $Bunzip2Error\n";
```
To read from an existing Perl filehandle, `$input`, and write the uncompressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.bz2" )
or die "Cannot open 'file1.txt.bz2': $!\n" ;
my $buffer ;
bunzip2 $input => \$buffer
or die "bunzip2 failed: $Bunzip2Error\n";
```
To uncompress all files in the directory "/my/home" that match "\*.txt.bz2" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
bunzip2 '</my/home/*.txt.bz2>' => '</my/home/#1.txt>'
or die "bunzip2 failed: $Bunzip2Error\n";
```
and if you want to compress each file one at a time, this will do the trick
```
use strict ;
use warnings ;
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
for my $input ( glob "/my/home/*.txt.bz2" )
{
my $output = $input;
$output =~ s/.bz2// ;
bunzip2 $input => $output
or die "Error compressing '$input': $Bunzip2Error\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::Bunzip2 is shown below
```
my $z = IO::Uncompress::Bunzip2->new( $input [OPTS] )
or die "IO::Uncompress::Bunzip2 failed: $Bunzip2Error\n";
```
Returns an `IO::Uncompress::Bunzip2` object on success and undef on failure. The variable `$Bunzip2Error` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::Bunzip2 can be used exactly like an <IO::File> filehandle. This means that all normal input file operations can be carried out with `$z`. For example, to read a line from a compressed file/buffer you can use either of these forms
```
$line = $z->getline();
$line = <$z>;
```
The mandatory parameter `$input` is used to determine the source of the compressed data. This parameter can take one of three forms.
A filename If the `$input` parameter is a scalar, it is assumed to be a filename. This file will be opened for reading and the compressed data will be read from it.
A filehandle If the `$input` parameter is a filehandle, the compressed data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input` is a scalar reference, the compressed data will be read from `$$input`.
###
Constructor Options
The option names defined below are case insensitive and can be optionally prefixed by a '-'. So all of the following are valid
```
-AutoClose
-autoclose
AUTOCLOSE
autoclose
```
OPTS is a combination of the following options:
`AutoClose => 0|1`
This option is only valid when the `$input` parameter is a filehandle. If specified, and the value is true, it will result in the file being closed once either the `close` method is called or the IO::Uncompress::Bunzip2 object is destroyed.
This parameter defaults to 0.
`MultiStream => 0|1`
Allows multiple concatenated compressed streams to be treated as a single compressed stream. Decompression will stop once either the end of the file/buffer is reached, an error is encountered (premature eof, corrupt compressed data) or the end of a stream is not immediately followed by the start of another stream.
This parameter defaults to 0.
`Prime => $string`
This option will uncompress the contents of `$string` before processing the input file/buffer.
This option can be useful when the compressed data is embedded in another file/data structure and it is not possible to work out where the compressed data begins without having to read the first few bytes. If this is the case, the uncompression can be *primed* with these bytes using this option.
`Transparent => 0|1`
If this option is set and the input file/buffer is not compressed data, the module will allow reading of it anyway.
In addition, if the input file/buffer does contain compressed data and there is non-compressed data immediately following it, setting this option will make this module treat the whole file/buffer as a single data stream.
This option defaults to 1.
`BlockSize => $num`
When reading the compressed input data, IO::Uncompress::Bunzip2 will read it in blocks of `$num` bytes.
This option defaults to 4096.
`InputLength => $size`
When present this option will limit the number of compressed bytes read from the input file/buffer to `$size`. This option can be used in the situation where there is useful data directly after the compressed data stream and you know beforehand the exact length of the compressed data stream.
This option is mostly used when reading from a filehandle, in which case the file pointer will be left pointing to the first byte directly after the compressed data stream.
This option defaults to off.
`Append => 0|1`
This option controls what the `read` method does with uncompressed data.
If set to 1, all uncompressed data will be appended to the output parameter of the `read` method.
If set to 0, the contents of the output parameter of the `read` method will be overwritten by the uncompressed data.
Defaults to 0.
`Strict => 0|1`
This option is a no-op.
`Small => 0|1`
When non-zero this options will make bzip2 use a decompression algorithm that uses less memory at the expense of increasing the amount of time taken for decompression.
Default is 0.
### Examples
TODO
Methods
-------
### read
Usage is
```
$status = $z->read($buffer)
```
Reads a block of compressed data (the size of the compressed block is determined by the `Buffer` option in the constructor), uncompresses it and writes any uncompressed data into `$buffer`. If the `Append` parameter is set in the constructor, the uncompressed data will be appended to the `$buffer` parameter. Otherwise `$buffer` will be overwritten.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### read
Usage is
```
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$status = read($z, $buffer, $length)
$status = read($z, $buffer, $length, $offset)
```
Attempt to read `$length` bytes of uncompressed data into `$buffer`.
The main difference between this form of the `read` method and the previous one, is that this one will attempt to return *exactly* `$length` bytes. The only circumstances that this function will not is if end-of-file or an IO error is encountered.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### getline
Usage is
```
$line = $z->getline()
$line = <$z>
```
Reads a single line.
This method fully supports the use of the variable `$/` (or `$INPUT_RECORD_SEPARATOR` or `$RS` when `English` is in use) to determine what constitutes an end of line. Paragraph mode, record mode and file slurp mode are all supported.
### getc
Usage is
```
$char = $z->getc()
```
Read a single character.
### ungetc
Usage is
```
$char = $z->ungetc($string)
```
### getHeaderInfo
Usage is
```
$hdr = $z->getHeaderInfo();
@hdrs = $z->getHeaderInfo();
```
This method returns either a hash reference (in scalar context) or a list or hash references (in array context) that contains information about each of the header fields in the compressed data stream(s).
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the end of the compressed input stream has been reached.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the input file/buffer. It is a fatal error to attempt to seek backward.
Note that the implementation of `seek` in this module does not provide true random access to a compressed file/buffer. It works by uncompressing data from the current offset in the file/buffer until it reaches the uncompressed offset specified in the parameters to `seek`. For very small files this may be acceptable behaviour. For large files it may cause an unacceptable delay.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
Returns the current uncompressed line number. If `EXPR` is present it has the effect of setting the line number. Note that setting the line number does not change the current position within the file/buffer being read.
The contents of `$/` are used to determine what constitutes a line terminator.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Uncompress::Bunzip2 object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Uncompress::Bunzip2 object was created, and the object is associated with a file, the underlying file will also be closed.
### nextStream
Usage is
```
my $status = $z->nextStream();
```
Skips to the next compressed data stream in the input file/buffer. If a new compressed data stream is found, the eof marker will be cleared and `$.` will be reset to 0.
Returns 1 if a new stream was found, 0 if none was found, and -1 if an error was encountered.
### trailingData
Usage is
```
my $data = $z->trailingData();
```
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete. It only makes sense to call this method once the end of the compressed data stream has been encountered.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option in the constructor.
Importing
---------
No symbolic constants are required by IO::Uncompress::Bunzip2 at present.
:all Imports `bunzip2` and `$Bunzip2Error`. Same as doing this
```
use IO::Uncompress::Bunzip2 qw(bunzip2 $Bunzip2Error) ;
```
EXAMPLES
--------
###
Working with Net::FTP
See [IO::Compress::FAQ](IO::Compress::FAQ#Compressed-files-and-Net%3A%3AFTP)
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
The primary site for the bzip2 program is <https://sourceware.org/bzip2/>.
See the module <Compress::Bzip2>
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl IO::Compress::FAQ IO::Compress::FAQ
=================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [GENERAL](#GENERAL)
+ [Compatibility with Unix compress/uncompress.](#Compatibility-with-Unix-compress/uncompress.)
+ [Accessing .tar.Z files](#Accessing-.tar.Z-files)
+ [How do I recompress using a different compression?](#How-do-I-recompress-using-a-different-compression?)
* [ZIP](#ZIP)
+ [What Compression Types do IO::Compress::Zip & IO::Uncompress::Unzip support?](#What-Compression-Types-do-IO::Compress::Zip-&-IO::Uncompress::Unzip-support?)
+ [Can I Read/Write Zip files larger the 4 Gig?](#Can-I-Read/Write-Zip-files-larger-the-4-Gig?)
+ [Can I write more that 64K entries is a Zip files?](#Can-I-write-more-that-64K-entries-is-a-Zip-files?)
+ [Zip Resources](#Zip-Resources)
* [GZIP](#GZIP)
+ [Gzip Resources](#Gzip-Resources)
+ [Dealing with concatenated gzip files](#Dealing-with-concatenated-gzip-files)
+ [Reading bgzip files with IO::Uncompress::Gunzip](#Reading-bgzip-files-with-IO::Uncompress::Gunzip)
* [ZLIB](#ZLIB)
+ [Zlib Resources](#Zlib-Resources)
* [Bzip2](#Bzip2)
+ [Bzip2 Resources](#Bzip2-Resources)
+ [Dealing with Concatenated bzip2 files](#Dealing-with-Concatenated-bzip2-files)
+ [Interoperating with Pbzip2](#Interoperating-with-Pbzip2)
* [HTTP & NETWORK](#HTTP-&-NETWORK)
+ [Apache::GZip Revisited](#Apache::GZip-Revisited)
+ [Compressed files and Net::FTP](#Compressed-files-and-Net::FTP)
* [MISC](#MISC)
+ [Using InputLength to uncompress data embedded in a larger file/buffer.](#Using-InputLength-to-uncompress-data-embedded-in-a-larger-file/buffer.)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Compress::FAQ -- Frequently Asked Questions about IO::Compress
DESCRIPTION
-----------
Common questions answered.
GENERAL
-------
###
Compatibility with Unix compress/uncompress.
Although `Compress::Zlib` has a pair of functions called `compress` and `uncompress`, they are *not* related to the Unix programs of the same name. The `Compress::Zlib` module is not compatible with Unix `compress`.
If you have the `uncompress` program available, you can use this to read compressed files
```
open F, "uncompress -c $filename |";
while (<F>)
{
...
```
Alternatively, if you have the `gunzip` program available, you can use this to read compressed files
```
open F, "gunzip -c $filename |";
while (<F>)
{
...
```
and this to write compress files, if you have the `compress` program available
```
open F, "| compress -c $filename ";
print F "data";
...
close F ;
```
###
Accessing .tar.Z files
The `Archive::Tar` module can optionally use `Compress::Zlib` (via the `IO::Zlib` module) to access tar files that have been compressed with `gzip`. Unfortunately tar files compressed with the Unix `compress` utility cannot be read by `Compress::Zlib` and so cannot be directly accessed by `Archive::Tar`.
If the `uncompress` or `gunzip` programs are available, you can use one of these workarounds to read `.tar.Z` files from `Archive::Tar`
Firstly with `uncompress`
```
use strict;
use warnings;
use Archive::Tar;
open F, "uncompress -c $filename |";
my $tar = Archive::Tar->new(*F);
...
```
and this with `gunzip`
```
use strict;
use warnings;
use Archive::Tar;
open F, "gunzip -c $filename |";
my $tar = Archive::Tar->new(*F);
...
```
Similarly, if the `compress` program is available, you can use this to write a `.tar.Z` file
```
use strict;
use warnings;
use Archive::Tar;
use IO::File;
my $fh = IO::File->new( "| compress -c >$filename" );
my $tar = Archive::Tar->new();
...
$tar->write($fh);
$fh->close ;
```
###
How do I recompress using a different compression?
This is easier that you might expect if you realise that all the `IO::Compress::*` objects are derived from `IO::File` and that all the `IO::Uncompress::*` modules can read from an `IO::File` filehandle.
So, for example, say you have a file compressed with gzip that you want to recompress with bzip2. Here is all that is needed to carry out the recompression.
```
use IO::Uncompress::Gunzip ':all';
use IO::Compress::Bzip2 ':all';
my $gzipFile = "somefile.gz";
my $bzipFile = "somefile.bz2";
my $gunzip = IO::Uncompress::Gunzip->new( $gzipFile )
or die "Cannot gunzip $gzipFile: $GunzipError\n" ;
bzip2 $gunzip => $bzipFile
or die "Cannot bzip2 to $bzipFile: $Bzip2Error\n" ;
```
Note, there is a limitation of this technique. Some compression file formats store extra information along with the compressed data payload. For example, gzip can optionally store the original filename and Zip stores a lot of information about the original file. If the original compressed file contains any of this extra information, it will not be transferred to the new compressed file using the technique above.
ZIP
---
###
What Compression Types do IO::Compress::Zip & IO::Uncompress::Unzip support?
The following compression formats are supported by `IO::Compress::Zip` and `IO::Uncompress::Unzip`
* Store (method 0)
No compression at all.
* Deflate (method 8)
This is the default compression used when creating a zip file with `IO::Compress::Zip`.
* Bzip2 (method 12)
Only supported if the `IO-Compress-Bzip2` module is installed.
* Lzma (method 14)
Only supported if the `IO-Compress-Lzma` module is installed.
###
Can I Read/Write Zip files larger the 4 Gig?
Yes, both the `IO-Compress-Zip` and `IO-Uncompress-Unzip` modules support the zip feature called *Zip64*. That allows them to read/write files/buffers larger than 4Gig.
If you are creating a Zip file using the one-shot interface, and any of the input files is greater than 4Gig, a zip64 complaint zip file will be created.
```
zip "really-large-file" => "my.zip";
```
Similarly with the one-shot interface, if the input is a buffer larger than 4 Gig, a zip64 complaint zip file will be created.
```
zip \$really_large_buffer => "my.zip";
```
The one-shot interface allows you to force the creation of a zip64 zip file by including the `Zip64` option.
```
zip $filehandle => "my.zip", Zip64 => 1;
```
If you want to create a zip64 zip file with the OO interface you must specify the `Zip64` option.
```
my $zip = IO::Compress::Zip->new( "whatever", Zip64 => 1 );
```
When uncompressing with `IO-Uncompress-Unzip`, it will automatically detect if the zip file is zip64.
If you intend to manipulate the Zip64 zip files created with `IO-Compress-Zip` using an external zip/unzip, make sure that it supports Zip64.
In particular, if you are using Info-Zip you need to have zip version 3.x or better to update a Zip64 archive and unzip version 6.x to read a zip64 archive.
###
Can I write more that 64K entries is a Zip files?
Yes. Zip64 allows this. See previous question.
###
Zip Resources
The primary reference for zip files is the "appnote" document available at <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>
An alternatively is the Info-Zip appnote. This is available from <ftp://ftp.info-zip.org/pub/infozip/doc/>
GZIP
----
###
Gzip Resources
The primary reference for gzip files is RFC 1952 <https://datatracker.ietf.org/doc/html/rfc1952>
The primary site for gzip is <http://www.gzip.org>.
###
Dealing with concatenated gzip files
If the gunzip program encounters a file containing multiple gzip files concatenated together it will automatically uncompress them all. The example below illustrates this behaviour
```
$ echo abc | gzip -c >x.gz
$ echo def | gzip -c >>x.gz
$ gunzip -c x.gz
abc
def
```
By default `IO::Uncompress::Gunzip` will *not* behave like the gunzip program. It will only uncompress the first gzip data stream in the file, as shown below
```
$ perl -MIO::Uncompress::Gunzip=:all -e 'gunzip "x.gz" => \*STDOUT'
abc
```
To force `IO::Uncompress::Gunzip` to uncompress all the gzip data streams, include the `MultiStream` option, as shown below
```
$ perl -MIO::Uncompress::Gunzip=:all -e 'gunzip "x.gz" => \*STDOUT, MultiStream => 1'
abc
def
```
###
Reading bgzip files with IO::Uncompress::Gunzip
A `bgzip` file consists of a series of valid gzip-compliant data streams concatenated together. To read a file created by `bgzip` with `IO::Uncompress::Gunzip` use the `MultiStream` option as shown in the previous section.
See the section titled "The BGZF compression format" in <http://samtools.github.io/hts-specs/SAMv1.pdf> for a definition of `bgzip`.
ZLIB
----
###
Zlib Resources
The primary site for the *zlib* compression library is <http://www.zlib.org>.
Bzip2
-----
###
Bzip2 Resources
The primary site for bzip2 is <http://www.bzip.org>.
###
Dealing with Concatenated bzip2 files
If the bunzip2 program encounters a file containing multiple bzip2 files concatenated together it will automatically uncompress them all. The example below illustrates this behaviour
```
$ echo abc | bzip2 -c >x.bz2
$ echo def | bzip2 -c >>x.bz2
$ bunzip2 -c x.bz2
abc
def
```
By default `IO::Uncompress::Bunzip2` will *not* behave like the bunzip2 program. It will only uncompress the first bunzip2 data stream in the file, as shown below
```
$ perl -MIO::Uncompress::Bunzip2=:all -e 'bunzip2 "x.bz2" => \*STDOUT'
abc
```
To force `IO::Uncompress::Bunzip2` to uncompress all the bzip2 data streams, include the `MultiStream` option, as shown below
```
$ perl -MIO::Uncompress::Bunzip2=:all -e 'bunzip2 "x.bz2" => \*STDOUT, MultiStream => 1'
abc
def
```
###
Interoperating with Pbzip2
Pbzip2 (<http://compression.ca/pbzip2/>) is a parallel implementation of bzip2. The output from pbzip2 consists of a series of concatenated bzip2 data streams.
By default `IO::Uncompress::Bzip2` will only uncompress the first bzip2 data stream in a pbzip2 file. To uncompress the complete pbzip2 file you must include the `MultiStream` option, like this.
```
bunzip2 $input => \$output, MultiStream => 1
or die "bunzip2 failed: $Bunzip2Error\n";
```
HTTP & NETWORK
---------------
###
Apache::GZip Revisited
Below is a mod\_perl Apache compression module, called `Apache::GZip`, taken from <http://perl.apache.org/docs/tutorials/tips/mod_perl_tricks/mod_perl_tricks.html#On_the_Fly_Compression>
```
package Apache::GZip;
#File: Apache::GZip.pm
use strict vars;
use Apache::Constants ':common';
use Compress::Zlib;
use IO::File;
use constant GZIP_MAGIC => 0x1f8b;
use constant OS_MAGIC => 0x03;
sub handler {
my $r = shift;
my ($fh,$gz);
my $file = $r->filename;
return DECLINED unless $fh=IO::File->new($file);
$r->header_out('Content-Encoding'=>'gzip');
$r->send_http_header;
return OK if $r->header_only;
tie *STDOUT,'Apache::GZip',$r;
print($_) while <$fh>;
untie *STDOUT;
return OK;
}
sub TIEHANDLE {
my($class,$r) = @_;
# initialize a deflation stream
my $d = deflateInit(-WindowBits=>-MAX_WBITS()) || return undef;
# gzip header -- don't ask how I found out
$r->print(pack("nccVcc",GZIP_MAGIC,Z_DEFLATED,0,time(),0,OS_MAGIC));
return bless { r => $r,
crc => crc32(undef),
d => $d,
l => 0
},$class;
}
sub PRINT {
my $self = shift;
foreach (@_) {
# deflate the data
my $data = $self->{d}->deflate($_);
$self->{r}->print($data);
# keep track of its length and crc
$self->{l} += length($_);
$self->{crc} = crc32($_,$self->{crc});
}
}
sub DESTROY {
my $self = shift;
# flush the output buffers
my $data = $self->{d}->flush;
$self->{r}->print($data);
# print the CRC and the total length (uncompressed)
$self->{r}->print(pack("LL",@{$self}{qw/crc l/}));
}
1;
```
Here's the Apache configuration entry you'll need to make use of it. Once set it will result in everything in the /compressed directory will be compressed automagically.
```
<Location /compressed>
SetHandler perl-script
PerlHandler Apache::GZip
</Location>
```
Although at first sight there seems to be quite a lot going on in `Apache::GZip`, you could sum up what the code was doing as follows -- read the contents of the file in `$r->filename`, compress it and write the compressed data to standard output. That's all.
This code has to jump through a few hoops to achieve this because
1. The gzip support in `Compress::Zlib` version 1.x can only work with a real filesystem filehandle. The filehandles used by Apache modules are not associated with the filesystem.
2. That means all the gzip support has to be done by hand - in this case by creating a tied filehandle to deal with creating the gzip header and trailer.
`IO::Compress::Gzip` doesn't have that filehandle limitation (this was one of the reasons for writing it in the first place). So if `IO::Compress::Gzip` is used instead of `Compress::Zlib` the whole tied filehandle code can be removed. Here is the rewritten code.
```
package Apache::GZip;
use strict vars;
use Apache::Constants ':common';
use IO::Compress::Gzip;
use IO::File;
sub handler {
my $r = shift;
my ($fh,$gz);
my $file = $r->filename;
return DECLINED unless $fh=IO::File->new($file);
$r->header_out('Content-Encoding'=>'gzip');
$r->send_http_header;
return OK if $r->header_only;
my $gz = IO::Compress::Gzip->new( '-', Minimal => 1 )
or return DECLINED ;
print $gz $_ while <$fh>;
return OK;
}
```
or even more succinctly, like this, using a one-shot gzip
```
package Apache::GZip;
use strict vars;
use Apache::Constants ':common';
use IO::Compress::Gzip qw(gzip);
sub handler {
my $r = shift;
$r->header_out('Content-Encoding'=>'gzip');
$r->send_http_header;
return OK if $r->header_only;
gzip $r->filename => '-', Minimal => 1
or return DECLINED ;
return OK;
}
1;
```
The use of one-shot `gzip` above just reads from `$r->filename` and writes the compressed data to standard output.
Note the use of the `Minimal` option in the code above. When using gzip for Content-Encoding you should *always* use this option. In the example above it will prevent the filename being included in the gzip header and make the size of the gzip data stream a slight bit smaller.
###
Compressed files and Net::FTP
The `Net::FTP` module provides two low-level methods called `stor` and `retr` that both return filehandles. These filehandles can used with the `IO::Compress/Uncompress` modules to compress or uncompress files read from or written to an FTP Server on the fly, without having to create a temporary file.
Firstly, here is code that uses `retr` to uncompressed a file as it is read from the FTP Server.
```
use Net::FTP;
use IO::Uncompress::Gunzip qw(:all);
my $ftp = Net::FTP->new( ... )
my $retr_fh = $ftp->retr($compressed_filename);
gunzip $retr_fh => $outFilename, AutoClose => 1
or die "Cannot uncompress '$compressed_file': $GunzipError\n";
```
and this to compress a file as it is written to the FTP Server
```
use Net::FTP;
use IO::Compress::Gzip qw(:all);
my $stor_fh = $ftp->stor($filename);
gzip "filename" => $stor_fh, AutoClose => 1
or die "Cannot compress '$filename': $GzipError\n";
```
MISC
----
###
Using `InputLength` to uncompress data embedded in a larger file/buffer.
A fairly common use-case is where compressed data is embedded in a larger file/buffer and you want to read both.
As an example consider the structure of a zip file. This is a well-defined file format that mixes both compressed and uncompressed sections of data in a single file.
For the purposes of this discussion you can think of a zip file as sequence of compressed data streams, each of which is prefixed by an uncompressed local header. The local header contains information about the compressed data stream, including the name of the compressed file and, in particular, the length of the compressed data stream.
To illustrate how to use `InputLength` here is a script that walks a zip file and prints out how many lines are in each compressed file (if you intend write code to walking through a zip file for real see ["Walking through a zip file" in IO::Uncompress::Unzip](IO::Uncompress::Unzip#Walking-through-a-zip-file) ). Also, although this example uses the zlib-based compression, the technique can be used by the other `IO::Uncompress::*` modules.
```
use strict;
use warnings;
use IO::File;
use IO::Uncompress::RawInflate qw(:all);
use constant ZIP_LOCAL_HDR_SIG => 0x04034b50;
use constant ZIP_LOCAL_HDR_LENGTH => 30;
my $file = $ARGV[0] ;
my $fh = IO::File->new( "<$file" )
or die "Cannot open '$file': $!\n";
while (1)
{
my $sig;
my $buffer;
my $x ;
($x = $fh->read($buffer, ZIP_LOCAL_HDR_LENGTH)) == ZIP_LOCAL_HDR_LENGTH
or die "Truncated file: $!\n";
my $signature = unpack ("V", substr($buffer, 0, 4));
last unless $signature == ZIP_LOCAL_HDR_SIG;
# Read Local Header
my $gpFlag = unpack ("v", substr($buffer, 6, 2));
my $compressedMethod = unpack ("v", substr($buffer, 8, 2));
my $compressedLength = unpack ("V", substr($buffer, 18, 4));
my $uncompressedLength = unpack ("V", substr($buffer, 22, 4));
my $filename_length = unpack ("v", substr($buffer, 26, 2));
my $extra_length = unpack ("v", substr($buffer, 28, 2));
my $filename ;
$fh->read($filename, $filename_length) == $filename_length
or die "Truncated file\n";
$fh->read($buffer, $extra_length) == $extra_length
or die "Truncated file\n";
if ($compressedMethod != 8 && $compressedMethod != 0)
{
warn "Skipping file '$filename' - not deflated $compressedMethod\n";
$fh->read($buffer, $compressedLength) == $compressedLength
or die "Truncated file\n";
next;
}
if ($compressedMethod == 0 && $gpFlag & 8 == 8)
{
die "Streamed Stored not supported for '$filename'\n";
}
next if $compressedLength == 0;
# Done reading the Local Header
my $inf = IO::Uncompress::RawInflate->new( $fh,
Transparent => 1,
InputLength => $compressedLength )
or die "Cannot uncompress $file [$filename]: $RawInflateError\n" ;
my $line_count = 0;
while (<$inf>)
{
++ $line_count;
}
print "$filename: $line_count\n";
}
```
The majority of the code above is concerned with reading the zip local header data. The code that I want to focus on is at the bottom.
```
while (1) {
# read local zip header data
# get $filename
# get $compressedLength
my $inf = IO::Uncompress::RawInflate->new( $fh,
Transparent => 1,
InputLength => $compressedLength )
or die "Cannot uncompress $file [$filename]: $RawInflateError\n" ;
my $line_count = 0;
while (<$inf>)
{
++ $line_count;
}
print "$filename: $line_count\n";
}
```
The call to `IO::Uncompress::RawInflate` creates a new filehandle `$inf` that can be used to read from the parent filehandle `$fh`, uncompressing it as it goes. The use of the `InputLength` option will guarantee that *at most* `$compressedLength` bytes of compressed data will be read from the `$fh` filehandle (The only exception is for an error case like a truncated file or a corrupt data stream).
This means that once RawInflate is finished `$fh` will be left at the byte directly after the compressed data stream.
Now consider what the code looks like without `InputLength`
```
while (1) {
# read local zip header data
# get $filename
# get $compressedLength
# read all the compressed data into $data
read($fh, $data, $compressedLength);
my $inf = IO::Uncompress::RawInflate->new( \$data,
Transparent => 1 )
or die "Cannot uncompress $file [$filename]: $RawInflateError\n" ;
my $line_count = 0;
while (<$inf>)
{
++ $line_count;
}
print "$filename: $line_count\n";
}
```
The difference here is the addition of the temporary variable `$data`. This is used to store a copy of the compressed data while it is being uncompressed.
If you know that `$compressedLength` isn't that big then using temporary storage won't be a problem. But if `$compressedLength` is very large or you are writing an application that other people will use, and so have no idea how big `$compressedLength` will be, it could be an issue.
Using `InputLength` avoids the use of temporary storage and means the application can cope with large compressed data streams.
One final point -- obviously `InputLength` can only be used whenever you know the length of the compressed data beforehand, like here with a zip file.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs//issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl TAP::Harness::Env TAP::Harness::Env
=================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [ENVIRONMENTAL VARIABLES](#ENVIRONMENTAL-VARIABLES)
NAME
----
TAP::Harness::Env - Parsing harness related environmental variables where appropriate
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
my $harness = TAP::Harness::Env->create(\%extra_args)
```
DESCRIPTION
-----------
This module implements the environmental variables that <Test::Harness> uses with TAP::Harness, and instantiates the appropriate class with the appropriate arguments.
METHODS
-------
* create( \%args )
This function reads the environment and generates an appropriate argument hash from it. If given any arguments in `%extra_args`, these will override the environmental defaults. In accepts `harness_class` (which defaults to `TAP::Harness`), and any argument the harness class accepts.
ENVIRONMENTAL VARIABLES
------------------------
`HARNESS_PERL_SWITCHES` Setting this adds perl command line switches to each test file run.
For example, `HARNESS_PERL_SWITCHES=-T` will turn on taint mode. `HARNESS_PERL_SWITCHES=-MDevel::Cover` will run `Devel::Cover` for each test.
`HARNESS_VERBOSE` If true, `TAP::Harness` will output the verbose results of running its tests.
`HARNESS_SUBCLASS` Specifies a TAP::Harness subclass to be used in place of TAP::Harness.
`HARNESS_OPTIONS` Provide additional options to the harness. Currently supported options are:
`j<n>`
Run <n> (default 9) parallel jobs.
`c` Try to color output. See ["new" in TAP::Formatter::Base](TAP::Formatter::Base#new).
`a<file.tgz>`
Will use <TAP::Harness::Archive> as the harness class, and save the TAP to `file.tgz`
`fPackage-With-Dashes`
Set the formatter\_class of the harness being run. Since the `HARNESS_OPTIONS` is separated by `:`, we use `-` instead.
Multiple options may be separated by colons:
```
HARNESS_OPTIONS=j9:c make test
```
`HARNESS_TIMER` Setting this to true will make the harness display the number of milliseconds each test took. You can also use *prove*'s `--timer` switch.
`HARNESS_COLOR` Attempt to produce color output.
`HARNESS_IGNORE_EXIT` If set to a true value instruct `TAP::Parser` to ignore exit and wait status from test scripts.
perl POSIX POSIX
=====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [FUNCTIONS](#FUNCTIONS)
* [CLASSES](#CLASSES)
+ [POSIX::SigAction](#POSIX::SigAction)
+ [POSIX::SigRt](#POSIX::SigRt)
+ [POSIX::SigSet](#POSIX::SigSet)
+ [POSIX::Termios](#POSIX::Termios)
* [PATHNAME CONSTANTS](#PATHNAME-CONSTANTS)
* [POSIX CONSTANTS](#POSIX-CONSTANTS)
* [RESOURCE CONSTANTS](#RESOURCE-CONSTANTS)
* [SYSTEM CONFIGURATION](#SYSTEM-CONFIGURATION)
* [ERRNO](#ERRNO)
* [FCNTL](#FCNTL)
* [FLOAT](#FLOAT)
* [FLOATING-POINT ENVIRONMENT](#FLOATING-POINT-ENVIRONMENT)
* [LIMITS](#LIMITS)
* [LOCALE](#LOCALE)
* [MATH](#MATH)
* [SIGNAL](#SIGNAL)
* [STAT](#STAT)
* [STDLIB](#STDLIB)
* [STDIO](#STDIO)
* [TIME](#TIME)
* [UNISTD](#UNISTD)
* [WAIT](#WAIT)
* [WINSOCK](#WINSOCK)
NAME
----
POSIX - Perl interface to IEEE Std 1003.1
SYNOPSIS
--------
```
use POSIX ();
use POSIX qw(setsid);
use POSIX qw(:errno_h :fcntl_h);
printf "EINTR is %d\n", EINTR;
$sess_id = POSIX::setsid();
$fd = POSIX::open($path, O_CREAT|O_EXCL|O_WRONLY, 0644);
# note: that's a filedescriptor, *NOT* a filehandle
```
DESCRIPTION
-----------
The POSIX module permits you to access all (or nearly all) the standard POSIX 1003.1 identifiers. Many of these identifiers have been given Perl-ish interfaces.
This document gives a condensed list of the features available in the POSIX module. Consult your operating system's manpages for general information on most features. Consult <perlfunc> for functions which are noted as being identical or almost identical to Perl's builtin functions.
The first section describes POSIX functions from the 1003.1 specification. The second section describes some classes for signal objects, TTY objects, and other miscellaneous objects. The remaining sections list various constants and macros in an organization which roughly follows IEEE Std 1003.1b-1993.
The notation `[C99]` indicates functions that were added in the ISO/IEC 9899:1999 version of the C language standard. Some may not be available on your system if it adheres to an earlier standard. Attempts to use any missing one will result in a fatal runtime error message.
CAVEATS
-------
*Everything is exported by default* (with a handful of exceptions). This is an unfortunate backwards compatibility feature and its use is **strongly [discouraged](perlpolicy#discouraged)**. You should either prevent the exporting (by saying `use POSIX ();`, as usual) and then use fully qualified names (e.g. `POSIX::SEEK_END`), or give an explicit import list. If you do neither and opt for the default (as in `use POSIX;`), you will import *hundreds and hundreds* of symbols into your namespace.
A few functions are not implemented because they are C specific. If you attempt to call these, they will print a message telling you that they aren't implemented, and suggest using the Perl equivalent, should one exist. For example, trying to access the `setjmp()` call will elicit the message "`setjmp() is C-specific: use eval {} instead`".
Furthermore, some evil vendors will claim 1003.1 compliance, but in fact are not so: they will not pass the PCTS (POSIX Compliance Test Suites). For example, one vendor may not define `EDEADLK`, or the semantics of the errno values set by `open(2)` might not be quite right. Perl does not attempt to verify POSIX compliance. That means you can currently successfully say "use POSIX", and then later in your program you find that your vendor has been lax and there's no usable `ICANON` macro after all. This could be construed to be a bug.
FUNCTIONS
---------
`_exit`
This is identical to the C function `_exit()`. It exits the program immediately which means among other things buffered I/O is **not** flushed.
Note that when using threads and in Linux this is **not** a good way to exit a thread because in Linux processes and threads are kind of the same thing (Note: while this is the situation in early 2003 there are projects under way to have threads with more POSIXly semantics in Linux). If you want not to return from a thread, detach the thread.
`abort` This is identical to the C function `abort()`. It terminates the process with a `SIGABRT` signal unless caught by a signal handler or if the handler does not return normally (it e.g. does a `longjmp`).
`abs` This is identical to Perl's builtin `abs()` function, returning the absolute value of its numerical argument (except that `POSIX::abs()` must be provided an explicit value (rather than relying on an implicit `$_`):
```
$absolute_value = POSIX::abs(42); # good
$absolute_value = POSIX::abs(); # throws exception
```
`access` Determines the accessibility of a file.
```
if( POSIX::access( "/", &POSIX::R_OK ) ){
print "have read permission\n";
}
```
Returns `undef` on failure. Note: do not use `access()` for security purposes. Between the `access()` call and the operation you are preparing for the permissions might change: a classic *race condition*.
`acos` This is identical to the C function `acos()`, returning the arcus cosine of its numerical argument. See also <Math::Trig>.
`acosh` This is identical to the C function `acosh()`, returning the hyperbolic arcus cosine of its numerical argument [C99]. See also <Math::Trig>. Added in Perl v5.22.
`alarm` This is identical to Perl's builtin `alarm()` function, either for arming or disarming the `SIGARLM` timer, except that `POSIX::alarm()` must be provided an explicit value (rather than relying on an implicit `$_`):
```
POSIX::alarm(3) # good
POSIX::alarm() # throws exception
```
`asctime` This is identical to the C function `asctime()`. It returns a string of the form
```
"Fri Jun 2 18:22:13 2000\n\0"
```
and it is called thusly
```
$asctime = asctime($sec, $min, $hour, $mday, $mon,
$year, $wday, $yday, $isdst);
```
The `$mon` is zero-based: January equals `0`. The `$year` is 1900-based: 2001 equals `101`. `$wday` and `$yday` default to zero (and are usually ignored anyway), and `$isdst` defaults to -1.
Note the result is always in English. Use `["strftime"](#strftime)` instead to get a result suitable for the current locale. That function's `%c` format yields the locale's preferred representation.
`asin` This is identical to the C function `asin()`, returning the arcus sine of its numerical argument. See also <Math::Trig>.
`asinh` This is identical to the C function `asinh()`, returning the hyperbolic arcus sine of its numerical argument [C99]. See also <Math::Trig>. Added in Perl v5.22.
`assert` Unimplemented, but you can use ["die" in perlfunc](perlfunc#die) and the [Carp](carp) module to achieve similar things.
`atan` This is identical to the C function `atan()`, returning the arcus tangent of its numerical argument. See also <Math::Trig>.
`atanh` This is identical to the C function `atanh()`, returning the hyperbolic arcus tangent of its numerical argument [C99]. See also <Math::Trig>. Added in Perl v5.22.
`atan2` This is identical to Perl's builtin `atan2()` function, returning the arcus tangent defined by its two numerical arguments, the *y* coordinate and the *x* coordinate. See also <Math::Trig>.
`atexit` Not implemented. `atexit()` is C-specific: use `END {}` instead, see <perlmod>.
`atof` Not implemented. `atof()` is C-specific. Perl converts strings to numbers transparently. If you need to force a scalar to a number, add a zero to it.
`atoi` Not implemented. `atoi()` is C-specific. Perl converts strings to numbers transparently. If you need to force a scalar to a number, add a zero to it. If you need to have just the integer part, see ["int" in perlfunc](perlfunc#int).
`atol` Not implemented. `atol()` is C-specific. Perl converts strings to numbers transparently. If you need to force a scalar to a number, add a zero to it. If you need to have just the integer part, see ["int" in perlfunc](perlfunc#int).
`bsearch` `bsearch()` not supplied. For doing binary search on wordlists, see <Search::Dict>.
`calloc` Not implemented. `calloc()` is C-specific. Perl does memory management transparently.
`cbrt` The cube root [C99]. Added in Perl v5.22.
`ceil` This is identical to the C function `ceil()`, returning the smallest integer value greater than or equal to the given numerical argument.
`chdir` This is identical to Perl's builtin `chdir()` function, allowing one to change the working (default) directory -- see ["chdir" in perlfunc](perlfunc#chdir) -- with the exception that `POSIX::chdir()` must be provided an explicit value (rather than relying on an implicit `$_`):
```
$rv = POSIX::chdir('path/to/dir'); # good
$rv = POSIX::chdir(); # throws exception
```
`chmod` This is identical to Perl's builtin `chmod()` function, allowing one to change file and directory permissions -- see ["chmod" in perlfunc](perlfunc#chmod) -- with the exception that `POSIX::chmod()` can only change one file at a time (rather than a list of files):
```
$c = chmod 0664, $file1, $file2; # good
$c = POSIX::chmod 0664, $file1; # throws exception
$c = POSIX::chmod 0664, $file1, $file2; # throws exception
```
As with the built-in `chmod()`, `$file` may be a filename or a file handle.
`chown` This is identical to Perl's builtin `chown()` function, allowing one to change file and directory owners and groups, see ["chown" in perlfunc](perlfunc#chown).
`clearerr` Not implemented. Use the method `IO::Handle::clearerr()` instead, to reset the error state (if any) and EOF state (if any) of the given stream.
`clock` This is identical to the C function `clock()`, returning the amount of spent processor time in microseconds.
`close` Close the file. This uses file descriptors such as those obtained by calling `POSIX::open`.
```
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
POSIX::close( $fd );
```
Returns `undef` on failure.
See also ["close" in perlfunc](perlfunc#close).
`closedir` This is identical to Perl's builtin `closedir()` function for closing a directory handle, see ["closedir" in perlfunc](perlfunc#closedir).
`cos` This is identical to Perl's builtin `cos()` function, for returning the cosine of its numerical argument, see ["cos" in perlfunc](perlfunc#cos). See also <Math::Trig>.
`cosh` This is identical to the C function `cosh()`, for returning the hyperbolic cosine of its numeric argument. See also <Math::Trig>.
`copysign` Returns `x` but with the sign of `y` [C99]. Added in Perl v5.22.
```
$x_with_sign_of_y = POSIX::copysign($x, $y);
```
See also ["signbit"](#signbit).
`creat` Create a new file. This returns a file descriptor like the ones returned by `POSIX::open`. Use `POSIX::close` to close the file.
```
$fd = POSIX::creat( "foo", 0611 );
POSIX::close( $fd );
```
See also ["sysopen" in perlfunc](perlfunc#sysopen) and its `O_CREAT` flag.
`ctermid` Generates the path name for the controlling terminal.
```
$path = POSIX::ctermid();
```
`ctime` This is identical to the C function `ctime()` and equivalent to `asctime(localtime(...))`, see ["asctime"](#asctime) and ["localtime"](#localtime).
`cuserid` [POSIX.1-1988] Get the login name of the owner of the current process.
```
$name = POSIX::cuserid();
```
Note: this function has not been specified by POSIX since 1990 and is included only for backwards compatibility. New code should use [`getlogin()`](perlfunc#getlogin) instead.
`difftime` This is identical to the C function `difftime()`, for returning the time difference (in seconds) between two times (as returned by `time()`), see ["time"](#time).
`div` Not implemented. `div()` is C-specific, use ["int" in perlfunc](perlfunc#int) on the usual `/` division and the modulus `%`.
`dup` This is similar to the C function `dup()`, for duplicating a file descriptor.
This uses file descriptors such as those obtained by calling `POSIX::open`.
Returns `undef` on failure.
`dup2` This is similar to the C function `dup2()`, for duplicating a file descriptor to an another known file descriptor.
This uses file descriptors such as those obtained by calling `POSIX::open`.
Returns `undef` on failure.
`erf` The error function [C99]. Added in Perl v5.22.
`erfc` The complementary error function [C99]. Added in Perl v5.22.
`errno` Returns the value of errno.
```
$errno = POSIX::errno();
```
This identical to the numerical values of the `$!`, see ["$ERRNO" in perlvar](perlvar#%24ERRNO).
`execl` Not implemented. `execl()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`execle` Not implemented. `execle()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`execlp` Not implemented. `execlp()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`execv` Not implemented. `execv()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`execve` Not implemented. `execve()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`execvp` Not implemented. `execvp()` is C-specific, see ["exec" in perlfunc](perlfunc#exec).
`exit` This is identical to Perl's builtin `exit()` function for exiting the program, see ["exit" in perlfunc](perlfunc#exit).
`exp` This is identical to Perl's builtin `exp()` function for returning the exponent (*e*-based) of the numerical argument, see ["exp" in perlfunc](perlfunc#exp).
`expm1` Equivalent to `exp(x) - 1`, but more precise for small argument values [C99]. Added in Perl v5.22.
See also ["log1p"](#log1p).
`fabs` This is identical to Perl's builtin `abs()` function for returning the absolute value of the numerical argument, see ["abs" in perlfunc](perlfunc#abs).
`fclose` Not implemented. Use method `IO::Handle::close()` instead, or see ["close" in perlfunc](perlfunc#close).
`fcntl` This is identical to Perl's builtin `fcntl()` function, see ["fcntl" in perlfunc](perlfunc#fcntl).
`fdopen` Not implemented. Use method `IO::Handle::new_from_fd()` instead, or see ["open" in perlfunc](perlfunc#open).
`feof` Not implemented. Use method `IO::Handle::eof()` instead, or see ["eof" in perlfunc](perlfunc#eof).
`ferror` Not implemented. Use method `IO::Handle::error()` instead.
`fflush` Not implemented. Use method `IO::Handle::flush()` instead. See also `["$OUTPUT\_AUTOFLUSH" in perlvar](perlvar#%24OUTPUT_AUTOFLUSH)`.
`fgetc` Not implemented. Use method `IO::Handle::getc()` instead, or see ["read" in perlfunc](perlfunc#read).
`fgetpos` Not implemented. Use method `IO::Seekable::getpos()` instead, or see ["seek" in perlfunc](perlfunc#seek).
`fgets` Not implemented. Use method `IO::Handle::gets()` instead. Similar to <>, also known as ["readline" in perlfunc](perlfunc#readline).
`fileno` Not implemented. Use method `IO::Handle::fileno()` instead, or see ["fileno" in perlfunc](perlfunc#fileno).
`floor` This is identical to the C function `floor()`, returning the largest integer value less than or equal to the numerical argument.
`fdim` "Positive difference", `x - y` if `x > y`, zero otherwise [C99]. Added in Perl v5.22.
`fegetround` Returns the current floating point rounding mode, one of
```
FE_TONEAREST FE_TOWARDZERO FE_UPWARD FE_DOWNWARD
```
`FE_TONEAREST` is like ["round"](#round), `FE_TOWARDZERO` is like ["trunc"](#trunc) [C99]. Added in Perl v5.22.
`fesetround` Sets the floating point rounding mode, see ["fegetround"](#fegetround) [C99]. Added in Perl v5.22.
`fma` "Fused multiply-add", `x * y + z`, possibly faster (and less lossy) than the explicit two operations [C99]. Added in Perl v5.22.
```
my $fused = POSIX::fma($x, $y, $z);
```
`fmax` Maximum of `x` and `y`, except when either is `NaN`, returns the other [C99]. Added in Perl v5.22.
```
my $min = POSIX::fmax($x, $y);
```
`fmin` Minimum of `x` and `y`, except when either is `NaN`, returns the other [C99]. Added in Perl v5.22.
```
my $min = POSIX::fmin($x, $y);
```
`fmod` This is identical to the C function `fmod()`.
```
$r = fmod($x, $y);
```
It returns the remainder `$r = $x - $n*$y`, where `$n = trunc($x/$y)`. The `$r` has the same sign as `$x` and magnitude (absolute value) less than the magnitude of `$y`.
`fopen` Not implemented. Use method `IO::File::open()` instead, or see ["open" in perlfunc](perlfunc#open).
`fork` This is identical to Perl's builtin `fork()` function for duplicating the current process, see ["fork" in perlfunc](perlfunc#fork) and <perlfork> if you are in Windows.
`fpathconf` Retrieves the value of a configurable limit on a file or directory. This uses file descriptors such as those obtained by calling `POSIX::open`.
The following will determine the maximum length of the longest allowable pathname on the filesystem which holds */var/foo*.
```
$fd = POSIX::open( "/var/foo", &POSIX::O_RDONLY );
$path_max = POSIX::fpathconf($fd, &POSIX::_PC_PATH_MAX);
```
Returns `undef` on failure.
`fpclassify` Returns one of
```
FP_NORMAL FP_ZERO FP_SUBNORMAL FP_INFINITE FP_NAN
```
telling the class of the argument [C99]. `FP_INFINITE` is positive or negative infinity, `FP_NAN` is not-a-number. `FP_SUBNORMAL` means subnormal numbers (also known as denormals), very small numbers with low precision. `FP_ZERO` is zero. `FP_NORMAL` is all the rest. Added in Perl v5.22.
`fprintf` Not implemented. `fprintf()` is C-specific, see ["printf" in perlfunc](perlfunc#printf) instead.
`fputc` Not implemented. `fputc()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`fputs` Not implemented. `fputs()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`fread` Not implemented. `fread()` is C-specific, see ["read" in perlfunc](perlfunc#read) instead.
`free` Not implemented. `free()` is C-specific. Perl does memory management transparently.
`freopen` Not implemented. `freopen()` is C-specific, see ["open" in perlfunc](perlfunc#open) instead.
`frexp` Return the mantissa and exponent of a floating-point number.
```
($mantissa, $exponent) = POSIX::frexp( 1.234e56 );
```
`fscanf` Not implemented. `fscanf()` is C-specific, use <> and regular expressions instead.
`fseek` Not implemented. Use method `IO::Seekable::seek()` instead, or see ["seek" in perlfunc](perlfunc#seek).
`fsetpos` Not implemented. Use method `IO::Seekable::setpos()` instead, or seek ["seek" in perlfunc](perlfunc#seek).
`fstat` Get file status. This uses file descriptors such as those obtained by calling `POSIX::open`. The data returned is identical to the data from Perl's builtin `stat` function.
```
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
@stats = POSIX::fstat( $fd );
```
`fsync` Not implemented. Use method `IO::Handle::sync()` instead.
`ftell` Not implemented. Use method `IO::Seekable::tell()` instead, or see ["tell" in perlfunc](perlfunc#tell).
`fwrite` Not implemented. `fwrite()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`getc` This is identical to Perl's builtin `getc()` function, see ["getc" in perlfunc](perlfunc#getc).
`getchar` Returns one character from STDIN. Identical to Perl's `getc()`, see ["getc" in perlfunc](perlfunc#getc).
`getcwd` Returns the name of the current working directory. See also [Cwd](cwd).
`getegid` Returns the effective group identifier. Similar to Perl' s builtin variable `$(`, see ["$EGID" in perlvar](perlvar#%24EGID).
`getenv` Returns the value of the specified environment variable. The same information is available through the `%ENV` array.
`geteuid` Returns the effective user identifier. Identical to Perl's builtin `$>` variable, see ["$EUID" in perlvar](perlvar#%24EUID).
`getgid` Returns the user's real group identifier. Similar to Perl's builtin variable `$)`, see ["$GID" in perlvar](perlvar#%24GID).
`getgrgid` This is identical to Perl's builtin `getgrgid()` function for returning group entries by group identifiers, see ["getgrgid" in perlfunc](perlfunc#getgrgid).
`getgrnam` This is identical to Perl's builtin `getgrnam()` function for returning group entries by group names, see ["getgrnam" in perlfunc](perlfunc#getgrnam).
`getgroups` Returns the ids of the user's supplementary groups. Similar to Perl's builtin variable `$)`, see ["$GID" in perlvar](perlvar#%24GID).
`getlogin` This is identical to Perl's builtin `getlogin()` function for returning the user name associated with the current session, see ["getlogin" in perlfunc](perlfunc#getlogin).
`getpayload`
```
use POSIX ':nan_payload';
getpayload($var)
```
Returns the `NaN` payload. Added in Perl v5.24.
Note the API instability warning in ["setpayload"](#setpayload).
See ["nan"](#nan) for more discussion about `NaN`.
`getpgrp` This is identical to Perl's builtin `getpgrp()` function for returning the process group identifier of the current process, see ["getpgrp" in perlfunc](perlfunc#getpgrp).
`getpid` Returns the process identifier. Identical to Perl's builtin variable `$$`, see ["$PID" in perlvar](perlvar#%24PID).
`getppid` This is identical to Perl's builtin `getppid()` function for returning the process identifier of the parent process of the current process , see ["getppid" in perlfunc](perlfunc#getppid).
`getpwnam` This is identical to Perl's builtin `getpwnam()` function for returning user entries by user names, see ["getpwnam" in perlfunc](perlfunc#getpwnam).
`getpwuid` This is identical to Perl's builtin `getpwuid()` function for returning user entries by user identifiers, see ["getpwuid" in perlfunc](perlfunc#getpwuid).
`gets` Returns one line from `STDIN`, similar to <>, also known as the `readline()` function, see ["readline" in perlfunc](perlfunc#readline).
**NOTE**: if you have C programs that still use `gets()`, be very afraid. The `gets()` function is a source of endless grief because it has no buffer overrun checks. It should **never** be used. The `fgets()` function should be preferred instead.
`getuid` Returns the user's identifier. Identical to Perl's builtin `$<` variable, see ["$UID" in perlvar](perlvar#%24UID).
`gmtime` This is identical to Perl's builtin `gmtime()` function for converting seconds since the epoch to a date in Greenwich Mean Time, see ["gmtime" in perlfunc](perlfunc#gmtime).
`hypot` Equivalent to `sqrt(x \* x + y \* y)` except more stable on very large or very small arguments [C99]. Added in Perl v5.22.
`ilogb` Integer binary logarithm [C99]. Added in Perl v5.22.
For example `ilogb(20)` is 4, as an integer.
See also ["logb"](#logb).
`Inf` The infinity as a constant:
```
use POSIX qw(Inf);
my $pos_inf = +Inf; # Or just Inf.
my $neg_inf = -Inf;
```
See also ["isinf"](#isinf), and ["fpclassify"](#fpclassify).
`isalnum` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:alnum:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isalpha` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:alpha:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isatty` Returns a boolean indicating whether the specified filehandle is connected to a tty. Similar to the `-t` operator, see ["-X" in perlfunc](perlfunc#-X).
`iscntrl` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:cntrl:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isdigit` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:digit:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isfinite` Returns true if the argument is a finite number (that is, not an infinity, or the not-a-number) [C99]. Added in Perl v5.22.
See also ["isinf"](#isinf), ["isnan"](#isnan), and ["fpclassify"](#fpclassify).
`isgraph` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:graph:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isgreater` (Also `isgreaterequal`, `isless`, `islessequal`, `islessgreater`, `isunordered`)
Floating point comparisons which handle the `NaN` [C99]. Added in Perl v5.22.
`isinf` Returns true if the argument is an infinity (positive or negative) [C99]. Added in Perl v5.22.
See also ["Inf"](#Inf), ["isnan"](#isnan), ["isfinite"](#isfinite), and ["fpclassify"](#fpclassify).
`islower` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:lower:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isnan` Returns true if the argument is `NaN` (not-a-number) [C99]. Added in Perl v5.22.
Note that you can also test for "`NaN`-ness" with [equality operators](perlop#Equality-Operators) (`==` or `!=`), as in
```
print "x is not a NaN\n" if $x == $x;
```
since the `NaN` is not equal to anything, **including itself**.
See also ["nan"](#nan), ["NaN"](#NaN), ["isinf"](#isinf), and ["fpclassify"](#fpclassify).
`isnormal` Returns true if the argument is normal (that is, not a subnormal/denormal, and not an infinity, or a not-a-number) [C99]. Added in Perl v5.22.
See also ["isfinite"](#isfinite), and ["fpclassify"](#fpclassify).
`isprint` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:print:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`ispunct` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:punct:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`issignaling`
```
use POSIX ':nan_payload';
issignaling($var, $payload)
```
Return true if the argument is a *signaling* NaN. Added in Perl v5.24.
Note the API instability warning in ["setpayload"](#setpayload).
See ["nan"](#nan) for more discussion about `NaN`.
`isspace` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:space:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isupper` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:upper:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`isxdigit` This function has been removed as of Perl v5.24. It was very similar to matching against `qr/ ^ [[:xdigit:]]+ $ /x`, which you should convert to use instead. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
`j0` `j1` `jn` `y0` `y1` `yn` The Bessel function of the first kind of the order zero.
`kill` This is identical to Perl's builtin `kill()` function for sending signals to processes (often to terminate them), see ["kill" in perlfunc](perlfunc#kill).
`labs` Not implemented. (For returning absolute values of long integers.) `labs()` is C-specific, see ["abs" in perlfunc](perlfunc#abs) instead.
`lchown` This is identical to the C function, except the order of arguments is consistent with Perl's builtin `chown()` with the added restriction of only one path, not a list of paths. Does the same thing as the `chown()` function but changes the owner of a symbolic link instead of the file the symbolic link points to.
```
POSIX::lchown($uid, $gid, $file_path);
```
`ldexp` This is identical to the C function `ldexp()` for multiplying floating point numbers with powers of two.
```
$x_quadrupled = POSIX::ldexp($x, 2);
```
`ldiv` Not implemented. (For computing dividends of long integers.) `ldiv()` is C-specific, use `/` and `int()` instead.
`lgamma` The logarithm of the Gamma function [C99]. Added in Perl v5.22.
See also ["tgamma"](#tgamma).
`log1p` Equivalent to `log(1 + x)`, but more stable results for small argument values [C99]. Added in Perl v5.22.
`log2` Logarithm base two [C99]. Added in Perl v5.22.
See also ["expm1"](#expm1).
`logb` Integer binary logarithm [C99]. Added in Perl v5.22.
For example `logb(20)` is 4, as a floating point number.
See also ["ilogb"](#ilogb).
`link` This is identical to Perl's builtin `link()` function for creating hard links into files, see ["link" in perlfunc](perlfunc#link).
`localeconv` Get numeric formatting information. Returns a reference to a hash containing the formatting values of the locale that currently underlies the program, regardless of whether or not it is called from within the scope of a `use locale`. Users of this function should also read <perllocale>, which provides a comprehensive discussion of Perl locale handling, including [a section devoted to this function](perllocale#The-localeconv-function). Prior to Perl 5.28, or when operating in a non thread-safe environment, it should not be used in a threaded application unless it's certain that the underlying locale is C or POSIX. This is because it otherwise changes the locale, which globally affects all threads simultaneously. Windows platforms starting with Visual Studio 2005 are mostly thread-safe, but use of this function in those prior to Visual Studio 2015 can have a race with a thread that has called ["switch\_to\_global\_locale" in perlapi](perlapi#switch_to_global_locale).
Here is how to query the database for the **de** (Deutsch or German) locale.
```
my $loc = POSIX::setlocale( &POSIX::LC_ALL, "de" );
print "Locale: \"$loc\"\n";
my $lconv = POSIX::localeconv();
foreach my $property (qw(
decimal_point
thousands_sep
grouping
int_curr_symbol
currency_symbol
mon_decimal_point
mon_thousands_sep
mon_grouping
positive_sign
negative_sign
int_frac_digits
frac_digits
p_cs_precedes
p_sep_by_space
n_cs_precedes
n_sep_by_space
p_sign_posn
n_sign_posn
int_p_cs_precedes
int_p_sep_by_space
int_n_cs_precedes
int_n_sep_by_space
int_p_sign_posn
int_n_sign_posn
))
{
printf qq(%s: "%s",\n),
$property, $lconv->{$property};
}
```
The members whose names begin with `int_p_` and `int_n_` were added by POSIX.1-2008 and are only available on systems that support them.
`localtime` This is identical to Perl's builtin `localtime()` function for converting seconds since the epoch to a date see ["localtime" in perlfunc](perlfunc#localtime) except that `POSIX::localtime()` must be provided an explicit value (rather than relying on an implicit `$_`):
```
@localtime = POSIX::localtime(time); # good
@localtime = localtime(); # good
@localtime = POSIX::localtime(); # throws exception
```
`log` This is identical to Perl's builtin `log()` function, returning the natural (*e*-based) logarithm of the numerical argument, see ["log" in perlfunc](perlfunc#log).
`log10` This is identical to the C function `log10()`, returning the 10-base logarithm of the numerical argument. You can also use
```
sub log10 { log($_[0]) / log(10) }
```
or
```
sub log10 { log($_[0]) / 2.30258509299405 }
```
or
```
sub log10 { log($_[0]) * 0.434294481903252 }
```
`longjmp` Not implemented. `longjmp()` is C-specific: use ["die" in perlfunc](perlfunc#die) instead.
`lseek` Move the file's read/write position. This uses file descriptors such as those obtained by calling `POSIX::open`.
```
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$off_t = POSIX::lseek( $fd, 0, &POSIX::SEEK_SET );
```
Returns `undef` on failure.
`lrint` Depending on the current floating point rounding mode, rounds the argument either toward nearest (like ["round"](#round)), toward zero (like ["trunc"](#trunc)), downward (toward negative infinity), or upward (toward positive infinity) [C99]. Added in Perl v5.22.
For the rounding mode, see ["fegetround"](#fegetround).
`lround` Like ["round"](#round), but as integer, as opposed to floating point [C99]. Added in Perl v5.22.
See also ["ceil"](#ceil), ["floor"](#floor), ["trunc"](#trunc).
Owing to an oversight, this is not currently exported by default, or as part of the `:math_h_c99` export tag; importing it must therefore be done by explicit name.
`malloc` Not implemented. `malloc()` is C-specific. Perl does memory management transparently.
`mblen` This is the same as the C function `mblen()` on unthreaded perls. On threaded perls, it transparently (almost) substitutes the more thread-safe [`mbrlen`(3)](mbrlen(3)), if available, instead of `mblen`.
Core Perl does not have any support for wide and multibyte locales, except Unicode UTF-8 locales. This function, in conjunction with ["mbtowc"](#mbtowc) and ["wctomb"](#wctomb) may be used to roll your own decoding/encoding of other types of multi-byte locales.
Use `undef` as the first parameter to this function to get the effect of passing NULL as the first parameter to `mblen`. This resets any shift state to its initial value. The return value is undefined if `mbrlen` was substituted, so you should never rely on it.
When the first parameter is a scalar containing a value that either is a PV string or can be forced into one, the return value is the number of bytes occupied by the first character of that string; or 0 if that first character is the wide NUL character; or negative if there is an error. This is based on the locale that currently underlies the program, regardless of whether or not the function is called from Perl code that is within the scope of `use locale`. Perl makes no attempt at hiding from your code any differences in the `errno` setting between `mblen` and `mbrlen`. It does set `errno` to 0 before calling them.
The optional second parameter is ignored if it is larger than the actual length of the first parameter string.
`mbtowc` This is the same as the C function `mbtowc()` on unthreaded perls. On threaded perls, it transparently (almost) substitutes the more thread-safe [`mbrtowc`(3)](mbrtowc(3)), if available, instead of `mbtowc`.
Core Perl does not have any support for wide and multibyte locales, except Unicode UTF-8 locales. This function, in conjunction with ["mblen"](#mblen) and ["wctomb"](#wctomb) may be used to roll your own decoding/encoding of other types of multi-byte locales.
The first parameter is a scalar into which, upon success, the wide character represented by the multi-byte string contained in the second parameter is stored. The optional third parameter is ignored if it is larger than the actual length of the second parameter string.
Use `undef` as the second parameter to this function to get the effect of passing NULL as the second parameter to `mbtowc`. This resets any shift state to its initial value. The return value is undefined if `mbrtowc` was substituted, so you should never rely on it.
When the second parameter is a scalar containing a value that either is a PV string or can be forced into one, the return value is the number of bytes occupied by the first character of that string; or 0 if that first character is the wide NUL character; or negative if there is an error. This is based on the locale that currently underlies the program, regardless of whether or not the function is called from Perl code that is within the scope of `use locale`. Perl makes no attempt at hiding from your code any differences in the `errno` setting between `mbtowc` and `mbrtowc`. It does set `errno` to 0 before calling them.
`memchr` Not implemented. `memchr()` is C-specific, see ["index" in perlfunc](perlfunc#index) instead.
`memcmp` Not implemented. `memcmp()` is C-specific, use `eq` instead, see <perlop>.
`memcpy` Not implemented. `memcpy()` is C-specific, use `=`, see <perlop>, or see ["substr" in perlfunc](perlfunc#substr).
`memmove` Not implemented. `memmove()` is C-specific, use `=`, see <perlop>, or see ["substr" in perlfunc](perlfunc#substr).
`memset` Not implemented. `memset()` is C-specific, use `x` instead, see <perlop>.
`mkdir` This is identical to Perl's builtin `mkdir()` function for creating directories, see ["mkdir" in perlfunc](perlfunc#mkdir).
`mkfifo` This is similar to the C function `mkfifo()` for creating FIFO special files.
```
if (mkfifo($path, $mode)) { ....
```
Returns `undef` on failure. The `$mode` is similar to the mode of `mkdir()`, see ["mkdir" in perlfunc](perlfunc#mkdir), though for `mkfifo` you **must** specify the `$mode`.
`mktime` Convert date/time info to a calendar time.
Synopsis:
```
mktime(sec, min, hour, mday, mon, year, wday = 0,
yday = 0, isdst = -1)
```
The month (`mon`), weekday (`wday`), and yearday (`yday`) begin at zero, *i.e.*, January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The year (`year`) is given in years since 1900; *i.e.*, the year 1995 is 95; the year 2001 is 101. Consult your system's `mktime()` manpage for details about these and the other arguments.
Calendar time for December 12, 1995, at 10:30 am.
```
$time_t = POSIX::mktime( 0, 30, 10, 12, 11, 95 );
print "Date = ", POSIX::ctime($time_t);
```
Returns `undef` on failure.
`modf` Return the integral and fractional parts of a floating-point number.
```
($fractional, $integral) = POSIX::modf( 3.14 );
```
See also ["round"](#round).
`NaN` The not-a-number as a constant:
```
use POSIX qw(NaN);
my $nan = NaN;
```
See also ["nan"](#nan), `/isnan`, and ["fpclassify"](#fpclassify).
`nan`
```
my $nan = nan();
```
Returns `NaN`, not-a-number [C99]. Added in Perl v5.22.
The returned NaN is always a *quiet* NaN, as opposed to *signaling*.
With an argument, can be used to generate a NaN with *payload*. The argument is first interpreted as a floating point number, but then any fractional parts are truncated (towards zero), and the value is interpreted as an unsigned integer. The bits of this integer are stored in the unused bits of the NaN.
The result has a dual nature: it is a NaN, but it also carries the integer inside it. The integer can be retrieved with ["getpayload"](#getpayload). Note, though, that the payload is not propagated, not even on copies, and definitely not in arithmetic operations.
How many bits fit in the NaN depends on what kind of floating points are being used, but on the most common platforms (64-bit IEEE 754, or the x86 80-bit long doubles) there are 51 and 61 bits available, respectively. (There would be 52 and 62, but the quiet/signaling bit of NaNs takes away one.) However, because of the floating-point-to- integer-and-back conversions, please test carefully whether you get back what you put in. If your integers are only 32 bits wide, you probably should not rely on more than 32 bits of payload.
Whether a "signaling" NaN is in any way different from a "quiet" NaN, depends on the platform. Also note that the payload of the default NaN (no argument to nan()) is not necessarily zero, use `setpayload` to explicitly set the payload. On some platforms like the 32-bit x86, (unless using the 80-bit long doubles) the signaling bit is not supported at all.
See also ["isnan"](#isnan), ["NaN"](#NaN), ["setpayload"](#setpayload) and ["issignaling"](#issignaling).
`nearbyint` Returns the nearest integer to the argument, according to the current rounding mode (see ["fegetround"](#fegetround)) [C99]. Added in Perl v5.22.
`nextafter` Returns the next representable floating point number after `x` in the direction of `y` [C99]. Added in Perl v5.22.
```
my $nextafter = POSIX::nextafter($x, $y);
```
Like ["nexttoward"](#nexttoward), but potentially less accurate.
`nexttoward` Returns the next representable floating point number after `x` in the direction of `y` [C99]. Added in Perl v5.22.
```
my $nexttoward = POSIX::nexttoward($x, $y);
```
Like ["nextafter"](#nextafter), but potentially more accurate.
`nice` This is similar to the C function `nice()`, for changing the scheduling preference of the current process. Positive arguments mean a more polite process, negative values a more needy process. Normal (non-root) user processes can only change towards being more polite.
Returns `undef` on failure.
`offsetof` Not implemented. `offsetof()` is C-specific, you probably want to see ["pack" in perlfunc](perlfunc#pack) instead.
`open` Open a file for reading for writing. This returns file descriptors, not Perl filehandles. Use `POSIX::close` to close the file.
Open a file read-only with mode 0666.
```
$fd = POSIX::open( "foo" );
```
Open a file for read and write.
```
$fd = POSIX::open( "foo", &POSIX::O_RDWR );
```
Open a file for write, with truncation.
```
$fd = POSIX::open(
"foo", &POSIX::O_WRONLY | &POSIX::O_TRUNC
);
```
Create a new file with mode 0640. Set up the file for writing.
```
$fd = POSIX::open(
"foo", &POSIX::O_CREAT | &POSIX::O_WRONLY, 0640
);
```
Returns `undef` on failure.
See also ["sysopen" in perlfunc](perlfunc#sysopen).
`opendir` Open a directory for reading.
```
$dir = POSIX::opendir( "/var" );
@files = POSIX::readdir( $dir );
POSIX::closedir( $dir );
```
Returns `undef` on failure.
`pathconf` Retrieves the value of a configurable limit on a file or directory.
The following will determine the maximum length of the longest allowable pathname on the filesystem which holds `/var`.
```
$path_max = POSIX::pathconf( "/var",
&POSIX::_PC_PATH_MAX );
```
Returns `undef` on failure.
`pause` This is similar to the C function `pause()`, which suspends the execution of the current process until a signal is received.
Returns `undef` on failure.
`perror` This is identical to the C function `perror()`, which outputs to the standard error stream the specified message followed by `": "` and the current error string. Use the `warn()` function and the `$!` variable instead, see ["warn" in perlfunc](perlfunc#warn) and ["$ERRNO" in perlvar](perlvar#%24ERRNO).
`pipe` Create an interprocess channel. This returns file descriptors like those returned by `POSIX::open`.
```
my ($read, $write) = POSIX::pipe();
POSIX::write( $write, "hello", 5 );
POSIX::read( $read, $buf, 5 );
```
See also ["pipe" in perlfunc](perlfunc#pipe).
`pow` Computes `$x` raised to the power `$exponent`.
```
$ret = POSIX::pow( $x, $exponent );
```
You can also use the `**` operator, see <perlop>.
`printf` Formats and prints the specified arguments to `STDOUT`. See also ["printf" in perlfunc](perlfunc#printf).
`putc` Not implemented. `putc()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`putchar` Not implemented. `putchar()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`puts` Not implemented. `puts()` is C-specific, see ["print" in perlfunc](perlfunc#print) instead.
`qsort` Not implemented. `qsort()` is C-specific, see ["sort" in perlfunc](perlfunc#sort) instead.
`raise` Sends the specified signal to the current process. See also ["kill" in perlfunc](perlfunc#kill) and the `$$` in ["$PID" in perlvar](perlvar#%24PID).
`rand` Not implemented. `rand()` is non-portable, see ["rand" in perlfunc](perlfunc#rand) instead.
`read` Read from a file. This uses file descriptors such as those obtained by calling `POSIX::open`. If the buffer `$buf` is not large enough for the read then Perl will extend it to make room for the request.
```
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$bytes = POSIX::read( $fd, $buf, 3 );
```
Returns `undef` on failure.
See also ["sysread" in perlfunc](perlfunc#sysread).
`readdir` This is identical to Perl's builtin `readdir()` function for reading directory entries, see ["readdir" in perlfunc](perlfunc#readdir).
`realloc` Not implemented. `realloc()` is C-specific. Perl does memory management transparently.
`remainder` Given `x` and `y`, returns the value `x - n*y`, where `n` is the integer closest to `x`/`y` [C99]. Added in Perl v5.22.
```
my $remainder = POSIX::remainder($x, $y)
```
See also ["remquo"](#remquo).
`remove` Deletes a name from the filesystem. Calls ["unlink" in perlfunc](perlfunc#unlink) for files and ["rmdir" in perlfunc](perlfunc#rmdir) for directories.
`remquo` Like ["remainder"](#remainder) but also returns the low-order bits of the quotient (n) [C99]. Added in Perl v5.22.
(This is quite esoteric interface, mainly used to implement numerical algorithms.)
`rename` This is identical to Perl's builtin `rename()` function for renaming files, see ["rename" in perlfunc](perlfunc#rename).
`rewind` Seeks to the beginning of the file.
`rewinddir` This is identical to Perl's builtin `rewinddir()` function for rewinding directory entry streams, see ["rewinddir" in perlfunc](perlfunc#rewinddir).
`rint` Identical to ["lrint"](#lrint).
`rmdir` This is identical to Perl's builtin `rmdir()` function for removing (empty) directories, see ["rmdir" in perlfunc](perlfunc#rmdir).
`round` Returns the integer (but still as floating point) nearest to the argument [C99]. Added in Perl v5.22.
See also ["ceil"](#ceil), ["floor"](#floor), ["lround"](#lround), ["modf"](#modf), and ["trunc"](#trunc).
`scalbn` Returns `x * 2**y` [C99]. Added in Perl v5.22.
See also ["frexp"](#frexp) and ["ldexp"](#ldexp).
`scanf` Not implemented. `scanf()` is C-specific, use <> and regular expressions instead, see <perlre>.
`setgid` Sets the real group identifier and the effective group identifier for this process. Similar to assigning a value to the Perl's builtin `$)` variable, see ["$EGID" in perlvar](perlvar#%24EGID), except that the latter will change only the real user identifier, and that the setgid() uses only a single numeric argument, as opposed to a space-separated list of numbers.
`setjmp` Not implemented. `setjmp()` is C-specific: use `eval {}` instead, see ["eval" in perlfunc](perlfunc#eval).
`setlocale` WARNING! Prior to Perl 5.28 or on a system that does not support thread-safe locale operations, do NOT use this function in a [thread](threads). The locale will change in all other threads at the same time, and should your thread get paused by the operating system, and another started, that thread will not have the locale it is expecting. On some platforms, there can be a race leading to segfaults if two threads call this function nearly simultaneously. This warning does not apply on unthreaded builds, or on perls where `${^SAFE_LOCALES}` exists and is non-zero; namely Perl 5.28 and later compiled to be locale-thread-safe.
This function modifies and queries the program's underlying locale. Users of this function should read <perllocale>, whch provides a comprehensive discussion of Perl locale handling, knowledge of which is necessary to properly use this function. It contains [a section devoted to this function](perllocale#The-setlocale-function). The discussion here is merely a summary reference for `setlocale()`. Note that Perl itself is almost entirely unaffected by the locale except within the scope of `"use locale"`. (Exceptions are listed in ["Not within the scope of "use locale"" in perllocale](perllocale#Not-within-the-scope-of-%22use-locale%22), and locale-dependent functions within the POSIX module ARE always affected by the current locale.)
The following examples assume
```
use POSIX qw(setlocale LC_ALL LC_CTYPE);
```
has been issued.
The following will set the traditional UNIX system locale behavior (the second argument `"C"`).
```
$loc = setlocale( LC_ALL, "C" );
```
The following will query the current `LC_CTYPE` category. (No second argument means 'query'.)
```
$loc = setlocale( LC_CTYPE );
```
The following will set the `LC_CTYPE` behaviour according to the locale environment variables (the second argument `""`). Please see your system's `setlocale(3)` documentation for the locale environment variables' meaning or consult <perllocale>.
```
$loc = setlocale( LC_CTYPE, "" );
```
The following will set the `LC_COLLATE` behaviour to Argentinian Spanish. **NOTE**: The naming and availability of locales depends on your operating system. Please consult <perllocale> for how to find out which locales are available in your system.
```
$loc = setlocale( LC_COLLATE, "es_AR.ISO8859-1" );
```
`setpayload`
```
use POSIX ':nan_payload';
setpayload($var, $payload);
```
Sets the `NaN` payload of var. Added in Perl v5.24.
NOTE: the NaN payload APIs are based on the latest (as of June 2015) proposed ISO C interfaces, but they are not yet a standard. Things may change.
See ["nan"](#nan) for more discussion about `NaN`.
See also ["setpayloadsig"](#setpayloadsig), ["isnan"](#isnan), ["getpayload"](#getpayload), and ["issignaling"](#issignaling).
`setpayloadsig`
```
use POSIX ':nan_payload';
setpayloadsig($var, $payload);
```
Like ["setpayload"](#setpayload) but also makes the NaN *signaling*. Added in Perl v5.24.
Depending on the platform the NaN may or may not behave differently.
Note the API instability warning in ["setpayload"](#setpayload).
Note that because how the floating point formats work out, on the most common platforms signaling payload of zero is best avoided, since it might end up being identical to `+Inf`.
See also ["nan"](#nan), ["isnan"](#isnan), ["getpayload"](#getpayload), and ["issignaling"](#issignaling).
`setpgid` This is similar to the C function `setpgid()` for setting the process group identifier of the current process.
Returns `undef` on failure.
`setsid` This is identical to the C function `setsid()` for setting the session identifier of the current process.
`setuid` Sets the real user identifier and the effective user identifier for this process. Similar to assigning a value to the Perl's builtin `$<` variable, see ["$UID" in perlvar](perlvar#%24UID), except that the latter will change only the real user identifier.
`sigaction` Detailed signal management. This uses `POSIX::SigAction` objects for the `action` and `oldaction` arguments (the oldaction can also be just a hash reference). Consult your system's `sigaction` manpage for details, see also ["POSIX::SigRt"](#POSIX%3A%3ASigRt).
Synopsis:
```
sigaction(signal, action, oldaction = 0)
```
Returns `undef` on failure. The `signal` must be a number (like `SIGHUP`), not a string (like `"SIGHUP"`), though Perl does try hard to understand you.
If you use the `SA_SIGINFO` flag, the signal handler will in addition to the first argument, the signal name, also receive a second argument, a hash reference, inside which are the following keys with the following semantics, as defined by POSIX/SUSv3:
```
signo the signal number
errno the error number
code if this is zero or less, the signal was sent by
a user process and the uid and pid make sense,
otherwise the signal was sent by the kernel
```
The constants for specific `code` values can be imported individually or using the `:signal_h_si_code` tag, since Perl v5.24.
The following are also defined by POSIX/SUSv3, but unfortunately not very widely implemented:
```
pid the process id generating the signal
uid the uid of the process id generating the signal
status exit value or signal for SIGCHLD
band band event for SIGPOLL
addr address of faulting instruction or memory
reference for SIGILL, SIGFPE, SIGSEGV or SIGBUS
```
A third argument is also passed to the handler, which contains a copy of the raw binary contents of the `siginfo` structure: if a system has some non-POSIX fields, this third argument is where to `unpack()` them from.
Note that not all `siginfo` values make sense simultaneously (some are valid only for certain signals, for example), and not all values make sense from Perl perspective, you should to consult your system's `sigaction` and possibly also `siginfo` documentation.
`siglongjmp` Not implemented. `siglongjmp()` is C-specific: use ["die" in perlfunc](perlfunc#die) instead.
`signbit` Returns zero for positive arguments, non-zero for negative arguments [C99]. Added in Perl v5.22.
`sigpending` Examine signals that are blocked and pending. This uses `POSIX::SigSet` objects for the `sigset` argument. Consult your system's `sigpending` manpage for details.
Synopsis:
```
sigpending(sigset)
```
Returns `undef` on failure.
`sigprocmask` Change and/or examine calling process's signal mask. This uses `POSIX::SigSet` objects for the `sigset` and `oldsigset` arguments. Consult your system's `sigprocmask` manpage for details.
Synopsis:
```
sigprocmask(how, sigset, oldsigset = 0)
```
Returns `undef` on failure.
Note that you can't reliably block or unblock a signal from its own signal handler if you're using safe signals. Other signals can be blocked or unblocked reliably.
`sigsetjmp` Not implemented. `sigsetjmp()` is C-specific: use `eval {}` instead, see ["eval" in perlfunc](perlfunc#eval).
`sigsuspend` Install a signal mask and suspend process until signal arrives. This uses `POSIX::SigSet` objects for the `signal_mask` argument. Consult your system's `sigsuspend` manpage for details.
Synopsis:
```
sigsuspend(signal_mask)
```
Returns `undef` on failure.
`sin` This is identical to Perl's builtin `sin()` function for returning the sine of the numerical argument, see ["sin" in perlfunc](perlfunc#sin). See also <Math::Trig>.
`sinh` This is identical to the C function `sinh()` for returning the hyperbolic sine of the numerical argument. See also <Math::Trig>.
`sleep` This is functionally identical to Perl's builtin `sleep()` function for suspending the execution of the current for process for certain number of seconds, see ["sleep" in perlfunc](perlfunc#sleep). There is one significant difference, however: `POSIX::sleep()` returns the number of **unslept** seconds, while the `CORE::sleep()` returns the number of slept seconds.
`sprintf` This is similar to Perl's builtin `sprintf()` function for returning a string that has the arguments formatted as requested, see ["sprintf" in perlfunc](perlfunc#sprintf).
`sqrt` This is identical to Perl's builtin `sqrt()` function. for returning the square root of the numerical argument, see ["sqrt" in perlfunc](perlfunc#sqrt).
`srand` Give a seed the pseudorandom number generator, see ["srand" in perlfunc](perlfunc#srand).
`sscanf` Not implemented. `sscanf()` is C-specific, use regular expressions instead, see <perlre>.
`stat` This is identical to Perl's builtin `stat()` function for returning information about files and directories.
`strcat` Not implemented. `strcat()` is C-specific, use `.=` instead, see <perlop>.
`strchr` Not implemented. `strchr()` is C-specific, see ["index" in perlfunc](perlfunc#index) instead.
`strcmp` Not implemented. `strcmp()` is C-specific, use `eq` or `cmp` instead, see <perlop>.
`strcoll` This is identical to the C function `strcoll()` for collating (comparing) strings transformed using the `strxfrm()` function. Not really needed since Perl can do this transparently, see <perllocale>.
Beware that in a UTF-8 locale, anything you pass to this function must be in UTF-8; and when not in a UTF-8 locale, anything passed must not be UTF-8 encoded.
Note also that it doesn't make sense for a string to be encoded in one locale (say, ISO-8859-6, Arabic) and to collate it based on another (like ISO-8859-7, Greek). The results will be essentially meaningless.
`strcpy` Not implemented. `strcpy()` is C-specific, use `=` instead, see <perlop>.
`strcspn` Not implemented. `strcspn()` is C-specific, use regular expressions instead, see <perlre>.
`strerror` Returns the error string for the specified errno. Identical to the string form of `$!`, see ["$ERRNO" in perlvar](perlvar#%24ERRNO).
`strftime` Convert date and time information to string. Returns the string.
Synopsis:
```
strftime(fmt, sec, min, hour, mday, mon, year,
wday = -1, yday = -1, isdst = -1)
```
The month (`mon`), weekday (`wday`), and yearday (`yday`) begin at zero, *i.e.*, January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The year (`year`) is given in years since 1900, *i.e.*, the year 1995 is 95; the year 2001 is 101. Consult your system's `strftime()` manpage for details about these and the other arguments.
If you want your code to be portable, your format (`fmt`) argument should use only the conversion specifiers defined by the ANSI C standard (C89, to play safe). These are `aAbBcdHIjmMpSUwWxXyYZ%`. But even then, the **results** of some of the conversion specifiers are non-portable. For example, the specifiers `aAbBcpZ` change according to the locale settings of the user, and both how to set locales (the locale names) and what output to expect are non-standard. The specifier `c` changes according to the timezone settings of the user and the timezone computation rules of the operating system. The `Z` specifier is notoriously unportable since the names of timezones are non-standard. Sticking to the numeric specifiers is the safest route.
The given arguments are made consistent as though by calling `mktime()` before calling your system's `strftime()` function, except that the `isdst` value is not affected.
The string for Tuesday, December 12, 1995.
```
$str = POSIX::strftime( "%A, %B %d, %Y",
0, 0, 0, 12, 11, 95, 2 );
print "$str\n";
```
`strlen` Not implemented. `strlen()` is C-specific, use `length()` instead, see ["length" in perlfunc](perlfunc#length).
`strncat` Not implemented. `strncat()` is C-specific, use `.=` instead, see <perlop>.
`strncmp` Not implemented. `strncmp()` is C-specific, use `eq` instead, see <perlop>.
`strncpy` Not implemented. `strncpy()` is C-specific, use `=` instead, see <perlop>.
`strpbrk` Not implemented. `strpbrk()` is C-specific, use regular expressions instead, see <perlre>.
`strrchr` Not implemented. `strrchr()` is C-specific, see ["rindex" in perlfunc](perlfunc#rindex) instead.
`strspn` Not implemented. `strspn()` is C-specific, use regular expressions instead, see <perlre>.
`strstr` This is identical to Perl's builtin `index()` function, see ["index" in perlfunc](perlfunc#index).
`strtod` String to double translation. Returns the parsed number and the number of characters in the unparsed portion of the string. Truly POSIX-compliant systems set `$!` (`$ERRNO`) to indicate a translation error, so clear `$!` before calling `strtod`. However, non-POSIX systems may not check for overflow, and therefore will never set `$!`.
`strtod` respects any POSIX `setlocale()` `LC_NUMERIC` settings, regardless of whether or not it is called from Perl code that is within the scope of `use locale`. Prior to Perl 5.28, or when operating in a non thread-safe environment, it should not be used in a threaded application unless it's certain that the underlying locale is C or POSIX. This is because it otherwise changes the locale, which globally affects all threads simultaneously.
To parse a string `$str` as a floating point number use
```
$! = 0;
($num, $n_unparsed) = POSIX::strtod($str);
```
The second returned item and `$!` can be used to check for valid input:
```
if (($str eq '') || ($n_unparsed != 0) || $!) {
die "Non-numeric input $str" . ($! ? ": $!\n" : "\n");
}
```
When called in a scalar context `strtod` returns the parsed number.
`strtok` Not implemented. `strtok()` is C-specific, use regular expressions instead, see <perlre>, or ["split" in perlfunc](perlfunc#split).
`strtol` String to (long) integer translation. Returns the parsed number and the number of characters in the unparsed portion of the string. Truly POSIX-compliant systems set `$!` (`$ERRNO`) to indicate a translation error, so clear `$!` before calling `strtol`. However, non-POSIX systems may not check for overflow, and therefore will never set `$!`.
`strtol` should respect any POSIX *setlocale()* settings.
To parse a string `$str` as a number in some base `$base` use
```
$! = 0;
($num, $n_unparsed) = POSIX::strtol($str, $base);
```
The base should be zero or between 2 and 36, inclusive. When the base is zero or omitted `strtol` will use the string itself to determine the base: a leading "0x" or "0X" means hexadecimal; a leading "0" means octal; any other leading characters mean decimal. Thus, "1234" is parsed as a decimal number, "01234" as an octal number, and "0x1234" as a hexadecimal number.
The second returned item and `$!` can be used to check for valid input:
```
if (($str eq '') || ($n_unparsed != 0) || !$!) {
die "Non-numeric input $str" . $! ? ": $!\n" : "\n";
}
```
When called in a scalar context `strtol` returns the parsed number.
`strtold` Like ["strtod"](#strtod) but for long doubles. Defined only if the system supports long doubles.
`strtoul` String to unsigned (long) integer translation. `strtoul()` is identical to `strtol()` except that `strtoul()` only parses unsigned integers. See ["strtol"](#strtol) for details.
Note: Some vendors supply `strtod()` and `strtol()` but not `strtoul()`. Other vendors that do supply `strtoul()` parse "-1" as a valid value.
`strxfrm` String transformation. Returns the transformed string.
```
$dst = POSIX::strxfrm( $src );
```
Used with `eq` or `cmp` as an alternative to `["strcoll"](#strcoll)`.
Not really needed since Perl can do this transparently, see <perllocale>.
Beware that in a UTF-8 locale, anything you pass to this function must be in UTF-8; and when not in a UTF-8 locale, anything passed must not be UTF-8 encoded.
`sysconf` Retrieves values of system configurable variables.
The following will get the machine's clock speed.
```
$clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK );
```
Returns `undef` on failure.
`system` This is identical to Perl's builtin `system()` function, see ["system" in perlfunc](perlfunc#system).
`tan` This is identical to the C function `tan()`, returning the tangent of the numerical argument. See also <Math::Trig>.
`tanh` This is identical to the C function `tanh()`, returning the hyperbolic tangent of the numerical argument. See also <Math::Trig>.
`tcdrain` This is similar to the C function `tcdrain()` for draining the output queue of its argument stream.
Returns `undef` on failure.
`tcflow` This is similar to the C function `tcflow()` for controlling the flow of its argument stream.
Returns `undef` on failure.
`tcflush` This is similar to the C function `tcflush()` for flushing the I/O buffers of its argument stream.
Returns `undef` on failure.
`tcgetpgrp` This is identical to the C function `tcgetpgrp()` for returning the process group identifier of the foreground process group of the controlling terminal.
`tcsendbreak` This is similar to the C function `tcsendbreak()` for sending a break on its argument stream.
Returns `undef` on failure.
`tcsetpgrp` This is similar to the C function `tcsetpgrp()` for setting the process group identifier of the foreground process group of the controlling terminal.
Returns `undef` on failure.
`tgamma` The Gamma function [C99]. Added in Perl v5.22.
See also ["lgamma"](#lgamma).
`time` This is identical to Perl's builtin `time()` function for returning the number of seconds since the epoch (whatever it is for the system), see ["time" in perlfunc](perlfunc#time).
`times` The `times()` function returns elapsed realtime since some point in the past (such as system startup), user and system times for this process, and user and system times used by child processes. All times are returned in clock ticks.
```
($realtime, $user, $system, $cuser, $csystem)
= POSIX::times();
```
Note: Perl's builtin `times()` function returns four values, measured in seconds.
`tmpfile` Not implemented. Use method `IO::File::new_tmpfile()` instead, or see <File::Temp>.
`tmpnam` For security reasons, which are probably detailed in your system's documentation for the C library `tmpnam()` function, this interface is no longer available since Perl v5.26; instead use <File::Temp>.
`tolower` This function has been removed as of Perl v5.26. This is identical to the C function, except that it can apply to a single character or to a whole string, and currently operates as if the locale always is "C". Consider using the `lc()` function, see ["lc" in perlfunc](perlfunc#lc), see ["lc" in perlfunc](perlfunc#lc), or the equivalent `\L` operator inside doublequotish strings.
`toupper` This function has been removed as of Perl v5.26. This is similar to the C function, except that it can apply to a single character or to a whole string, and currently operates as if the locale always is "C". Consider using the `uc()` function, see ["uc" in perlfunc](perlfunc#uc), or the equivalent `\U` operator inside doublequotish strings.
`trunc` Returns the integer toward zero from the argument [C99]. Added in Perl v5.22.
See also ["ceil"](#ceil), ["floor"](#floor), and ["round"](#round).
`ttyname` This is identical to the C function `ttyname()` for returning the name of the current terminal.
`tzname` Retrieves the time conversion information from the `tzname` variable.
```
POSIX::tzset();
($std, $dst) = POSIX::tzname();
```
`tzset` This is identical to the C function `tzset()` for setting the current timezone based on the environment variable `TZ`, to be used by `ctime()`, `localtime()`, `mktime()`, and `strftime()` functions.
`umask` This is identical to Perl's builtin `umask()` function for setting (and querying) the file creation permission mask, see ["umask" in perlfunc](perlfunc#umask).
`uname` Get name of current operating system.
```
($sysname, $nodename, $release, $version, $machine)
= POSIX::uname();
```
Note that the actual meanings of the various fields are not that well standardized, do not expect any great portability. The `$sysname` might be the name of the operating system, the `$nodename` might be the name of the host, the `$release` might be the (major) release number of the operating system, the `$version` might be the (minor) release number of the operating system, and the `$machine` might be a hardware identifier. Maybe.
`ungetc` Not implemented. Use method `IO::Handle::ungetc()` instead.
`unlink` This is identical to Perl's builtin `unlink()` function for removing files, see ["unlink" in perlfunc](perlfunc#unlink).
`utime` This is identical to Perl's builtin `utime()` function for changing the time stamps of files and directories, see ["utime" in perlfunc](perlfunc#utime).
`vfprintf` Not implemented. `vfprintf()` is C-specific, see ["printf" in perlfunc](perlfunc#printf) instead.
`vprintf` Not implemented. `vprintf()` is C-specific, see ["printf" in perlfunc](perlfunc#printf) instead.
`vsprintf` Not implemented. `vsprintf()` is C-specific, see ["sprintf" in perlfunc](perlfunc#sprintf) instead.
`wait` This is identical to Perl's builtin `wait()` function, see ["wait" in perlfunc](perlfunc#wait).
`waitpid` Wait for a child process to change state. This is identical to Perl's builtin `waitpid()` function, see ["waitpid" in perlfunc](perlfunc#waitpid).
```
$pid = POSIX::waitpid( -1, POSIX::WNOHANG );
print "status = ", ($? / 256), "\n";
```
See ["mblen"](#mblen).
`wctomb` This is the same as the C function `wctomb()` on unthreaded perls. On threaded perls, it transparently (almost) substitutes the more thread-safe [`wcrtomb`(3)](wcrtomb(3)), if available, instead of `wctomb`.
Core Perl does not have any support for wide and multibyte locales, except Unicode UTF-8 locales. This function, in conjunction with ["mblen"](#mblen) and ["mbtowc"](#mbtowc) may be used to roll your own decoding/encoding of other types of multi-byte locales.
Use `undef` as the first parameter to this function to get the effect of passing NULL as the first parameter to `wctomb`. This resets any shift state to its initial value. The return value is undefined if `wcrtomb` was substituted, so you should never rely on it.
When the first parameter is a scalar, the code point contained in the scalar second parameter is converted into a multi-byte string and stored into the first parameter scalar. This is based on the locale that currently underlies the program, regardless of whether or not the function is called from Perl code that is within the scope of `use locale`. The return value is the number of bytes stored; or negative if the code point isn't representable in the current locale. Perl makes no attempt at hiding from your code any differences in the `errno` setting between `wctomb` and `wcrtomb`. It does set `errno` to 0 before calling them.
`write` Write to a file. This uses file descriptors such as those obtained by calling `POSIX::open`.
```
$fd = POSIX::open( "foo", &POSIX::O_WRONLY );
$buf = "hello";
$bytes = POSIX::write( $fd, $buf, 5 );
```
Returns `undef` on failure.
See also ["syswrite" in perlfunc](perlfunc#syswrite).
CLASSES
-------
###
`POSIX::SigAction`
`new` Creates a new `POSIX::SigAction` object which corresponds to the C `struct sigaction`. This object will be destroyed automatically when it is no longer needed. The first parameter is the handler, a sub reference. The second parameter is a `POSIX::SigSet` object, it defaults to the empty set. The third parameter contains the `sa_flags`, it defaults to 0.
```
$sigset = POSIX::SigSet->new(SIGINT, SIGQUIT);
$sigaction = POSIX::SigAction->new(
\&handler, $sigset, &POSIX::SA_NOCLDSTOP
);
```
This `POSIX::SigAction` object is intended for use with the `POSIX::sigaction()` function.
`handler` `mask` `flags` accessor functions to get/set the values of a SigAction object.
```
$sigset = $sigaction->mask;
$sigaction->flags(&POSIX::SA_RESTART);
```
`safe` accessor function for the "safe signals" flag of a SigAction object; see <perlipc> for general information on safe (a.k.a. "deferred") signals. If you wish to handle a signal safely, use this accessor to set the "safe" flag in the `POSIX::SigAction` object:
```
$sigaction->safe(1);
```
You may also examine the "safe" flag on the output action object which is filled in when given as the third parameter to `POSIX::sigaction()`:
```
sigaction(SIGINT, $new_action, $old_action);
if ($old_action->safe) {
# previous SIGINT handler used safe signals
}
```
###
`POSIX::SigRt`
`%SIGRT`
A hash of the POSIX realtime signal handlers. It is an extension of the standard `%SIG`, the `$POSIX::SIGRT{SIGRTMIN}` is roughly equivalent to `$SIG{SIGRTMIN}`, but the right POSIX moves (see below) are made with the `POSIX::SigSet` and `POSIX::sigaction` instead of accessing the `%SIG`.
You can set the `%POSIX::SIGRT` elements to set the POSIX realtime signal handlers, use `delete` and `exists` on the elements, and use `scalar` on the `%POSIX::SIGRT` to find out how many POSIX realtime signals there are available `(SIGRTMAX - SIGRTMIN + 1`, the `SIGRTMAX` is a valid POSIX realtime signal).
Setting the `%SIGRT` elements is equivalent to calling this:
```
sub new {
my ($rtsig, $handler, $flags) = @_;
my $sigset = POSIX::SigSet($rtsig);
my $sigact = POSIX::SigAction->new($handler,$sigset,$flags);
sigaction($rtsig, $sigact);
}
```
The flags default to zero, if you want something different you can either use `local` on `$POSIX::SigRt::SIGACTION_FLAGS`, or you can derive from POSIX::SigRt and define your own `new()` (the tied hash STORE method of the `%SIGRT` calls `new($rtsig, $handler, $SIGACTION_FLAGS)`, where the `$rtsig` ranges from zero to `SIGRTMAX - SIGRTMIN + 1)`.
Just as with any signal, you can use `sigaction($rtsig, undef, $oa)` to retrieve the installed signal handler (or, rather, the signal action).
**NOTE:** whether POSIX realtime signals really work in your system, or whether Perl has been compiled so that it works with them, is outside of this discussion.
`SIGRTMIN` Return the minimum POSIX realtime signal number available, or `undef` if no POSIX realtime signals are available.
`SIGRTMAX` Return the maximum POSIX realtime signal number available, or `undef` if no POSIX realtime signals are available.
###
`POSIX::SigSet`
`new` Create a new SigSet object. This object will be destroyed automatically when it is no longer needed. Arguments may be supplied to initialize the set.
Create an empty set.
```
$sigset = POSIX::SigSet->new;
```
Create a set with `SIGUSR1`.
```
$sigset = POSIX::SigSet->new( &POSIX::SIGUSR1 );
```
Throws an error if any of the signals supplied cannot be added to the set.
`addset` Add a signal to a SigSet object.
```
$sigset->addset( &POSIX::SIGUSR2 );
```
Returns `undef` on failure.
`delset` Remove a signal from the SigSet object.
```
$sigset->delset( &POSIX::SIGUSR2 );
```
Returns `undef` on failure.
`emptyset` Initialize the SigSet object to be empty.
```
$sigset->emptyset();
```
Returns `undef` on failure.
`fillset` Initialize the SigSet object to include all signals.
```
$sigset->fillset();
```
Returns `undef` on failure.
`ismember` Tests the SigSet object to see if it contains a specific signal.
```
if( $sigset->ismember( &POSIX::SIGUSR1 ) ){
print "contains SIGUSR1\n";
}
```
###
`POSIX::Termios`
`new` Create a new Termios object. This object will be destroyed automatically when it is no longer needed. A Termios object corresponds to the `termios` C struct. `new()` mallocs a new one, `getattr()` fills it from a file descriptor, and `setattr()` sets a file descriptor's parameters to match Termios' contents.
```
$termios = POSIX::Termios->new;
```
`getattr` Get terminal control attributes.
Obtain the attributes for `stdin`.
```
$termios->getattr( 0 ) # Recommended for clarity.
$termios->getattr()
```
Obtain the attributes for stdout.
```
$termios->getattr( 1 )
```
Returns `undef` on failure.
`getcc` Retrieve a value from the `c_cc` field of a `termios` object. The `c_cc` field is an array so an index must be specified.
```
$c_cc[1] = $termios->getcc(1);
```
`getcflag` Retrieve the `c_cflag` field of a `termios` object.
```
$c_cflag = $termios->getcflag;
```
`getiflag` Retrieve the `c_iflag` field of a `termios` object.
```
$c_iflag = $termios->getiflag;
```
`getispeed` Retrieve the input baud rate.
```
$ispeed = $termios->getispeed;
```
`getlflag` Retrieve the `c_lflag` field of a `termios` object.
```
$c_lflag = $termios->getlflag;
```
`getoflag` Retrieve the `c_oflag` field of a `termios` object.
```
$c_oflag = $termios->getoflag;
```
`getospeed` Retrieve the output baud rate.
```
$ospeed = $termios->getospeed;
```
`setattr` Set terminal control attributes.
Set attributes immediately for stdout.
```
$termios->setattr( 1, &POSIX::TCSANOW );
```
Returns `undef` on failure.
`setcc` Set a value in the `c_cc` field of a `termios` object. The `c_cc` field is an array so an index must be specified.
```
$termios->setcc( &POSIX::VEOF, 1 );
```
`setcflag` Set the `c_cflag` field of a `termios` object.
```
$termios->setcflag( $c_cflag | &POSIX::CLOCAL );
```
`setiflag` Set the `c_iflag` field of a `termios` object.
```
$termios->setiflag( $c_iflag | &POSIX::BRKINT );
```
`setispeed` Set the input baud rate.
```
$termios->setispeed( &POSIX::B9600 );
```
Returns `undef` on failure.
`setlflag` Set the `c_lflag` field of a `termios` object.
```
$termios->setlflag( $c_lflag | &POSIX::ECHO );
```
`setoflag` Set the `c_oflag` field of a `termios` object.
```
$termios->setoflag( $c_oflag | &POSIX::OPOST );
```
`setospeed` Set the output baud rate.
```
$termios->setospeed( &POSIX::B9600 );
```
Returns `undef` on failure.
Baud rate values `B38400` `B75` `B200` `B134` `B300` `B1800` `B150` `B0` `B19200` `B1200` `B9600` `B600` `B4800` `B50` `B2400` `B110`
Terminal interface values `TCSADRAIN` `TCSANOW` `TCOON` `TCIOFLUSH` `TCOFLUSH` `TCION` `TCIFLUSH` `TCSAFLUSH` `TCIOFF` `TCOOFF`
`c_cc` field values `VEOF` `VEOL` `VERASE` `VINTR` `VKILL` `VQUIT` `VSUSP` `VSTART` `VSTOP` `VMIN` `VTIME` `NCCS`
`c_cflag` field values `CLOCAL` `CREAD` `CSIZE` `CS5` `CS6` `CS7` `CS8` `CSTOPB` `HUPCL` `PARENB` `PARODD`
`c_iflag` field values `BRKINT` `ICRNL` `IGNBRK` `IGNCR` `IGNPAR` `INLCR` `INPCK` `ISTRIP` `IXOFF` `IXON` `PARMRK`
`c_lflag` field values `ECHO` `ECHOE` `ECHOK` `ECHONL` `ICANON` `IEXTEN` `ISIG` `NOFLSH` `TOSTOP`
`c_oflag` field values `OPOST`
PATHNAME CONSTANTS
-------------------
Constants `_PC_CHOWN_RESTRICTED` `_PC_LINK_MAX` `_PC_MAX_CANON` `_PC_MAX_INPUT` `_PC_NAME_MAX` `_PC_NO_TRUNC` `_PC_PATH_MAX` `_PC_PIPE_BUF` `_PC_VDISABLE`
POSIX CONSTANTS
----------------
Constants `_POSIX_ARG_MAX` `_POSIX_CHILD_MAX` `_POSIX_CHOWN_RESTRICTED` `_POSIX_JOB_CONTROL` `_POSIX_LINK_MAX` `_POSIX_MAX_CANON` `_POSIX_MAX_INPUT` `_POSIX_NAME_MAX` `_POSIX_NGROUPS_MAX` `_POSIX_NO_TRUNC` `_POSIX_OPEN_MAX` `_POSIX_PATH_MAX` `_POSIX_PIPE_BUF` `_POSIX_SAVED_IDS` `_POSIX_SSIZE_MAX` `_POSIX_STREAM_MAX` `_POSIX_TZNAME_MAX` `_POSIX_VDISABLE` `_POSIX_VERSION`
RESOURCE CONSTANTS
-------------------
Imported with the `:sys_resource_h` tag.
Constants Added in Perl v5.28:
`PRIO_PROCESS` `PRIO_PGRP` `PRIO_USER`
SYSTEM CONFIGURATION
---------------------
Constants `_SC_ARG_MAX` `_SC_CHILD_MAX` `_SC_CLK_TCK` `_SC_JOB_CONTROL` `_SC_NGROUPS_MAX` `_SC_OPEN_MAX` `_SC_PAGESIZE` `_SC_SAVED_IDS` `_SC_STREAM_MAX` `_SC_TZNAME_MAX` `_SC_VERSION`
ERRNO
-----
Constants `E2BIG` `EACCES` `EADDRINUSE` `EADDRNOTAVAIL` `EAFNOSUPPORT` `EAGAIN` `EALREADY` `EBADF` `EBADMSG` `EBUSY` `ECANCELED` `ECHILD` `ECONNABORTED` `ECONNREFUSED` `ECONNRESET` `EDEADLK` `EDESTADDRREQ` `EDOM` `EDQUOT` `EEXIST` `EFAULT` `EFBIG` `EHOSTDOWN` `EHOSTUNREACH` `EIDRM` `EILSEQ` `EINPROGRESS` `EINTR` `EINVAL` `EIO` `EISCONN` `EISDIR` `ELOOP` `EMFILE` `EMLINK` `EMSGSIZE` `ENAMETOOLONG` `ENETDOWN` `ENETRESET` `ENETUNREACH` `ENFILE` `ENOBUFS` `ENODATA` `ENODEV` `ENOENT` `ENOEXEC` `ENOLCK` `ENOLINK` `ENOMEM` `ENOMSG` `ENOPROTOOPT` `ENOSPC` `ENOSR` `ENOSTR` `ENOSYS` `ENOTBLK` `ENOTCONN` `ENOTDIR` `ENOTEMPTY` `ENOTRECOVERABLE` `ENOTSOCK` `ENOTSUP` `ENOTTY` `ENXIO` `EOPNOTSUPP` `EOTHER` `EOVERFLOW` `EOWNERDEAD` `EPERM` `EPFNOSUPPORT` `EPIPE` `EPROCLIM` `EPROTO` `EPROTONOSUPPORT` `EPROTOTYPE` `ERANGE` `EREMOTE` `ERESTART` `EROFS` `ESHUTDOWN` `ESOCKTNOSUPPORT` `ESPIPE` `ESRCH` `ESTALE` `ETIME` `ETIMEDOUT` `ETOOMANYREFS` `ETXTBSY` `EUSERS` `EWOULDBLOCK` `EXDEV`
FCNTL
-----
Constants `FD_CLOEXEC` `F_DUPFD` `F_GETFD` `F_GETFL` `F_GETLK` `F_OK` `F_RDLCK` `F_SETFD` `F_SETFL` `F_SETLK` `F_SETLKW` `F_UNLCK` `F_WRLCK` `O_ACCMODE` `O_APPEND` `O_CREAT` `O_EXCL` `O_NOCTTY` `O_NONBLOCK` `O_RDONLY` `O_RDWR` `O_TRUNC` `O_WRONLY`
FLOAT
-----
Constants `DBL_DIG` `DBL_EPSILON` `DBL_MANT_DIG` `DBL_MAX` `DBL_MAX_10_EXP` `DBL_MAX_EXP` `DBL_MIN` `DBL_MIN_10_EXP` `DBL_MIN_EXP` `FLT_DIG` `FLT_EPSILON` `FLT_MANT_DIG` `FLT_MAX` `FLT_MAX_10_EXP` `FLT_MAX_EXP` `FLT_MIN` `FLT_MIN_10_EXP` `FLT_MIN_EXP` `FLT_RADIX` `FLT_ROUNDS` `LDBL_DIG` `LDBL_EPSILON` `LDBL_MANT_DIG` `LDBL_MAX` `LDBL_MAX_10_EXP` `LDBL_MAX_EXP` `LDBL_MIN` `LDBL_MIN_10_EXP` `LDBL_MIN_EXP`
FLOATING-POINT ENVIRONMENT
---------------------------
Constants `FE_DOWNWARD` `FE_TONEAREST` `FE_TOWARDZERO` `FE_UPWARD` on systems that support them.
LIMITS
------
Constants `ARG_MAX` `CHAR_BIT` `CHAR_MAX` `CHAR_MIN` `CHILD_MAX` `INT_MAX` `INT_MIN` `LINK_MAX` `LONG_MAX` `LONG_MIN` `MAX_CANON` `MAX_INPUT` `MB_LEN_MAX` `NAME_MAX` `NGROUPS_MAX` `OPEN_MAX` `PATH_MAX` `PIPE_BUF` `SCHAR_MAX` `SCHAR_MIN` `SHRT_MAX` `SHRT_MIN` `SSIZE_MAX` `STREAM_MAX` `TZNAME_MAX` `UCHAR_MAX` `UINT_MAX` `ULONG_MAX` `USHRT_MAX`
LOCALE
------
Constants `LC_ALL` `LC_COLLATE` `LC_CTYPE` `LC_MONETARY` `LC_NUMERIC` `LC_TIME` `LC_MESSAGES` on systems that support them.
MATH
----
Constants `HUGE_VAL`
Added in Perl v5.22:
`FP_ILOGB0` `FP_ILOGBNAN` `FP_INFINITE` `FP_NAN` `FP_NORMAL` `FP_SUBNORMAL` `FP_ZERO` `INFINITY` `NAN` `Inf` `NaN` `M_1_PI` `M_2_PI` `M_2_SQRTPI` `M_E` `M_LN10` `M_LN2` `M_LOG10E` `M_LOG2E` `M_PI` `M_PI_2` `M_PI_4` `M_SQRT1_2` `M_SQRT2` on systems with C99 support.
SIGNAL
------
Constants `SA_NOCLDSTOP` `SA_NOCLDWAIT` `SA_NODEFER` `SA_ONSTACK` `SA_RESETHAND` `SA_RESTART` `SA_SIGINFO` `SIGABRT` `SIGALRM` `SIGCHLD` `SIGCONT` `SIGFPE` `SIGHUP` `SIGILL` `SIGINT` `SIGKILL` `SIGPIPE` `SIGQUIT` `SIGSEGV` `SIGSTOP` `SIGTERM` `SIGTSTP` `SIGTTIN` `SIGTTOU` `SIGUSR1` `SIGUSR2` `SIG_BLOCK` `SIG_DFL` `SIG_ERR` `SIG_IGN` `SIG_SETMASK` `SIG_UNBLOCK`
Added in Perl v5.24:
`ILL_ILLOPC` `ILL_ILLOPN` `ILL_ILLADR` `ILL_ILLTRP` `ILL_PRVOPC` `ILL_PRVREG` `ILL_COPROC` `ILL_BADSTK` `FPE_INTDIV` `FPE_INTOVF` `FPE_FLTDIV` `FPE_FLTOVF` `FPE_FLTUND` `FPE_FLTRES` `FPE_FLTINV` `FPE_FLTSUB` `SEGV_MAPERR` `SEGV_ACCERR` `BUS_ADRALN` `BUS_ADRERR` `BUS_OBJERR` `TRAP_BRKPT` `TRAP_TRACE` `CLD_EXITED` `CLD_KILLED` `CLD_DUMPED` `CLD_TRAPPED` `CLD_STOPPED` `CLD_CONTINUED` `POLL_IN` `POLL_OUT` `POLL_MSG` `POLL_ERR` `POLL_PRI` `POLL_HUP` `SI_USER` `SI_QUEUE` `SI_TIMER` `SI_ASYNCIO` `SI_MESGQ`
STAT
----
Constants `S_IRGRP` `S_IROTH` `S_IRUSR` `S_IRWXG` `S_IRWXO` `S_IRWXU` `S_ISGID` `S_ISUID` `S_IWGRP` `S_IWOTH` `S_IWUSR` `S_IXGRP` `S_IXOTH` `S_IXUSR`
Macros `S_ISBLK` `S_ISCHR` `S_ISDIR` `S_ISFIFO` `S_ISREG`
STDLIB
------
Constants `EXIT_FAILURE` `EXIT_SUCCESS` `MB_CUR_MAX` `RAND_MAX`
STDIO
-----
Constants `BUFSIZ` `EOF` `FILENAME_MAX` `L_ctermid` `L_cuserid` `TMP_MAX`
TIME
----
Constants `CLK_TCK` `CLOCKS_PER_SEC`
UNISTD
------
Constants `R_OK` `SEEK_CUR` `SEEK_END` `SEEK_SET` `STDIN_FILENO` `STDOUT_FILENO` `STDERR_FILENO` `W_OK` `X_OK`
WAIT
----
Constants `WNOHANG` `WUNTRACED`
`WNOHANG` Do not suspend the calling process until a child process changes state but instead return immediately.
`WUNTRACED` Catch stopped child processes.
Macros `WIFEXITED` `WEXITSTATUS` `WIFSIGNALED` `WTERMSIG` `WIFSTOPPED` `WSTOPSIG`
`WIFEXITED` `WIFEXITED(${^CHILD_ERROR_NATIVE})` returns true if the child process exited normally (`exit()` or by falling off the end of `main()`)
`WEXITSTATUS` `WEXITSTATUS(${^CHILD_ERROR_NATIVE})` returns the normal exit status of the child process (only meaningful if `WIFEXITED(${^CHILD_ERROR_NATIVE})` is true)
`WIFSIGNALED` `WIFSIGNALED(${^CHILD_ERROR_NATIVE})` returns true if the child process terminated because of a signal
`WTERMSIG` `WTERMSIG(${^CHILD_ERROR_NATIVE})` returns the signal the child process terminated for (only meaningful if `WIFSIGNALED(${^CHILD_ERROR_NATIVE})` is true)
`WIFSTOPPED` `WIFSTOPPED(${^CHILD_ERROR_NATIVE})` returns true if the child process is currently stopped (can happen only if you specified the WUNTRACED flag to `waitpid()`)
`WSTOPSIG` `WSTOPSIG(${^CHILD_ERROR_NATIVE})` returns the signal the child process was stopped for (only meaningful if `WIFSTOPPED(${^CHILD_ERROR_NATIVE})` is true)
WINSOCK
-------
(Windows only.)
Constants Added in Perl v5.24:
`WSAEINTR` `WSAEBADF` `WSAEACCES` `WSAEFAULT` `WSAEINVAL` `WSAEMFILE` `WSAEWOULDBLOCK` `WSAEINPROGRESS` `WSAEALREADY` `WSAENOTSOCK` `WSAEDESTADDRREQ` `WSAEMSGSIZE` `WSAEPROTOTYPE` `WSAENOPROTOOPT` `WSAEPROTONOSUPPORT` `WSAESOCKTNOSUPPORT` `WSAEOPNOTSUPP` `WSAEPFNOSUPPORT` `WSAEAFNOSUPPORT` `WSAEADDRINUSE` `WSAEADDRNOTAVAIL` `WSAENETDOWN` `WSAENETUNREACH` `WSAENETRESET` `WSAECONNABORTED` `WSAECONNRESET` `WSAENOBUFS` `WSAEISCONN` `WSAENOTCONN` `WSAESHUTDOWN` `WSAETOOMANYREFS` `WSAETIMEDOUT` `WSAECONNREFUSED` `WSAELOOP` `WSAENAMETOOLONG` `WSAEHOSTDOWN` `WSAEHOSTUNREACH` `WSAENOTEMPTY` `WSAEPROCLIM` `WSAEUSERS` `WSAEDQUOT` `WSAESTALE` `WSAEREMOTE` `WSAEDISCON` `WSAENOMORE` `WSAECANCELLED` `WSAEINVALIDPROCTABLE` `WSAEINVALIDPROVIDER` `WSAEPROVIDERFAILEDINIT` `WSAEREFUSED`
| programming_docs |
perl Pod::Html::Util Pod::Html::Util
===============
CONTENTS
--------
* [NAME](#NAME)
* [SUBROUTINES](#SUBROUTINES)
+ [process\_command\_line()](#process_command_line())
+ [usage()](#usage())
+ [unixify()](#unixify())
+ [relativize\_url()](#relativize_url())
+ [html\_escape()](#html_escape())
+ [htmlify()](#htmlify())
+ [anchorify()](#anchorify())
+ [trim\_leading\_whitespace()](#trim_leading_whitespace())
NAME
----
Pod::Html::Util - helper functions for Pod-Html
SUBROUTINES
-----------
**Note:** While these functions are importable on request from *Pod::Html::Util*, they are specifically intended for use within (a) the *Pod-Html* distribution (modules and test programs) shipped as part of the Perl 5 core and (b) other parts of the core such as the *installhtml* program. These functions may be modified or relocated within the core distribution -- or removed entirely therefrom -- as the core's needs evolve. Hence, you should not rely on these functions in situations other than those just described.
###
`process_command_line()`
Process command-line switches (options). Returns a reference to a hash. Will provide usage message if `--help` switch is present or if parameters are invalid.
Calling this subroutine may modify `@ARGV`.
###
`usage()`
Display customary Pod::Html usage information on STDERR.
###
`unixify()`
Ensure that *Pod::Html*'s internals and tests handle paths consistently across Unix, Windows and VMS.
###
`relativize_url()`
Convert an absolute URL to one relative to a base URL. Assumes both end in a filename.
###
`html_escape()`
Make text safe for HTML.
###
`htmlify()`
```
htmlify($heading);
```
Converts a pod section specification to a suitable section specification for HTML. Note that we keep spaces and special characters except `", ?` (Netscape problem) and the hyphen (writer's problem...).
###
`anchorify()`
```
anchorify(@heading);
```
Similar to `htmlify()`, but turns non-alphanumerics into underscores. Note that `anchorify()` is not exported by default.
###
`trim_leading_whitespace()`
Remove any level of indentation (spaces or tabs) from each code block consistently. Adapted from: https://metacpan.org/source/HAARG/MetaCPAN-Pod-XHTML-0.002001/lib/Pod/Simple/Role/StripVerbatimIndent.pm
perl Pod::Perldoc::ToChecker Pod::Perldoc::ToChecker
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToChecker - let Perldoc check Pod for errors
SYNOPSIS
--------
```
% perldoc -o checker SomeFile.pod
No Pod errors in SomeFile.pod
(or an error report)
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Simple::Checker as a "formatter" class (or if that is not available, then Pod::Checker), to check for errors in a given Pod file.
This is actually a Pod::Simple::Checker (or Pod::Checker) subclass, and inherits all its options.
SEE ALSO
---------
<Pod::Simple::Checker>, <Pod::Simple>, <Pod::Checker>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl TAP::Formatter::Color TAP::Formatter::Color
=====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [can\_color](#can_color)
- [set\_color](#set_color)
NAME
----
TAP::Formatter::Color - Run Perl test scripts with color
VERSION
-------
Version 3.44
DESCRIPTION
-----------
Note that this harness is *experimental*. You may not like the colors I've chosen and I haven't yet provided an easy way to override them.
This test harness is the same as <TAP::Harness>, but test results are output in color. Passing tests are printed in green. Failing tests are in red. Skipped tests are blue on a white background and TODO tests are printed in white.
If <Term::ANSIColor> cannot be found (and <Win32::Console::ANSI> if running under Windows) tests will be run without color.
SYNOPSIS
--------
```
use TAP::Formatter::Color;
my $harness = TAP::Formatter::Color->new( \%args );
$harness->runtests(@tests);
```
METHODS
-------
###
Class Methods
#### `new`
The constructor returns a new `TAP::Formatter::Color` object. If <Term::ANSIColor> is not installed, returns undef.
#### `can_color`
```
Test::Formatter::Color->can_color()
```
Returns a boolean indicating whether or not this module can actually generate colored output. This will be false if it could not load the modules needed for the current platform.
#### `set_color`
Set the output color.
perl Module::Load Module::Load
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Difference between load and autoload](#Difference-between-load-and-autoload)
* [FUNCTIONS](#FUNCTIONS)
* [Rules](#Rules)
* [IMPORTS THE FUNCTIONS](#IMPORTS-THE-FUNCTIONS)
* [Caveats](#Caveats)
* [SEE ALSO](#SEE-ALSO)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [BUG REPORTS](#BUG-REPORTS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Module::Load - runtime require of both modules and files
SYNOPSIS
--------
```
use Module::Load;
my $module = 'Data::Dumper';
load Data::Dumper; # loads that module, but not import any functions
# -> cannot use 'Dumper' function
load 'Data::Dumper'; # ditto
load $module # tritto
autoload Data::Dumper; # loads that module and imports the default functions
# -> can use 'Dumper' function
my $script = 'some/script.pl'
load $script;
load 'some/script.pl'; # use quotes because of punctuations
load thing; # try 'thing' first, then 'thing.pm'
load CGI, ':all'; # like 'use CGI qw[:standard]'
```
DESCRIPTION
-----------
`Module::Load` eliminates the need to know whether you are trying to require either a file or a module.
If you consult `perldoc -f require` you will see that `require` will behave differently when given a bareword or a string.
In the case of a string, `require` assumes you are wanting to load a file. But in the case of a bareword, it assumes you mean a module.
This gives nasty overhead when you are trying to dynamically require modules at runtime, since you will need to change the module notation (`Acme::Comment`) to a file notation fitting the particular platform you are on.
`Module::Load` eliminates the need for this overhead and will just DWYM.
###
Difference between `load` and `autoload`
`Module::Load` imports the two functions - `load` and `autoload`
`autoload` imports the default functions automatically, but `load` do not import any functions.
`autoload` is usable under `BEGIN{};`.
Both the functions can import the functions that are specified.
Following codes are same.
```
load File::Spec::Functions, qw/splitpath/;
autoload File::Spec::Functions, qw/splitpath/;
```
FUNCTIONS
---------
load Loads a specified module.
See ["Rules"](#Rules) for detailed loading rule.
autoload Loads a specified module and imports the default functions.
Except importing the functions, 'autoload' is same as 'load'.
load\_remote Loads a specified module to the specified package.
```
use Module::Load 'load_remote';
my $pkg = 'Other::Package';
load_remote $pkg, 'Data::Dumper'; # load a module to 'Other::Package'
# but do not import 'Dumper' function
```
A module for loading must be quoted.
Except specifing the package and quoting module name, 'load\_remote' is same as 'load'.
autoload\_remote Loads a specified module and imports the default functions to the specified package.
```
use Module::Load 'autoload_remote';
my $pkg = 'Other::Package';
autoload_remote $pkg, 'Data::Dumper'; # load a module to 'Other::Package'
# and imports 'Dumper' function
```
A module for loading must be quoted.
Except specifing the package and quoting module name, 'autoload\_remote' is same as 'load\_remote'.
Rules
-----
All functions have the following rules to decide what it thinks you want:
* If the argument has any characters in it other than those matching `\w`, `:` or `'`, it must be a file
* If the argument matches only `[\w:']`, it must be a module
* If the argument matches only `\w`, it could either be a module or a file. We will try to find `file.pm` first in `@INC` and if that fails, we will try to find `file` in @INC. If both fail, we die with the respective error messages.
IMPORTS THE FUNCTIONS
----------------------
'load' and 'autoload' are imported by default, but 'load\_remote' and 'autoload\_remote' are not imported.
To use 'load\_remote' or 'autoload\_remote', specify at 'use'.
"load","autoload","load\_remote","autoload\_remote" Imports the selected functions.
```
# imports 'load' and 'autoload' (default)
use Module::Load;
# imports 'autoload' only
use Module::Load 'autoload';
# imports 'autoload' and 'autoload_remote', but don't import 'load';
use Module::Load qw/autoload autoload_remote/;
```
'all' Imports all the functions.
```
use Module::Load 'all'; # imports load, autoload, load_remote, autoload_remote
```
'','none',undef Not import any functions (`load` and `autoload` are not imported).
```
use Module::Load '';
use Module::Load 'none';
use Module::Load undef;
```
Caveats
-------
Because of a bug in perl (#19213), at least in version 5.6.1, we have to hardcode the path separator for a require on Win32 to be `/`, like on Unix rather than the Win32 `\`. Otherwise perl will not read its own %INC accurately double load files if they are required again, or in the worst case, core dump.
`Module::Load` cannot do implicit imports, only explicit imports. (in other words, you always have to specify explicitly what you wish to import from a module, even if the functions are in that modules' `@EXPORT`)
SEE ALSO
---------
<Module::Runtime> provides functions for loading modules, checking the validity of a module name, converting a module name to partial `.pm` path, and related utility functions.
["require" in perlfunc](https://metacpan.org/pod/perlfunc#require) and ["use" in perlfunc](https://metacpan.org/pod/perlfunc#use).
<Mojo::Loader> is a "class loader and plugin framework", and is included in the [Mojolicious](https://metacpan.org/release/Mojolicious) distribution.
<Module::Loader> is a module for finding and loading modules in a given namespace, inspired by `Mojo::Loader`.
ACKNOWLEDGEMENTS
----------------
Thanks to Jonas B. Nielsen for making explicit imports work.
BUG REPORTS
------------
Please report bugs or other issues to <[email protected]>.
AUTHOR
------
This module by Jos Boumans <[email protected]>.
COPYRIGHT
---------
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
perl perlobj perlobj
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [An Object is Simply a Data Structure](#An-Object-is-Simply-a-Data-Structure)
- [Objects Are Blessed; Variables Are Not](#Objects-Are-Blessed;-Variables-Are-Not)
+ [A Class is Simply a Package](#A-Class-is-Simply-a-Package)
+ [A Method is Simply a Subroutine](#A-Method-is-Simply-a-Subroutine)
+ [Method Invocation](#Method-Invocation)
+ [Inheritance](#Inheritance)
- [How SUPER is Resolved](#How-SUPER-is-Resolved)
- [Multiple Inheritance](#Multiple-Inheritance)
- [Method Resolution Order](#Method-Resolution-Order)
- [Method Resolution Caching](#Method-Resolution-Caching)
+ [Writing Constructors](#Writing-Constructors)
+ [Attributes](#Attributes)
- [Writing Accessors](#Writing-Accessors)
+ [An Aside About Smarter and Safer Code](#An-Aside-About-Smarter-and-Safer-Code)
+ [Method Call Variations](#Method-Call-Variations)
- [Method Names with a Fully Qualified Name](#Method-Names-with-a-Fully-Qualified-Name)
- [Method Names as Strings](#Method-Names-as-Strings)
- [Class Names as Strings](#Class-Names-as-Strings)
- [Subroutine References as Methods](#Subroutine-References-as-Methods)
- [Dereferencing Method Call](#Dereferencing-Method-Call)
- [Method Calls on Filehandles](#Method-Calls-on-Filehandles)
+ [Invoking Class Methods](#Invoking-Class-Methods)
- [Indirect Object Syntax](#Indirect-Object-Syntax)
+ [bless, blessed, and ref](#bless,-blessed,-and-ref)
+ [The UNIVERSAL Class](#The-UNIVERSAL-Class)
+ [AUTOLOAD](#AUTOLOAD)
+ [Destructors](#Destructors)
- [Global Destruction](#Global-Destruction)
+ [Non-Hash Objects](#Non-Hash-Objects)
+ [Inside-Out objects](#Inside-Out-objects)
+ [Pseudo-hashes](#Pseudo-hashes)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlobj - Perl object reference
DESCRIPTION
-----------
This document provides a reference for Perl's object orientation features. If you're looking for an introduction to object-oriented programming in Perl, please see <perlootut>.
In order to understand Perl objects, you first need to understand references in Perl. See <perlreftut> for details.
This document describes all of Perl's object-oriented (OO) features from the ground up. If you're just looking to write some object-oriented code of your own, you are probably better served by using one of the object systems from CPAN described in <perlootut>.
If you're looking to write your own object system, or you need to maintain code which implements objects from scratch then this document will help you understand exactly how Perl does object orientation.
There are a few basic principles which define object oriented Perl:
1. An object is simply a data structure that knows to which class it belongs.
2. A class is simply a package. A class provides methods that expect to operate on objects.
3. A method is simply a subroutine that expects a reference to an object (or a package name, for class methods) as the first argument.
Let's look at each of these principles in depth.
###
An Object is Simply a Data Structure
Unlike many other languages which support object orientation, Perl does not provide any special syntax for constructing an object. Objects are merely Perl data structures (hashes, arrays, scalars, filehandles, etc.) that have been explicitly associated with a particular class.
That explicit association is created by the built-in `bless` function, which is typically used within the *constructor* subroutine of the class.
Here is a simple constructor:
```
package File;
sub new {
my $class = shift;
return bless {}, $class;
}
```
The name `new` isn't special. We could name our constructor something else:
```
package File;
sub load {
my $class = shift;
return bless {}, $class;
}
```
The modern convention for OO modules is to always use `new` as the name for the constructor, but there is no requirement to do so. Any subroutine that blesses a data structure into a class is a valid constructor in Perl.
In the previous examples, the `{}` code creates a reference to an empty anonymous hash. The `bless` function then takes that reference and associates the hash with the class in `$class`. In the simplest case, the `$class` variable will end up containing the string "File".
We can also use a variable to store a reference to the data structure that is being blessed as our object:
```
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
```
Once we've blessed the hash referred to by `$self` we can start calling methods on it. This is useful if you want to put object initialization in its own separate method:
```
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->_initialize();
return $self;
}
```
Since the object is also a hash, you can treat it as one, using it to store data associated with the object. Typically, code inside the class can treat the hash as an accessible data structure, while code outside the class should always treat the object as opaque. This is called **encapsulation**. Encapsulation means that the user of an object does not have to know how it is implemented. The user simply calls documented methods on the object.
Note, however, that (unlike most other OO languages) Perl does not ensure or enforce encapsulation in any way. If you want objects to actually *be* opaque you need to arrange for that yourself. This can be done in a variety of ways, including using ["Inside-Out objects"](#Inside-Out-objects) or modules from CPAN.
####
Objects Are Blessed; Variables Are Not
When we bless something, we are not blessing the variable which contains a reference to that thing, nor are we blessing the reference that the variable stores; we are blessing the thing that the variable refers to (sometimes known as the *referent*). This is best demonstrated with this code:
```
use Scalar::Util 'blessed';
my $foo = {};
my $bar = $foo;
bless $foo, 'Class';
print blessed( $bar ) // 'not blessed'; # prints "Class"
$bar = "some other value";
print blessed( $bar ) // 'not blessed'; # prints "not blessed"
```
When we call `bless` on a variable, we are actually blessing the underlying data structure that the variable refers to. We are not blessing the reference itself, nor the variable that contains that reference. That's why the second call to `blessed( $bar )` returns false. At that point `$bar` is no longer storing a reference to an object.
You will sometimes see older books or documentation mention "blessing a reference" or describe an object as a "blessed reference", but this is incorrect. It isn't the reference that is blessed as an object; it's the thing the reference refers to (i.e. the referent).
###
A Class is Simply a Package
Perl does not provide any special syntax for class definitions. A package is simply a namespace containing variables and subroutines. The only difference is that in a class, the subroutines may expect a reference to an object or the name of a class as the first argument. This is purely a matter of convention, so a class may contain both methods and subroutines which *don't* operate on an object or class.
Each package contains a special array called `@ISA`. The `@ISA` array contains a list of that class's parent classes, if any. This array is examined when Perl does method resolution, which we will cover later.
Calling methods from a package means it must be loaded, of course, so you will often want to load a module and add it to `@ISA` at the same time. You can do so in a single step using the <parent> pragma. (In older code you may encounter the <base> pragma, which is nowadays discouraged except when you have to work with the equally discouraged <fields> pragma.)
However the parent classes are set, the package's `@ISA` variable will contain a list of those parents. This is simply a list of scalars, each of which is a string that corresponds to a package name.
All classes inherit from the [UNIVERSAL](universal) class implicitly. The [UNIVERSAL](universal) class is implemented by the Perl core, and provides several default methods, such as `isa()`, `can()`, and `VERSION()`. The `UNIVERSAL` class will *never* appear in a package's `@ISA` variable.
Perl *only* provides method inheritance as a built-in feature. Attribute inheritance is left up the class to implement. See the ["Writing Accessors"](#Writing-Accessors) section for details.
###
A Method is Simply a Subroutine
Perl does not provide any special syntax for defining a method. A method is simply a regular subroutine, and is declared with `sub`. What makes a method special is that it expects to receive either an object or a class name as its first argument.
Perl *does* provide special syntax for method invocation, the `->` operator. We will cover this in more detail later.
Most methods you write will expect to operate on objects:
```
sub save {
my $self = shift;
open my $fh, '>', $self->path() or die $!;
print {$fh} $self->data() or die $!;
close $fh or die $!;
}
```
###
Method Invocation
Calling a method on an object is written as `$object->method`.
The left hand side of the method invocation (or arrow) operator is the object (or class name), and the right hand side is the method name.
```
my $pod = File->new( 'perlobj.pod', $data );
$pod->save();
```
The `->` syntax is also used when dereferencing a reference. It looks like the same operator, but these are two different operations.
When you call a method, the thing on the left side of the arrow is passed as the first argument to the method. That means when we call `Critter->new()`, the `new()` method receives the string `"Critter"` as its first argument. When we call `$fred->speak()`, the `$fred` variable is passed as the first argument to `speak()`.
Just as with any Perl subroutine, all of the arguments passed in `@_` are aliases to the original argument. This includes the object itself. If you assign directly to `$_[0]` you will change the contents of the variable that holds the reference to the object. We recommend that you don't do this unless you know exactly what you're doing.
Perl knows what package the method is in by looking at the left side of the arrow. If the left hand side is a package name, it looks for the method in that package. If the left hand side is an object, then Perl looks for the method in the package that the object has been blessed into.
If the left hand side is neither a package name nor an object, then the method call will cause an error, but see the section on ["Method Call Variations"](#Method-Call-Variations) for more nuances.
### Inheritance
We already talked about the special `@ISA` array and the <parent> pragma.
When a class inherits from another class, any methods defined in the parent class are available to the child class. If you attempt to call a method on an object that isn't defined in its own class, Perl will also look for that method in any parent classes it may have.
```
package File::MP3;
use parent 'File'; # sets @File::MP3::ISA = ('File');
my $mp3 = File::MP3->new( 'Andvari.mp3', $data );
$mp3->save();
```
Since we didn't define a `save()` method in the `File::MP3` class, Perl will look at the `File::MP3` class's parent classes to find the `save()` method. If Perl cannot find a `save()` method anywhere in the inheritance hierarchy, it will die.
In this case, it finds a `save()` method in the `File` class. Note that the object passed to `save()` in this case is still a `File::MP3` object, even though the method is found in the `File` class.
We can override a parent's method in a child class. When we do so, we can still call the parent class's method with the `SUPER` pseudo-class.
```
sub save {
my $self = shift;
say 'Prepare to rock';
$self->SUPER::save();
}
```
The `SUPER` modifier can *only* be used for method calls. You can't use it for regular subroutine calls or class methods:
```
SUPER::save($thing); # FAIL: looks for save() sub in package SUPER
SUPER->save($thing); # FAIL: looks for save() method in class
# SUPER
$thing->SUPER::save(); # Okay: looks for save() method in parent
# classes
```
####
How SUPER is Resolved
The `SUPER` pseudo-class is resolved from the package where the call is made. It is *not* resolved based on the object's class. This is important, because it lets methods at different levels within a deep inheritance hierarchy each correctly call their respective parent methods.
```
package A;
sub new {
return bless {}, shift;
}
sub speak {
my $self = shift;
say 'A';
}
package B;
use parent -norequire, 'A';
sub speak {
my $self = shift;
$self->SUPER::speak();
say 'B';
}
package C;
use parent -norequire, 'B';
sub speak {
my $self = shift;
$self->SUPER::speak();
say 'C';
}
my $c = C->new();
$c->speak();
```
In this example, we will get the following output:
```
A
B
C
```
This demonstrates how `SUPER` is resolved. Even though the object is blessed into the `C` class, the `speak()` method in the `B` class can still call `SUPER::speak()` and expect it to correctly look in the parent class of `B` (i.e the class the method call is in), not in the parent class of `C` (i.e. the class the object belongs to).
There are rare cases where this package-based resolution can be a problem. If you copy a subroutine from one package to another, `SUPER` resolution will be done based on the original package.
####
Multiple Inheritance
Multiple inheritance often indicates a design problem, but Perl always gives you enough rope to hang yourself with if you ask for it.
To declare multiple parents, you simply need to pass multiple class names to `use parent`:
```
package MultiChild;
use parent 'Parent1', 'Parent2';
```
####
Method Resolution Order
Method resolution order only matters in the case of multiple inheritance. In the case of single inheritance, Perl simply looks up the inheritance chain to find a method:
```
Grandparent
|
Parent
|
Child
```
If we call a method on a `Child` object and that method is not defined in the `Child` class, Perl will look for that method in the `Parent` class and then, if necessary, in the `Grandparent` class.
If Perl cannot find the method in any of these classes, it will die with an error message.
When a class has multiple parents, the method lookup order becomes more complicated.
By default, Perl does a depth-first left-to-right search for a method. That means it starts with the first parent in the `@ISA` array, and then searches all of its parents, grandparents, etc. If it fails to find the method, it then goes to the next parent in the original class's `@ISA` array and searches from there.
```
SharedGreatGrandParent
/ \
PaternalGrandparent MaternalGrandparent
\ /
Father Mother
\ /
Child
```
So given the diagram above, Perl will search `Child`, `Father`, `PaternalGrandparent`, `SharedGreatGrandParent`, `Mother`, and finally `MaternalGrandparent`. This may be a problem because now we're looking in `SharedGreatGrandParent` *before* we've checked all its derived classes (i.e. before we tried `Mother` and `MaternalGrandparent`).
It is possible to ask for a different method resolution order with the <mro> pragma.
```
package Child;
use mro 'c3';
use parent 'Father', 'Mother';
```
This pragma lets you switch to the "C3" resolution order. In simple terms, "C3" order ensures that shared parent classes are never searched before child classes, so Perl will now search: `Child`, `Father`, `PaternalGrandparent`, `Mother` `MaternalGrandparent`, and finally `SharedGreatGrandParent`. Note however that this is not "breadth-first" searching: All the `Father` ancestors (except the common ancestor) are searched before any of the `Mother` ancestors are considered.
The C3 order also lets you call methods in sibling classes with the `next` pseudo-class. See the <mro> documentation for more details on this feature.
####
Method Resolution Caching
When Perl searches for a method, it caches the lookup so that future calls to the method do not need to search for it again. Changing a class's parent class or adding subroutines to a class will invalidate the cache for that class.
The <mro> pragma provides some functions for manipulating the method cache directly.
###
Writing Constructors
As we mentioned earlier, Perl provides no special constructor syntax. This means that a class must implement its own constructor. A constructor is simply a class method that returns a reference to a new object.
The constructor can also accept additional parameters that define the object. Let's write a real constructor for the `File` class we used earlier:
```
package File;
sub new {
my $class = shift;
my ( $path, $data ) = @_;
my $self = bless {
path => $path,
data => $data,
}, $class;
return $self;
}
```
As you can see, we've stored the path and file data in the object itself. Remember, under the hood, this object is still just a hash. Later, we'll write accessors to manipulate this data.
For our `File::MP3` class, we can check to make sure that the path we're given ends with ".mp3":
```
package File::MP3;
sub new {
my $class = shift;
my ( $path, $data ) = @_;
die "You cannot create a File::MP3 without an mp3 extension\n"
unless $path =~ /\.mp3\z/;
return $class->SUPER::new(@_);
}
```
This constructor lets its parent class do the actual object construction.
### Attributes
An attribute is a piece of data belonging to a particular object. Unlike most object-oriented languages, Perl provides no special syntax or support for declaring and manipulating attributes.
Attributes are often stored in the object itself. For example, if the object is an anonymous hash, we can store the attribute values in the hash using the attribute name as the key.
While it's possible to refer directly to these hash keys outside of the class, it's considered a best practice to wrap all access to the attribute with accessor methods.
This has several advantages. Accessors make it easier to change the implementation of an object later while still preserving the original API.
An accessor lets you add additional code around attribute access. For example, you could apply a default to an attribute that wasn't set in the constructor, or you could validate that a new value for the attribute is acceptable.
Finally, using accessors makes inheritance much simpler. Subclasses can use the accessors rather than having to know how a parent class is implemented internally.
####
Writing Accessors
As with constructors, Perl provides no special accessor declaration syntax, so classes must provide explicitly written accessor methods. There are two common types of accessors, read-only and read-write.
A simple read-only accessor simply gets the value of a single attribute:
```
sub path {
my $self = shift;
return $self->{path};
}
```
A read-write accessor will allow the caller to set the value as well as get it:
```
sub path {
my $self = shift;
if (@_) {
$self->{path} = shift;
}
return $self->{path};
}
```
###
An Aside About Smarter and Safer Code
Our constructor and accessors are not very smart. They don't check that a `$path` is defined, nor do they check that a `$path` is a valid filesystem path.
Doing these checks by hand can quickly become tedious. Writing a bunch of accessors by hand is also incredibly tedious. There are a lot of modules on CPAN that can help you write safer and more concise code, including the modules we recommend in <perlootut>.
###
Method Call Variations
Perl supports several other ways to call methods besides the `$object->method()` usage we've seen so far.
####
Method Names with a Fully Qualified Name
Perl allows you to call methods using their fully qualified name (the package and method name):
```
my $mp3 = File::MP3->new( 'Regin.mp3', $data );
$mp3->File::save();
```
When you call a fully qualified method name like `File::save`, the method resolution search for the `save` method starts in the `File` class, skipping any `save` method the `File::MP3` class may have defined. It still searches the `File` class's parents if necessary.
While this feature is most commonly used to explicitly call methods inherited from an ancestor class, there is no technical restriction that enforces this:
```
my $obj = Tree->new();
$obj->Dog::bark();
```
This calls the `bark` method from class `Dog` on an object of class `Tree`, even if the two classes are completely unrelated. Use this with great care.
The `SUPER` pseudo-class that was described earlier is *not* the same as calling a method with a fully-qualified name. See the earlier ["Inheritance"](#Inheritance) section for details.
####
Method Names as Strings
Perl lets you use a scalar variable containing a string as a method name:
```
my $file = File->new( $path, $data );
my $method = 'save';
$file->$method();
```
This works exactly like calling `$file->save()`. This can be very useful for writing dynamic code. For example, it allows you to pass a method name to be called as a parameter to another method.
####
Class Names as Strings
Perl also lets you use a scalar containing a string as a class name:
```
my $class = 'File';
my $file = $class->new( $path, $data );
```
Again, this allows for very dynamic code.
####
Subroutine References as Methods
You can also use a subroutine reference as a method:
```
my $sub = sub {
my $self = shift;
$self->save();
};
$file->$sub();
```
This is exactly equivalent to writing `$sub->($file)`. You may see this idiom in the wild combined with a call to `can`:
```
if ( my $meth = $object->can('foo') ) {
$object->$meth();
}
```
####
Dereferencing Method Call
Perl also lets you use a dereferenced scalar reference in a method call. That's a mouthful, so let's look at some code:
```
$file->${ \'save' };
$file->${ returns_scalar_ref() };
$file->${ \( returns_scalar() ) };
$file->${ returns_ref_to_sub_ref() };
```
This works if the dereference produces a string *or* a subroutine reference.
####
Method Calls on Filehandles
Under the hood, Perl filehandles are instances of the `IO::Handle` or `IO::File` class. Once you have an open filehandle, you can call methods on it. Additionally, you can call methods on the `STDIN`, `STDOUT`, and `STDERR` filehandles.
```
open my $fh, '>', 'path/to/file';
$fh->autoflush();
$fh->print('content');
STDOUT->autoflush();
```
###
Invoking Class Methods
Because Perl allows you to use barewords for package names and subroutine names, it sometimes interprets a bareword's meaning incorrectly. For example, the construct `Class->new()` can be interpreted as either `'Class'->new()` or `Class()->new()`. In English, that second interpretation reads as "call a subroutine named Class(), then call new() as a method on the return value of Class()". If there is a subroutine named `Class()` in the current namespace, Perl will always interpret `Class->new()` as the second alternative: a call to `new()` on the object returned by a call to `Class()`
You can force Perl to use the first interpretation (i.e. as a method call on the class named "Class") in two ways. First, you can append a `::` to the class name:
```
Class::->new()
```
Perl will always interpret this as a method call.
Alternatively, you can quote the class name:
```
'Class'->new()
```
Of course, if the class name is in a scalar Perl will do the right thing as well:
```
my $class = 'Class';
$class->new();
```
####
Indirect Object Syntax
**Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl interpreter. See below for more details.**
Perl supports another method invocation syntax called "indirect object" notation. This syntax is called "indirect" because the method comes before the object it is being invoked on.
This syntax can be used with any class or object method:
```
my $file = new File $path, $data;
save $file;
```
We recommend that you avoid this syntax, for several reasons.
First, it can be confusing to read. In the above example, it's not clear if `save` is a method provided by the `File` class or simply a subroutine that expects a file object as its first argument.
When used with class methods, the problem is even worse. Because Perl allows subroutine names to be written as barewords, Perl has to guess whether the bareword after the method is a class name or subroutine name. In other words, Perl can resolve the syntax as either `File->new( $path, $data )` **or** `new( File( $path, $data ) )`.
To parse this code, Perl uses a heuristic based on what package names it has seen, what subroutines exist in the current package, what barewords it has previously seen, and other input. Needless to say, heuristics can produce very surprising results!
Older documentation (and some CPAN modules) encouraged this syntax, particularly for constructors, so you may still find it in the wild. However, we encourage you to avoid using it in new code.
You can force Perl to interpret the bareword as a class name by appending "::" to it, like we saw earlier:
```
my $file = new File:: $path, $data;
```
Indirect object syntax is only available when the [`"indirect"`](feature#The-%27indirect%27-feature) named feature is enabled. This is enabled by default, but can be disabled if requested. This feature is present in older feature version bundles, but was removed from the `:5.36` bundle; so a [`use VERSION`](perlfunc#use-VERSION) declaration of `v5.36` or above will also disable the feature.
```
use v5.36;
# indirect object syntax is no longer available
```
###
`bless`, `blessed`, and `ref`
As we saw earlier, an object is simply a data structure that has been blessed into a class via the `bless` function. The `bless` function can take either one or two arguments:
```
my $object = bless {}, $class;
my $object = bless {};
```
In the first form, the anonymous hash is being blessed into the class in `$class`. In the second form, the anonymous hash is blessed into the current package.
The second form is strongly discouraged, because it breaks the ability of a subclass to reuse the parent's constructor, but you may still run across it in existing code.
If you want to know whether a particular scalar refers to an object, you can use the `blessed` function exported by <Scalar::Util>, which is shipped with the Perl core.
```
use Scalar::Util 'blessed';
if ( defined blessed($thing) ) { ... }
```
If `$thing` refers to an object, then this function returns the name of the package the object has been blessed into. If `$thing` doesn't contain a reference to a blessed object, the `blessed` function returns `undef`.
Note that `blessed($thing)` will also return false if `$thing` has been blessed into a class named "0". This is a possible, but quite pathological. Don't create a class named "0" unless you know what you're doing.
Similarly, Perl's built-in `ref` function treats a reference to a blessed object specially. If you call `ref($thing)` and `$thing` holds a reference to an object, it will return the name of the class that the object has been blessed into.
If you simply want to check that a variable contains an object reference, we recommend that you use `defined blessed($object)`, since `ref` returns true values for all references, not just objects.
###
The UNIVERSAL Class
All classes automatically inherit from the [UNIVERSAL](universal) class, which is built-in to the Perl core. This class provides a number of methods, all of which can be called on either a class or an object. You can also choose to override some of these methods in your class. If you do so, we recommend that you follow the built-in semantics described below.
isa($class) The `isa` method returns *true* if the object is a member of the class in `$class`, or a member of a subclass of `$class`.
If you override this method, it should never throw an exception.
DOES($role) The `DOES` method returns *true* if its object claims to perform the role `$role`. By default, this is equivalent to `isa`. This method is provided for use by object system extensions that implement roles, like `Moose` and `Role::Tiny`.
You can also override `DOES` directly in your own classes. If you override this method, it should never throw an exception.
can($method) The `can` method checks to see if the class or object it was called on has a method named `$method`. This checks for the method in the class and all of its parents. If the method exists, then a reference to the subroutine is returned. If it does not then `undef` is returned.
If your class responds to method calls via `AUTOLOAD`, you may want to overload `can` to return a subroutine reference for methods which your `AUTOLOAD` method handles.
If you override this method, it should never throw an exception.
VERSION($need) The `VERSION` method returns the version number of the class (package).
If the `$need` argument is given then it will check that the current version (as defined by the $VERSION variable in the package) is greater than or equal to `$need`; it will die if this is not the case. This method is called automatically by the `VERSION` form of `use`.
```
use Package 1.2 qw(some imported subs);
# implies:
Package->VERSION(1.2);
```
We recommend that you use this method to access another package's version, rather than looking directly at `$Package::VERSION`. The package you are looking at could have overridden the `VERSION` method.
We also recommend using this method to check whether a module has a sufficient version. The internal implementation uses the <version> module to make sure that different types of version numbers are compared correctly.
### AUTOLOAD
If you call a method that doesn't exist in a class, Perl will throw an error. However, if that class or any of its parent classes defines an `AUTOLOAD` method, that `AUTOLOAD` method is called instead.
`AUTOLOAD` is called as a regular method, and the caller will not know the difference. Whatever value your `AUTOLOAD` method returns is returned to the caller.
The fully qualified method name that was called is available in the `$AUTOLOAD` package global for your class. Since this is a global, if you want to refer to do it without a package name prefix under `strict 'vars'`, you need to declare it.
```
# XXX - this is a terrible way to implement accessors, but it makes
# for a simple example.
our $AUTOLOAD;
sub AUTOLOAD {
my $self = shift;
# Remove qualifier from original method name...
my $called = $AUTOLOAD =~ s/.*:://r;
# Is there an attribute of that name?
die "No such attribute: $called"
unless exists $self->{$called};
# If so, return it...
return $self->{$called};
}
sub DESTROY { } # see below
```
Without the `our $AUTOLOAD` declaration, this code will not compile under the <strict> pragma.
As the comment says, this is not a good way to implement accessors. It's slow and too clever by far. However, you may see this as a way to provide accessors in older Perl code. See <perlootut> for recommendations on OO coding in Perl.
If your class does have an `AUTOLOAD` method, we strongly recommend that you override `can` in your class as well. Your overridden `can` method should return a subroutine reference for any method that your `AUTOLOAD` responds to.
### Destructors
When the last reference to an object goes away, the object is destroyed. If you only have one reference to an object stored in a lexical scalar, the object is destroyed when that scalar goes out of scope. If you store the object in a package global, that object may not go out of scope until the program exits.
If you want to do something when the object is destroyed, you can define a `DESTROY` method in your class. This method will always be called by Perl at the appropriate time, unless the method is empty.
This is called just like any other method, with the object as the first argument. It does not receive any additional arguments. However, the `$_[0]` variable will be read-only in the destructor, so you cannot assign a value to it.
If your `DESTROY` method throws an exception, this will not cause any control transfer beyond exiting the method. The exception will be reported to `STDERR` as a warning, marked "(in cleanup)", and Perl will continue with whatever it was doing before.
Because `DESTROY` methods can be called at any time, you should localize any global status variables that might be set by anything you do in your `DESTROY` method. If you are in doubt about a particular status variable, it doesn't hurt to localize it. There are five global status variables, and the safest way is to localize all five of them:
```
sub DESTROY {
local($., $@, $!, $^E, $?);
my $self = shift;
...;
}
```
If you define an `AUTOLOAD` in your class, then Perl will call your `AUTOLOAD` to handle the `DESTROY` method. You can prevent this by defining an empty `DESTROY`, like we did in the autoloading example. You can also check the value of `$AUTOLOAD` and return without doing anything when called to handle `DESTROY`.
####
Global Destruction
The order in which objects are destroyed during the global destruction before the program exits is unpredictable. This means that any objects contained by your object may already have been destroyed. You should check that a contained object is defined before calling a method on it:
```
sub DESTROY {
my $self = shift;
$self->{handle}->close() if $self->{handle};
}
```
You can use the `${^GLOBAL_PHASE}` variable to detect if you are currently in the global destruction phase:
```
sub DESTROY {
my $self = shift;
return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
$self->{handle}->close();
}
```
Note that this variable was added in Perl 5.14.0. If you want to detect the global destruction phase on older versions of Perl, you can use the `Devel::GlobalDestruction` module on CPAN.
If your `DESTROY` method issues a warning during global destruction, the Perl interpreter will append the string " during global destruction" to the warning.
During global destruction, Perl will always garbage collect objects before unblessed references. See ["PERL\_DESTRUCT\_LEVEL" in perlhacktips](perlhacktips#PERL_DESTRUCT_LEVEL) for more information about global destruction.
###
Non-Hash Objects
All the examples so far have shown objects based on a blessed hash. However, it's possible to bless any type of data structure or referent, including scalars, globs, and subroutines. You may see this sort of thing when looking at code in the wild.
Here's an example of a module as a blessed scalar:
```
package Time;
use v5.36;
sub new {
my $class = shift;
my $time = time;
return bless \$time, $class;
}
sub epoch {
my $self = shift;
return $$self;
}
my $time = Time->new();
print $time->epoch();
```
###
Inside-Out objects
In the past, the Perl community experimented with a technique called "inside-out objects". An inside-out object stores its data outside of the object's reference, indexed on a unique property of the object, such as its memory address, rather than in the object itself. This has the advantage of enforcing the encapsulation of object attributes, since their data is not stored in the object itself.
This technique was popular for a while (and was recommended in Damian Conway's *Perl Best Practices*), but never achieved universal adoption. The <Object::InsideOut> module on CPAN provides a comprehensive implementation of this technique, and you may see it or other inside-out modules in the wild.
Here is a simple example of the technique, using the <Hash::Util::FieldHash> core module. This module was added to the core to support inside-out object implementations.
```
package Time;
use v5.36;
use Hash::Util::FieldHash 'fieldhash';
fieldhash my %time_for;
sub new {
my $class = shift;
my $self = bless \( my $object ), $class;
$time_for{$self} = time;
return $self;
}
sub epoch {
my $self = shift;
return $time_for{$self};
}
my $time = Time->new;
print $time->epoch;
```
###
Pseudo-hashes
The pseudo-hash feature was an experimental feature introduced in earlier versions of Perl and removed in 5.10.0. A pseudo-hash is an array reference which can be accessed using named keys like a hash. You may run in to some code in the wild which uses it. See the <fields> pragma for more information.
SEE ALSO
---------
A kinder, gentler tutorial on object-oriented programming in Perl can be found in <perlootut>. You should also check out <perlmodlib> for some style guides on constructing both modules and classes.
| programming_docs |
perl perlperf perlperf
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [OVERVIEW](#OVERVIEW)
+ [ONE STEP SIDEWAYS](#ONE-STEP-SIDEWAYS)
+ [ONE STEP FORWARD](#ONE-STEP-FORWARD)
+ [ANOTHER STEP SIDEWAYS](#ANOTHER-STEP-SIDEWAYS)
* [GENERAL GUIDELINES](#GENERAL-GUIDELINES)
* [BENCHMARKS](#BENCHMARKS)
+ [Assigning and Dereferencing Variables.](#Assigning-and-Dereferencing-Variables.)
+ [Search and replace or tr](#Search-and-replace-or-tr)
* [PROFILING TOOLS](#PROFILING-TOOLS)
+ [Devel::DProf](#Devel::DProf)
+ [Devel::Profiler](#Devel::Profiler)
+ [Devel::SmallProf](#Devel::SmallProf)
+ [Devel::FastProf](#Devel::FastProf)
+ [Devel::NYTProf](#Devel::NYTProf)
* [SORTING](#SORTING)
* [LOGGING](#LOGGING)
+ [Logging if DEBUG (constant)](#Logging-if-DEBUG-(constant))
* [POSTSCRIPT](#POSTSCRIPT)
* [SEE ALSO](#SEE-ALSO)
+ [PERLDOCS](#PERLDOCS)
+ [MAN PAGES](#MAN-PAGES)
+ [MODULES](#MODULES)
+ [URLS](#URLS)
* [AUTHOR](#AUTHOR)
NAME
----
perlperf - Perl Performance and Optimization Techniques
DESCRIPTION
-----------
This is an introduction to the use of performance and optimization techniques which can be used with particular reference to perl programs. While many perl developers have come from other languages, and can use their prior knowledge where appropriate, there are many other people who might benefit from a few perl specific pointers. If you want the condensed version, perhaps the best advice comes from the renowned Japanese Samurai, Miyamoto Musashi, who said:
```
"Do Not Engage in Useless Activity"
```
in 1645.
OVERVIEW
--------
Perhaps the most common mistake programmers make is to attempt to optimize their code before a program actually does anything useful - this is a bad idea. There's no point in having an extremely fast program that doesn't work. The first job is to get a program to *correctly* do something **useful**, (not to mention ensuring the test suite is fully functional), and only then to consider optimizing it. Having decided to optimize existing working code, there are several simple but essential steps to consider which are intrinsic to any optimization process.
###
ONE STEP SIDEWAYS
Firstly, you need to establish a baseline time for the existing code, which timing needs to be reliable and repeatable. You'll probably want to use the `Benchmark` or `Devel::NYTProf` modules, or something similar, for this step, or perhaps the Unix system `time` utility, whichever is appropriate. See the base of this document for a longer list of benchmarking and profiling modules, and recommended further reading.
###
ONE STEP FORWARD
Next, having examined the program for *hot spots*, (places where the code seems to run slowly), change the code with the intention of making it run faster. Using version control software, like `subversion`, will ensure no changes are irreversible. It's too easy to fiddle here and fiddle there - don't change too much at any one time or you might not discover which piece of code **really** was the slow bit.
###
ANOTHER STEP SIDEWAYS
It's not enough to say: "that will make it run faster", you have to check it. Rerun the code under control of the benchmarking or profiling modules, from the first step above, and check that the new code executed the **same task** in *less time*. Save your work and repeat...
GENERAL GUIDELINES
-------------------
The critical thing when considering performance is to remember there is no such thing as a `Golden Bullet`, which is why there are no rules, only guidelines.
It is clear that inline code is going to be faster than subroutine or method calls, because there is less overhead, but this approach has the disadvantage of being less maintainable and comes at the cost of greater memory usage - there is no such thing as a free lunch. If you are searching for an element in a list, it can be more efficient to store the data in a hash structure, and then simply look to see whether the key is defined, rather than to loop through the entire array using grep() for instance. substr() may be (a lot) faster than grep() but not as flexible, so you have another trade-off to access. Your code may contain a line which takes 0.01 of a second to execute which if you call it 1,000 times, quite likely in a program parsing even medium sized files for instance, you already have a 10 second delay, in just one single code location, and if you call that line 100,000 times, your entire program will slow down to an unbearable crawl.
Using a subroutine as part of your sort is a powerful way to get exactly what you want, but will usually be slower than the built-in *alphabetic* `cmp` and *numeric* `<=>` sort operators. It is possible to make multiple passes over your data, building indices to make the upcoming sort more efficient, and to use what is known as the `OM` (Orcish Maneuver) to cache the sort keys in advance. The cache lookup, while a good idea, can itself be a source of slowdown by enforcing a double pass over the data - once to setup the cache, and once to sort the data. Using `pack()` to extract the required sort key into a consistent string can be an efficient way to build a single string to compare, instead of using multiple sort keys, which makes it possible to use the standard, written in `c` and fast, perl `sort()` function on the output, and is the basis of the `GRT` (Guttman Rossler Transform). Some string combinations can slow the `GRT` down, by just being too plain complex for its own good.
For applications using database backends, the standard `DBIx` namespace has tries to help with keeping things nippy, not least because it tries to *not* query the database until the latest possible moment, but always read the docs which come with your choice of libraries. Among the many issues facing developers dealing with databases should remain aware of is to always use `SQL` placeholders and to consider pre-fetching data sets when this might prove advantageous. Splitting up a large file by assigning multiple processes to parsing a single file, using say `POE`, `threads` or `fork` can also be a useful way of optimizing your usage of the available `CPU` resources, though this technique is fraught with concurrency issues and demands high attention to detail.
Every case has a specific application and one or more exceptions, and there is no replacement for running a few tests and finding out which method works best for your particular environment, this is why writing optimal code is not an exact science, and why we love using Perl so much - TMTOWTDI.
BENCHMARKS
----------
Here are a few examples to demonstrate usage of Perl's benchmarking tools.
###
Assigning and Dereferencing Variables.
I'm sure most of us have seen code which looks like, (or worse than), this:
```
if ( $obj->{_ref}->{_myscore} >= $obj->{_ref}->{_yourscore} ) {
...
```
This sort of code can be a real eyesore to read, as well as being very sensitive to typos, and it's much clearer to dereference the variable explicitly. We're side-stepping the issue of working with object-oriented programming techniques to encapsulate variable access via methods, only accessible through an object. Here we're just discussing the technical implementation of choice, and whether this has an effect on performance. We can see whether this dereferencing operation, has any overhead by putting comparative code in a file and running a `Benchmark` test.
# dereference
```
#!/usr/bin/perl
use v5.36;
use Benchmark;
my $ref = {
'ref' => {
_myscore => '100 + 1',
_yourscore => '102 - 1',
},
};
timethese(1000000, {
'direct' => sub {
my $x = $ref->{ref}->{_myscore} . $ref->{ref}->{_yourscore} ;
},
'dereference' => sub {
my $ref = $ref->{ref};
my $myscore = $ref->{_myscore};
my $yourscore = $ref->{_yourscore};
my $x = $myscore . $yourscore;
},
});
```
It's essential to run any timing measurements a sufficient number of times so the numbers settle on a numerical average, otherwise each run will naturally fluctuate due to variations in the environment, to reduce the effect of contention for `CPU` resources and network bandwidth for instance. Running the above code for one million iterations, we can take a look at the report output by the `Benchmark` module, to see which approach is the most effective.
```
$> perl dereference
Benchmark: timing 1000000 iterations of dereference, direct...
dereference: 2 wallclock secs ( 1.59 usr + 0.00 sys = 1.59 CPU) @ 628930.82/s (n=1000000)
direct: 1 wallclock secs ( 1.20 usr + 0.00 sys = 1.20 CPU) @ 833333.33/s (n=1000000)
```
The difference is clear to see and the dereferencing approach is slower. While it managed to execute an average of 628,930 times a second during our test, the direct approach managed to run an additional 204,403 times, unfortunately. Unfortunately, because there are many examples of code written using the multiple layer direct variable access, and it's usually horrible. It is, however, minusculy faster. The question remains whether the minute gain is actually worth the eyestrain, or the loss of maintainability.
###
Search and replace or tr
If we have a string which needs to be modified, while a regex will almost always be much more flexible, `tr`, an oft underused tool, can still be a useful. One scenario might be replace all vowels with another character. The regex solution might look like this:
```
$str =~ s/[aeiou]/x/g
```
The `tr` alternative might look like this:
```
$str =~ tr/aeiou/xxxxx/
```
We can put that into a test file which we can run to check which approach is the fastest, using a global `$STR` variable to assign to the `my $str` variable so as to avoid perl trying to optimize any of the work away by noticing it's assigned only the once.
# regex-transliterate
```
#!/usr/bin/perl
use v5.36;
use Benchmark;
my $STR = "$$-this and that";
timethese( 1000000, {
'sr' => sub { my $str = $STR; $str =~ s/[aeiou]/x/g; return $str; },
'tr' => sub { my $str = $STR; $str =~ tr/aeiou/xxxxx/; return $str; },
});
```
Running the code gives us our results:
```
$> perl regex-transliterate
Benchmark: timing 1000000 iterations of sr, tr...
sr: 2 wallclock secs ( 1.19 usr + 0.00 sys = 1.19 CPU) @ 840336.13/s (n=1000000)
tr: 0 wallclock secs ( 0.49 usr + 0.00 sys = 0.49 CPU) @ 2040816.33/s (n=1000000)
```
The `tr` version is a clear winner. One solution is flexible, the other is fast - and it's appropriately the programmer's choice which to use.
Check the `Benchmark` docs for further useful techniques.
PROFILING TOOLS
----------------
A slightly larger piece of code will provide something on which a profiler can produce more extensive reporting statistics. This example uses the simplistic `wordmatch` program which parses a given input file and spews out a short report on the contents.
# wordmatch
```
#!/usr/bin/perl
use v5.36;
=head1 NAME
filewords - word analysis of input file
=head1 SYNOPSIS
filewords -f inputfilename [-d]
=head1 DESCRIPTION
This program parses the given filename, specified with C<-f>, and
displays a simple analysis of the words found therein. Use the C<-d>
switch to enable debugging messages.
=cut
use FileHandle;
use Getopt::Long;
my $debug = 0;
my $file = '';
my $result = GetOptions (
'debug' => \$debug,
'file=s' => \$file,
);
die("invalid args") unless $result;
unless ( -f $file ) {
die("Usage: $0 -f filename [-d]");
}
my $FH = FileHandle->new("< $file")
or die("unable to open file($file): $!");
my $i_LINES = 0;
my $i_WORDS = 0;
my %count = ();
my @lines = <$FH>;
foreach my $line ( @lines ) {
$i_LINES++;
$line =~ s/\n//;
my @words = split(/ +/, $line);
my $i_words = scalar(@words);
$i_WORDS = $i_WORDS + $i_words;
debug("line: $i_LINES supplying $i_words words: @words");
my $i_word = 0;
foreach my $word ( @words ) {
$i_word++;
$count{$i_LINES}{spec} += matches($i_word, $word,
'[^a-zA-Z0-9]');
$count{$i_LINES}{only} += matches($i_word, $word,
'^[^a-zA-Z0-9]+$');
$count{$i_LINES}{cons} += matches($i_word, $word,
'^[(?i:bcdfghjklmnpqrstvwxyz)]+$');
$count{$i_LINES}{vows} += matches($i_word, $word,
'^[(?i:aeiou)]+$');
$count{$i_LINES}{caps} += matches($i_word, $word,
'^[(A-Z)]+$');
}
}
print report( %count );
sub matches {
my $i_wd = shift;
my $word = shift;
my $regex = shift;
my $has = 0;
if ( $word =~ /($regex)/ ) {
$has++ if $1;
}
debug( "word: $i_wd "
. ($has ? 'matches' : 'does not match')
. " chars: /$regex/");
return $has;
}
sub report {
my %report = @_;
my %rep;
foreach my $line ( keys %report ) {
foreach my $key ( keys $report{$line}->%* ) {
$rep{$key} += $report{$line}{$key};
}
}
my $report = qq|
$0 report for $file:
lines in file: $i_LINES
words in file: $i_WORDS
words with special (non-word) characters: $i_spec
words with only special (non-word) characters: $i_only
words with only consonants: $i_cons
words with only capital letters: $i_caps
words with only vowels: $i_vows
|;
return $report;
}
sub debug {
my $message = shift;
if ( $debug ) {
print STDERR "DBG: $message\n";
}
}
exit 0;
```
###
Devel::DProf
This venerable module has been the de-facto standard for Perl code profiling for more than a decade, but has been replaced by a number of other modules which have brought us back to the 21st century. Although you're recommended to evaluate your tool from the several mentioned here and from the CPAN list at the base of this document, (and currently <Devel::NYTProf> seems to be the weapon of choice - see below), we'll take a quick look at the output from <Devel::DProf> first, to set a baseline for Perl profiling tools. Run the above program under the control of `Devel::DProf` by using the `-d` switch on the command-line.
```
$> perl -d:DProf wordmatch -f perl5db.pl
<...multiple lines snipped...>
wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701
```
`Devel::DProf` produces a special file, called *tmon.out* by default, and this file is read by the `dprofpp` program, which is already installed as part of the `Devel::DProf` distribution. If you call `dprofpp` with no options, it will read the *tmon.out* file in the current directory and produce a human readable statistics report of the run of your program. Note that this may take a little time.
```
$> dprofpp
Total Elapsed Time = 2.951677 Seconds
User+System Time = 2.871677 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c Name
102. 2.945 3.003 251215 0.0000 0.0000 main::matches
2.40 0.069 0.069 260643 0.0000 0.0000 main::debug
1.74 0.050 0.050 1 0.0500 0.0500 main::report
1.04 0.030 0.049 4 0.0075 0.0123 main::BEGIN
0.35 0.010 0.010 3 0.0033 0.0033 Exporter::as_heavy
0.35 0.010 0.010 7 0.0014 0.0014 IO::File::BEGIN
0.00 - -0.000 1 - - Getopt::Long::FindOption
0.00 - -0.000 1 - - Symbol::BEGIN
0.00 - -0.000 1 - - Fcntl::BEGIN
0.00 - -0.000 1 - - Fcntl::bootstrap
0.00 - -0.000 1 - - warnings::BEGIN
0.00 - -0.000 1 - - IO::bootstrap
0.00 - -0.000 1 - - Getopt::Long::ConfigDefaults
0.00 - -0.000 1 - - Getopt::Long::Configure
0.00 - -0.000 1 - - Symbol::gensym
```
`dprofpp` will produce some quite detailed reporting on the activity of the `wordmatch` program. The wallclock, user and system, times are at the top of the analysis, and after this are the main columns defining which define the report. Check the `dprofpp` docs for details of the many options it supports.
See also `<Apache::DProf>` which hooks `Devel::DProf` into `mod_perl`.
###
Devel::Profiler
Let's take a look at the same program using a different profiler: `Devel::Profiler`, a drop-in Perl-only replacement for `Devel::DProf`. The usage is very slightly different in that instead of using the special `-d:` flag, you pull `Devel::Profiler` in directly as a module using `-M`.
```
$> perl -MDevel::Profiler wordmatch -f perl5db.pl
<...multiple lines snipped...>
wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701
```
`Devel::Profiler` generates a tmon.out file which is compatible with the `dprofpp` program, thus saving the construction of a dedicated statistics reader program. `dprofpp` usage is therefore identical to the above example.
```
$> dprofpp
Total Elapsed Time = 20.984 Seconds
User+System Time = 19.981 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c Name
49.0 9.792 14.509 251215 0.0000 0.0001 main::matches
24.4 4.887 4.887 260643 0.0000 0.0000 main::debug
0.25 0.049 0.049 1 0.0490 0.0490 main::report
0.00 0.000 0.000 1 0.0000 0.0000 Getopt::Long::GetOptions
0.00 0.000 0.000 2 0.0000 0.0000 Getopt::Long::ParseOptionSpec
0.00 0.000 0.000 1 0.0000 0.0000 Getopt::Long::FindOption
0.00 0.000 0.000 1 0.0000 0.0000 IO::File::new
0.00 0.000 0.000 1 0.0000 0.0000 IO::Handle::new
0.00 0.000 0.000 1 0.0000 0.0000 Symbol::gensym
0.00 0.000 0.000 1 0.0000 0.0000 IO::File::open
```
Interestingly we get slightly different results, which is mostly because the algorithm which generates the report is different, even though the output file format was allegedly identical. The elapsed, user and system times are clearly showing the time it took for `Devel::Profiler` to execute its own run, but the column listings feel more accurate somehow than the ones we had earlier from `Devel::DProf`. The 102% figure has disappeared, for example. This is where we have to use the tools at our disposal, and recognise their pros and cons, before using them. Interestingly, the numbers of calls for each subroutine are identical in the two reports, it's the percentages which differ. As the author of `Devel::Proviler` writes:
```
...running HTML::Template's test suite under Devel::DProf shows
output() taking NO time but Devel::Profiler shows around 10% of the
time is in output(). I don't know which to trust but my gut tells me
something is wrong with Devel::DProf. HTML::Template::output() is a
big routine that's called for every test. Either way, something needs
fixing.
```
YMMV.
See also `<Devel::Apache::Profiler>` which hooks `Devel::Profiler` into `mod_perl`.
###
Devel::SmallProf
The `Devel::SmallProf` profiler examines the runtime of your Perl program and produces a line-by-line listing to show how many times each line was called, and how long each line took to execute. It is called by supplying the familiar `-d` flag to Perl at runtime.
```
$> perl -d:SmallProf wordmatch -f perl5db.pl
<...multiple lines snipped...>
wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701
```
`Devel::SmallProf` writes it's output into a file called *smallprof.out*, by default. The format of the file looks like this:
```
<num> <time> <ctime> <line>:<text>
```
When the program has terminated, the output may be examined and sorted using any standard text filtering utilities. Something like the following may be sufficient:
```
$> cat smallprof.out | grep \d*: | sort -k3 | tac | head -n20
251215 1.65674 7.68000 75: if ( $word =~ /($regex)/ ) {
251215 0.03264 4.40000 79: debug("word: $i_wd ".($has ? 'matches' :
251215 0.02693 4.10000 81: return $has;
260643 0.02841 4.07000 128: if ( $debug ) {
260643 0.02601 4.04000 126: my $message = shift;
251215 0.02641 3.91000 73: my $has = 0;
251215 0.03311 3.71000 70: my $i_wd = shift;
251215 0.02699 3.69000 72: my $regex = shift;
251215 0.02766 3.68000 71: my $word = shift;
50243 0.59726 1.00000 59: $count{$i_LINES}{cons} =
50243 0.48175 0.92000 61: $count{$i_LINES}{spec} =
50243 0.00644 0.89000 56: my $i_cons = matches($i_word, $word,
50243 0.48837 0.88000 63: $count{$i_LINES}{caps} =
50243 0.00516 0.88000 58: my $i_caps = matches($i_word, $word, '^[(A-
50243 0.00631 0.81000 54: my $i_spec = matches($i_word, $word, '[^a-
50243 0.00496 0.80000 57: my $i_vows = matches($i_word, $word,
50243 0.00688 0.80000 53: $i_word++;
50243 0.48469 0.79000 62: $count{$i_LINES}{only} =
50243 0.48928 0.77000 60: $count{$i_LINES}{vows} =
50243 0.00683 0.75000 55: my $i_only = matches($i_word, $word, '^[^a-
```
You can immediately see a slightly different focus to the subroutine profiling modules, and we start to see exactly which line of code is taking the most time. That regex line is looking a bit suspicious, for example. Remember that these tools are supposed to be used together, there is no single best way to profile your code, you need to use the best tools for the job.
See also `<Apache::SmallProf>` which hooks `Devel::SmallProf` into `mod_perl`.
###
Devel::FastProf
`Devel::FastProf` is another Perl line profiler. This was written with a view to getting a faster line profiler, than is possible with for example `Devel::SmallProf`, because it's written in `C`. To use `Devel::FastProf`, supply the `-d` argument to Perl:
```
$> perl -d:FastProf wordmatch -f perl5db.pl
<...multiple lines snipped...>
wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701
```
`Devel::FastProf` writes statistics to the file *fastprof.out* in the current directory. The output file, which can be specified, can be interpreted by using the `fprofpp` command-line program.
```
$> fprofpp | head -n20
# fprofpp output format is:
# filename:line time count: source
wordmatch:75 3.93338 251215: if ( $word =~ /($regex)/ ) {
wordmatch:79 1.77774 251215: debug("word: $i_wd ".($has ? 'matches' : 'does not match')." chars: /$regex/");
wordmatch:81 1.47604 251215: return $has;
wordmatch:126 1.43441 260643: my $message = shift;
wordmatch:128 1.42156 260643: if ( $debug ) {
wordmatch:70 1.36824 251215: my $i_wd = shift;
wordmatch:71 1.36739 251215: my $word = shift;
wordmatch:72 1.35939 251215: my $regex = shift;
```
Straightaway we can see that the number of times each line has been called is identical to the `Devel::SmallProf` output, and the sequence is only very slightly different based on the ordering of the amount of time each line took to execute, `if ( $debug ) {` and `my $message = shift;`, for example. The differences in the actual times recorded might be in the algorithm used internally, or it could be due to system resource limitations or contention.
See also the <DBIx::Profile> which will profile database queries running under the `DBIx::*` namespace.
###
Devel::NYTProf
`Devel::NYTProf` is the **next generation** of Perl code profiler, fixing many shortcomings in other tools and implementing many cool features. First of all it can be used as either a *line* profiler, a *block* or a *subroutine* profiler, all at once. It can also use sub-microsecond (100ns) resolution on systems which provide `clock_gettime()`. It can be started and stopped even by the program being profiled. It's a one-line entry to profile `mod_perl` applications. It's written in `c` and is probably the fastest profiler available for Perl. The list of coolness just goes on. Enough of that, let's see how to it works - just use the familiar `-d` switch to plug it in and run the code.
```
$> perl -d:NYTProf wordmatch -f perl5db.pl
wordmatch report for perl5db.pl:
lines in file: 9427
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701
```
`NYTProf` will generate a report database into the file *nytprof.out* by default. Human readable reports can be generated from here by using the supplied `nytprofhtml` (HTML output) and `nytprofcsv` (CSV output) programs. We've used the Unix system `html2text` utility to convert the *nytprof/index.html* file for convenience here.
```
$> html2text nytprof/index.html
Performance Profile Index
For wordmatch
Run on Fri Sep 26 13:46:39 2008
Reported on Fri Sep 26 13:47:23 2008
Top 15 Subroutines -- ordered by exclusive time
|Calls |P |F |Inclusive|Exclusive|Subroutine |
| | | |Time |Time | |
|251215|5 |1 |13.09263 |10.47692 |main:: |matches |
|260642|2 |1 |2.71199 |2.71199 |main:: |debug |
|1 |1 |1 |0.21404 |0.21404 |main:: |report |
|2 |2 |2 |0.00511 |0.00511 |XSLoader:: |load (xsub) |
|14 |14|7 |0.00304 |0.00298 |Exporter:: |import |
|3 |1 |1 |0.00265 |0.00254 |Exporter:: |as_heavy |
|10 |10|4 |0.00140 |0.00140 |vars:: |import |
|13 |13|1 |0.00129 |0.00109 |constant:: |import |
|1 |1 |1 |0.00360 |0.00096 |FileHandle:: |import |
|3 |3 |3 |0.00086 |0.00074 |warnings::register::|import |
|9 |3 |1 |0.00036 |0.00036 |strict:: |bits |
|13 |13|13|0.00032 |0.00029 |strict:: |import |
|2 |2 |2 |0.00020 |0.00020 |warnings:: |import |
|2 |1 |1 |0.00020 |0.00020 |Getopt::Long:: |ParseOptionSpec|
|7 |7 |6 |0.00043 |0.00020 |strict:: |unimport |
For more information see the full list of 189 subroutines.
```
The first part of the report already shows the critical information regarding which subroutines are using the most time. The next gives some statistics about the source files profiled.
```
Source Code Files -- ordered by exclusive time then name
|Stmts |Exclusive|Avg. |Reports |Source File |
| |Time | | | |
|2699761|15.66654 |6e-06 |line . block . sub|wordmatch |
|35 |0.02187 |0.00062|line . block . sub|IO/Handle.pm |
|274 |0.01525 |0.00006|line . block . sub|Getopt/Long.pm |
|20 |0.00585 |0.00029|line . block . sub|Fcntl.pm |
|128 |0.00340 |0.00003|line . block . sub|Exporter/Heavy.pm |
|42 |0.00332 |0.00008|line . block . sub|IO/File.pm |
|261 |0.00308 |0.00001|line . block . sub|Exporter.pm |
|323 |0.00248 |8e-06 |line . block . sub|constant.pm |
|12 |0.00246 |0.00021|line . block . sub|File/Spec/Unix.pm |
|191 |0.00240 |0.00001|line . block . sub|vars.pm |
|77 |0.00201 |0.00003|line . block . sub|FileHandle.pm |
|12 |0.00198 |0.00016|line . block . sub|Carp.pm |
|14 |0.00175 |0.00013|line . block . sub|Symbol.pm |
|15 |0.00130 |0.00009|line . block . sub|IO.pm |
|22 |0.00120 |0.00005|line . block . sub|IO/Seekable.pm |
|198 |0.00085 |4e-06 |line . block . sub|warnings/register.pm|
|114 |0.00080 |7e-06 |line . block . sub|strict.pm |
|47 |0.00068 |0.00001|line . block . sub|warnings.pm |
|27 |0.00054 |0.00002|line . block . sub|overload.pm |
|9 |0.00047 |0.00005|line . block . sub|SelectSaver.pm |
|13 |0.00045 |0.00003|line . block . sub|File/Spec.pm |
|2701595|15.73869 | |Total |
|128647 |0.74946 | |Average |
| |0.00201 |0.00003|Median |
| |0.00121 |0.00003|Deviation |
Report produced by the NYTProf 2.03 Perl profiler, developed by Tim Bunce and
Adam Kaplan.
```
At this point, if you're using the *html* report, you can click through the various links to bore down into each subroutine and each line of code. Because we're using the text reporting here, and there's a whole directory full of reports built for each source file, we'll just display a part of the corresponding *wordmatch-line.html* file, sufficient to give an idea of the sort of output you can expect from this cool tool.
```
$> html2text nytprof/wordmatch-line.html
Performance Profile -- -block view-.-line view-.-sub view-
For wordmatch
Run on Fri Sep 26 13:46:39 2008
Reported on Fri Sep 26 13:47:22 2008
File wordmatch
Subroutines -- ordered by exclusive time
|Calls |P|F|Inclusive|Exclusive|Subroutine |
| | | |Time |Time | |
|251215|5|1|13.09263 |10.47692 |main::|matches|
|260642|2|1|2.71199 |2.71199 |main::|debug |
|1 |1|1|0.21404 |0.21404 |main::|report |
|0 |0|0|0 |0 |main::|BEGIN |
|Line|Stmts.|Exclusive|Avg. |Code |
| | |Time | | |
|1 | | | |#!/usr/bin/perl |
|2 | | | | |
| | | | |use strict; |
|3 |3 |0.00086 |0.00029|# spent 0.00003s making 1 calls to strict:: |
| | | | |import |
| | | | |use warnings; |
|4 |3 |0.01563 |0.00521|# spent 0.00012s making 1 calls to warnings:: |
| | | | |import |
|5 | | | | |
|6 | | | |=head1 NAME |
|7 | | | | |
|8 | | | |filewords - word analysis of input file |
<...snip...>
|62 |1 |0.00445 |0.00445|print report( %count ); |
| | | | |# spent 0.21404s making 1 calls to main::report|
|63 | | | | |
| | | | |# spent 23.56955s (10.47692+2.61571) within |
| | | | |main::matches which was called 251215 times, |
| | | | |avg 0.00005s/call: # 50243 times |
| | | | |(2.12134+0.51939s) at line 57 of wordmatch, avg|
| | | | |0.00005s/call # 50243 times (2.17735+0.54550s) |
|64 | | | |at line 56 of wordmatch, avg 0.00005s/call # |
| | | | |50243 times (2.10992+0.51797s) at line 58 of |
| | | | |wordmatch, avg 0.00005s/call # 50243 times |
| | | | |(2.12696+0.51598s) at line 55 of wordmatch, avg|
| | | | |0.00005s/call # 50243 times (1.94134+0.51687s) |
| | | | |at line 54 of wordmatch, avg 0.00005s/call |
| | | | |sub matches { |
<...snip...>
|102 | | | | |
| | | | |# spent 2.71199s within main::debug which was |
| | | | |called 260642 times, avg 0.00001s/call: # |
| | | | |251215 times (2.61571+0s) by main::matches at |
|103 | | | |line 74 of wordmatch, avg 0.00001s/call # 9427 |
| | | | |times (0.09628+0s) at line 50 of wordmatch, avg|
| | | | |0.00001s/call |
| | | | |sub debug { |
|104 |260642|0.58496 |2e-06 |my $message = shift; |
|105 | | | | |
|106 |260642|1.09917 |4e-06 |if ( $debug ) { |
|107 | | | |print STDERR "DBG: $message\n"; |
|108 | | | |} |
|109 | | | |} |
|110 | | | | |
|111 |1 |0.01501 |0.01501|exit 0; |
|112 | | | | |
```
Oodles of very useful information in there - this seems to be the way forward.
See also `<Devel::NYTProf::Apache>` which hooks `Devel::NYTProf` into `mod_perl`.
SORTING
-------
Perl modules are not the only tools a performance analyst has at their disposal, system tools like `time` should not be overlooked as the next example shows, where we take a quick look at sorting. Many books, theses and articles, have been written about efficient sorting algorithms, and this is not the place to repeat such work, there's several good sorting modules which deserve taking a look at too: `Sort::Maker`, `Sort::Key` spring to mind. However, it's still possible to make some observations on certain Perl specific interpretations on issues relating to sorting data sets and give an example or two with regard to how sorting large data volumes can effect performance. Firstly, an often overlooked point when sorting large amounts of data, one can attempt to reduce the data set to be dealt with and in many cases `grep()` can be quite useful as a simple filter:
```
@data = sort grep { /$filter/ } @incoming
```
A command such as this can vastly reduce the volume of material to actually sort through in the first place, and should not be too lightly disregarded purely on the basis of its simplicity. The `KISS` principle is too often overlooked - the next example uses the simple system `time` utility to demonstrate. Let's take a look at an actual example of sorting the contents of a large file, an apache logfile would do. This one has over a quarter of a million lines, is 50M in size, and a snippet of it looks like this:
# logfile
```
188.209-65-87.adsl-dyn.isp.belgacom.be - - [08/Feb/2007:12:57:16 +0000] "GET /favicon.ico HTTP/1.1" 404 209 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
188.209-65-87.adsl-dyn.isp.belgacom.be - - [08/Feb/2007:12:57:16 +0000] "GET /favicon.ico HTTP/1.1" 404 209 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
151.56.71.198 - - [08/Feb/2007:12:57:41 +0000] "GET /suse-on-vaio.html HTTP/1.1" 200 2858 "http://www.linux-on-laptops.com/sony.html" "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"
151.56.71.198 - - [08/Feb/2007:12:57:42 +0000] "GET /data/css HTTP/1.1" 404 206 "http://www.rfi.net/suse-on-vaio.html" "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"
151.56.71.198 - - [08/Feb/2007:12:57:43 +0000] "GET /favicon.ico HTTP/1.1" 404 209 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"
217.113.68.60 - - [08/Feb/2007:13:02:15 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
217.113.68.60 - - [08/Feb/2007:13:02:16 +0000] "GET /data/css HTTP/1.1" 404 206 "http://www.rfi.net/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] "GET /suse-on-vaio.html HTTP/1.1" 200 2858 "http://www.linux-on-laptops.com/sony.html" "Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)"
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] "GET /data/css HTTP/1.1" 404 206 "http://www.rfi.net/suse-on-vaio.html" "Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)"
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] "GET /favicon.ico HTTP/1.1" 404 209 "-" "Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)"
195.24.196.99 - - [08/Feb/2007:13:26:48 +0000] "GET / HTTP/1.0" 200 3309 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9"
195.24.196.99 - - [08/Feb/2007:13:26:58 +0000] "GET /data/css HTTP/1.0" 404 206 "http://www.rfi.net/" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9"
195.24.196.99 - - [08/Feb/2007:13:26:59 +0000] "GET /favicon.ico HTTP/1.0" 404 209 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9"
crawl1.cosmixcorp.com - - [08/Feb/2007:13:27:57 +0000] "GET /robots.txt HTTP/1.0" 200 179 "-" "voyager/1.0"
crawl1.cosmixcorp.com - - [08/Feb/2007:13:28:25 +0000] "GET /links.html HTTP/1.0" 200 3413 "-" "voyager/1.0"
fhm226.internetdsl.tpnet.pl - - [08/Feb/2007:13:37:32 +0000] "GET /suse-on-vaio.html HTTP/1.1" 200 2858 "http://www.linux-on-laptops.com/sony.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
fhm226.internetdsl.tpnet.pl - - [08/Feb/2007:13:37:34 +0000] "GET /data/css HTTP/1.1" 404 206 "http://www.rfi.net/suse-on-vaio.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
80.247.140.134 - - [08/Feb/2007:13:57:35 +0000] "GET / HTTP/1.1" 200 3309 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"
80.247.140.134 - - [08/Feb/2007:13:57:37 +0000] "GET /data/css HTTP/1.1" 404 206 "http://www.rfi.net" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"
pop.compuscan.co.za - - [08/Feb/2007:14:10:43 +0000] "GET / HTTP/1.1" 200 3309 "-" "www.clamav.net"
livebot-207-46-98-57.search.live.com - - [08/Feb/2007:14:12:04 +0000] "GET /robots.txt HTTP/1.0" 200 179 "-" "msnbot/1.0 (+http://search.msn.com/msnbot.htm)"
livebot-207-46-98-57.search.live.com - - [08/Feb/2007:14:12:04 +0000] "GET /html/oracle.html HTTP/1.0" 404 214 "-" "msnbot/1.0 (+http://search.msn.com/msnbot.htm)"
dslb-088-064-005-154.pools.arcor-ip.net - - [08/Feb/2007:14:12:15 +0000] "GET / HTTP/1.1" 200 3309 "-" "www.clamav.net"
196.201.92.41 - - [08/Feb/2007:14:15:01 +0000] "GET / HTTP/1.1" 200 3309 "-" "MOT-L7/08.B7.DCR MIB/2.2.1 Profile/MIDP-2.0 Configuration/CLDC-1.1"
```
The specific task here is to sort the 286,525 lines of this file by Response Code, Query, Browser, Referring Url, and lastly Date. One solution might be to use the following code, which iterates over the files given on the command-line.
# sort-apache-log
```
#!/usr/bin/perl -n
use v5.36;
my @data;
LINE:
while ( <> ) {
my $line = $_;
if (
$line =~ m/^(
([\w\.\-]+) # client
\s*-\s*-\s*\[
([^]]+) # date
\]\s*"\w+\s*
(\S+) # query
[^"]+"\s*
(\d+) # status
\s+\S+\s+"[^"]*"\s+"
([^"]*) # browser
"
.*
)$/x
) {
my @chunks = split(/ +/, $line);
my $ip = $1;
my $date = $2;
my $query = $3;
my $status = $4;
my $browser = $5;
push(@data, [$ip, $date, $query, $status, $browser, $line]);
}
}
my @sorted = sort {
$a->[3] cmp $b->[3]
||
$a->[2] cmp $b->[2]
||
$a->[0] cmp $b->[0]
||
$a->[1] cmp $b->[1]
||
$a->[4] cmp $b->[4]
} @data;
foreach my $data ( @sorted ) {
print $data->[5];
}
exit 0;
```
When running this program, redirect `STDOUT` so it is possible to check the output is correct from following test runs and use the system `time` utility to check the overall runtime.
```
$> time ./sort-apache-log logfile > out-sort
real 0m17.371s
user 0m15.757s
sys 0m0.592s
```
The program took just over 17 wallclock seconds to run. Note the different values `time` outputs, it's important to always use the same one, and to not confuse what each one means.
Elapsed Real Time The overall, or wallclock, time between when `time` was called, and when it terminates. The elapsed time includes both user and system times, and time spent waiting for other users and processes on the system. Inevitably, this is the most approximate of the measurements given.
User CPU Time The user time is the amount of time the entire process spent on behalf of the user on this system executing this program.
System CPU Time The system time is the amount of time the kernel itself spent executing routines, or system calls, on behalf of this process user.
Running this same process as a `Schwarzian Transform` it is possible to eliminate the input and output arrays for storing all the data, and work on the input directly as it arrives too. Otherwise, the code looks fairly similar:
# sort-apache-log-schwarzian
```
#!/usr/bin/perl -n
use v5.36;
print
map $_->[0] =>
sort {
$a->[4] cmp $b->[4]
||
$a->[3] cmp $b->[3]
||
$a->[1] cmp $b->[1]
||
$a->[2] cmp $b->[2]
||
$a->[5] cmp $b->[5]
}
map [ $_, m/^(
([\w\.\-]+) # client
\s*-\s*-\s*\[
([^]]+) # date
\]\s*"\w+\s*
(\S+) # query
[^"]+"\s*
(\d+) # status
\s+\S+\s+"[^"]*"\s+"
([^"]*) # browser
"
.*
)$/xo ]
=> <>;
exit 0;
```
Run the new code against the same logfile, as above, to check the new time.
```
$> time ./sort-apache-log-schwarzian logfile > out-schwarz
real 0m9.664s
user 0m8.873s
sys 0m0.704s
```
The time has been cut in half, which is a respectable speed improvement by any standard. Naturally, it is important to check the output is consistent with the first program run, this is where the Unix system `cksum` utility comes in.
```
$> cksum out-sort out-schwarz
3044173777 52029194 out-sort
3044173777 52029194 out-schwarz
```
BTW. Beware too of pressure from managers who see you speed a program up by 50% of the runtime once, only to get a request one month later to do the same again (true story) - you'll just have to point out you're only human, even if you are a Perl programmer, and you'll see what you can do...
LOGGING
-------
An essential part of any good development process is appropriate error handling with appropriately informative messages, however there exists a school of thought which suggests that log files should be *chatty*, as if the chain of unbroken output somehow ensures the survival of the program. If speed is in any way an issue, this approach is wrong.
A common sight is code which looks something like this:
```
logger->debug( "A logging message via process-id: $$ INC: "
. Dumper(\%INC) )
```
The problem is that this code will always be parsed and executed, even when the debug level set in the logging configuration file is zero. Once the debug() subroutine has been entered, and the internal `$debug` variable confirmed to be zero, for example, the message which has been sent in will be discarded and the program will continue. In the example given though, the `\%INC` hash will already have been dumped, and the message string constructed, all of which work could be bypassed by a debug variable at the statement level, like this:
```
logger->debug( "A logging message via process-id: $$ INC: "
. Dumper(\%INC) ) if $DEBUG;
```
This effect can be demonstrated by setting up a test script with both forms, including a `debug()` subroutine to emulate typical `logger()` functionality.
# ifdebug
```
#!/usr/bin/perl
use v5.36;
use Benchmark;
use Data::Dumper;
my $DEBUG = 0;
sub debug {
my $msg = shift;
if ( $DEBUG ) {
print "DEBUG: $msg\n";
}
};
timethese(100000, {
'debug' => sub {
debug( "A $0 logging message via process-id: $$" . Dumper(\%INC) )
},
'ifdebug' => sub {
debug( "A $0 logging message via process-id: $$" . Dumper(\%INC) ) if $DEBUG
},
});
```
Let's see what `Benchmark` makes of this:
```
$> perl ifdebug
Benchmark: timing 100000 iterations of constant, sub...
ifdebug: 0 wallclock secs ( 0.01 usr + 0.00 sys = 0.01 CPU) @ 10000000.00/s (n=100000)
(warning: too few iterations for a reliable count)
debug: 14 wallclock secs (13.18 usr + 0.04 sys = 13.22 CPU) @ 7564.30/s (n=100000)
```
In the one case the code, which does exactly the same thing as far as outputting any debugging information is concerned, in other words nothing, takes 14 seconds, and in the other case the code takes one hundredth of a second. Looks fairly definitive. Use a `$DEBUG` variable BEFORE you call the subroutine, rather than relying on the smart functionality inside it.
###
Logging if DEBUG (constant)
It's possible to take the previous idea a little further, by using a compile time `DEBUG` constant.
# ifdebug-constant
```
#!/usr/bin/perl
use v5.36;
use Benchmark;
use Data::Dumper;
use constant
DEBUG => 0
;
sub debug {
if ( DEBUG ) {
my $msg = shift;
print "DEBUG: $msg\n";
}
};
timethese(100000, {
'debug' => sub {
debug( "A $0 logging message via process-id: $$" . Dumper(\%INC) )
},
'constant' => sub {
debug( "A $0 logging message via process-id: $$" . Dumper(\%INC) ) if DEBUG
},
});
```
Running this program produces the following output:
```
$> perl ifdebug-constant
Benchmark: timing 100000 iterations of constant, sub...
constant: 0 wallclock secs (-0.00 usr + 0.00 sys = -0.00 CPU) @ -7205759403792793600000.00/s (n=100000)
(warning: too few iterations for a reliable count)
sub: 14 wallclock secs (13.09 usr + 0.00 sys = 13.09 CPU) @ 7639.42/s (n=100000)
```
The `DEBUG` constant wipes the floor with even the `$debug` variable, clocking in at minus zero seconds, and generates a "warning: too few iterations for a reliable count" message into the bargain. To see what is really going on, and why we had too few iterations when we thought we asked for 100000, we can use the very useful `B::Deparse` to inspect the new code:
```
$> perl -MO=Deparse ifdebug-constant
use Benchmark;
use Data::Dumper;
use constant ('DEBUG', 0);
sub debug {
use warnings;
use strict 'refs';
0;
}
use warnings;
use strict 'refs';
timethese(100000, {'sub', sub {
debug "A $0 logging message via process-id: $$" . Dumper(\%INC);
}
, 'constant', sub {
0;
}
});
ifdebug-constant syntax OK
```
The output shows the constant() subroutine we're testing being replaced with the value of the `DEBUG` constant: zero. The line to be tested has been completely optimized away, and you can't get much more efficient than that.
POSTSCRIPT
----------
This document has provided several way to go about identifying hot-spots, and checking whether any modifications have improved the runtime of the code.
As a final thought, remember that it's not (at the time of writing) possible to produce a useful program which will run in zero or negative time and this basic principle can be written as: *useful programs are slow* by their very definition. It is of course possible to write a nearly instantaneous program, but it's not going to do very much, here's a very efficient one:
```
$> perl -e 0
```
Optimizing that any further is a job for `p5p`.
SEE ALSO
---------
Further reading can be found using the modules and links below.
### PERLDOCS
For example: `perldoc -f sort`.
<perlfaq4>.
<perlfork>, <perlfunc>, <perlretut>, <perlthrtut>.
<threads>.
###
MAN PAGES
`time`.
### MODULES
It's not possible to individually showcase all the performance related code for Perl here, naturally, but here's a short list of modules from the CPAN which deserve further attention.
```
Apache::DProf
Apache::SmallProf
Benchmark
DBIx::Profile
Devel::AutoProfiler
Devel::DProf
Devel::DProfLB
Devel::FastProf
Devel::GraphVizProf
Devel::NYTProf
Devel::NYTProf::Apache
Devel::Profiler
Devel::Profile
Devel::Profit
Devel::SmallProf
Devel::WxProf
POE::Devel::Profiler
Sort::Key
Sort::Maker
```
### URLS
Very useful online reference material:
```
https://web.archive.org/web/20120515021937/http://www.ccl4.org/~nick/P/Fast_Enough/
https://web.archive.org/web/20050706081718/http://www-106.ibm.com/developerworks/library/l-optperl.html
https://perlbuzz.com/2007/11/14/bind_output_variables_in_dbi_for_speed_and_safety/
http://en.wikipedia.org/wiki/Performance_analysis
http://apache.perl.org/docs/1.0/guide/performance.html
http://perlgolf.sourceforge.net/
http://www.sysarch.com/Perl/sort_paper.html
```
AUTHOR
------
Richard Foley <[email protected]> Copyright (c) 2008
| programming_docs |
perl perllexwarn perllexwarn
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
perllexwarn - Perl Lexical Warnings
DESCRIPTION
-----------
Perl v5.6.0 introduced lexical control over the handling of warnings by category. The `warnings` pragma generally replaces the command line flag **-w**. Documentation on the use of lexical warnings, once partly found in this document, is now found in the <warnings> documentation.
perl Encode::JP::H2Z Encode::JP::H2Z
===============
CONTENTS
--------
* [NAME](#NAME)
NAME
----
Encode::JP::H2Z -- internally used by Encode::JP::2022\_JP\*
perl perlivp perlivp
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [AUTHOR](#AUTHOR)
NAME
----
perlivp - Perl Installation Verification Procedure
SYNOPSIS
--------
**perlivp** [**-p**] [**-v**] [**-h**]
DESCRIPTION
-----------
The **perlivp** program is set up at Perl source code build time to test the Perl version it was built under. It can be used after running:
```
make install
```
(or your platform's equivalent procedure) to verify that **perl** and its libraries have been installed correctly. A correct installation is verified by output that looks like:
```
ok 1
ok 2
```
etc.
OPTIONS
-------
**-h** help Prints out a brief help message.
**-p** print preface Gives a description of each test prior to performing it.
**-v** verbose Gives more detailed information about each test, after it has been performed. Note that any failed tests ought to print out some extra information whether or not -v is thrown.
DIAGNOSTICS
-----------
* print "# Perl binary '$perlpath' does not appear executable.\n";
Likely to occur for a perl binary that was not properly installed. Correct by conducting a proper installation.
* print "# Perl version '$]' installed, expected $ivp\_VERSION.\n";
Likely to occur for a perl that was not properly installed. Correct by conducting a proper installation.
* print "# Perl \@INC directory '$\_' does not appear to exist.\n";
Likely to occur for a perl library tree that was not properly installed. Correct by conducting a proper installation.
* print "# Needed module '$\_' does not appear to be properly installed.\n";
One of the two modules that is used by perlivp was not present in the installation. This is a serious error since it adversely affects perlivp's ability to function. You may be able to correct this by performing a proper perl installation.
* print "# Required module '$\_' does not appear to be properly installed.\n";
An attempt to `eval "require $module"` failed, even though the list of extensions indicated that it should succeed. Correct by conducting a proper installation.
* print "# Unnecessary module 'bLuRfle' appears to be installed.\n";
This test not coming out ok could indicate that you have in fact installed a bLuRfle.pm module or that the `eval " require \"$module_name.pm\"; "` test may give misleading results with your installation of perl. If yours is the latter case then please let the author know.
* print "# file",+($#missing == 0) ? '' : 's'," missing from installation:\n";
One or more files turned up missing according to a run of `ExtUtils::Installed -> validate()` over your installation. Correct by conducting a proper installation.
For further information on how to conduct a proper installation consult the INSTALL file that comes with the perl source and the README file for your platform.
AUTHOR
------
Peter Prymmer
perl Test2::API::Stack Test2::API::Stack
=================
CONTENTS
--------
* [NAME](#NAME)
* [\*\*\*INTERNALS NOTE\*\*\*](#***INTERNALS-NOTE***)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::Stack - Object to manage a stack of <Test2::Hub> instances.
\*\*\*INTERNALS NOTE\*\*\*
---------------------------
**The internals of this package are subject to change at any time!** The public methods provided will not change in backwards incompatible ways, but the underlying implementation details might. **Do not break encapsulation here!**
DESCRIPTION
-----------
This module is used to represent and manage a stack of <Test2::Hub> objects. Hubs are usually in a stack so that you can push a new hub into place that can intercept and handle events differently than the primary hub.
SYNOPSIS
--------
```
my $stack = Test2::API::Stack->new;
my $hub = $stack->top;
```
METHODS
-------
$stack = Test2::API::Stack->new() This will create a new empty stack instance. All arguments are ignored.
$hub = $stack->new\_hub()
$hub = $stack->new\_hub(%params)
$hub = $stack->new\_hub(%params, class => $class) This will generate a new hub and push it to the top of the stack. Optionally you can provide arguments that will be passed into the constructor for the <Test2::Hub> object.
If you specify the `'class' => $class` argument, the new hub will be an instance of the specified class.
Unless your parameters specify `'formatter'` or `'ipc'` arguments, the formatter and IPC instance will be inherited from the current top hub. You can set the parameters to `undef` to avoid having a formatter or IPC instance.
If there is no top hub, and you do not ask to leave IPC and formatter undef, then a new formatter will be created, and the IPC instance from <Test2::API> will be used.
$hub = $stack->top() This will return the top hub from the stack. If there is no top hub yet this will create it.
$hub = $stack->peek() This will return the top hub from the stack. If there is no top hub yet this will return undef.
$stack->cull This will call `$hub->cull` on all hubs in the stack.
@hubs = $stack->all This will return all the hubs in the stack as a list.
$stack->clear This will completely remove all hubs from the stack. Normally you do not want to do this, but there are a few valid reasons for it.
$stack->push($hub) This will push the new hub onto the stack.
$stack->pop($hub) This will pop a hub from the stack, if the hub at the top of the stack does not match the hub you expect (passed in as an argument) it will throw an exception.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl DBM_Filter DBM\_Filter
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [What is a DBM Filter?](#What-is-a-DBM-Filter?)
+ [So what's new?](#So-what's-new?)
* [METHODS](#METHODS)
+ [$db->Filter\_Push() / $db->Filter\_Key\_Push() / $db->Filter\_Value\_Push()](#%24db-%3EFilter_Push()-/-%24db-%3EFilter_Key_Push()-/-%24db-%3EFilter_Value_Push())
+ [$db->Filter\_Pop()](#%24db-%3EFilter_Pop())
+ [$db->Filtered()](#%24db-%3EFiltered())
* [Writing a Filter](#Writing-a-Filter)
+ [Immediate Filters](#Immediate-Filters)
+ [Canned Filters](#Canned-Filters)
* [Filters Included](#Filters-Included)
* [NOTES](#NOTES)
+ [Maintain Round Trip Integrity](#Maintain-Round-Trip-Integrity)
+ [Don't mix filtered & non-filtered data in the same database file.](#Don't-mix-filtered-&-non-filtered-data-in-the-same-database-file.)
* [EXAMPLE](#EXAMPLE)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter -- Filter DBM keys/values
SYNOPSIS
--------
```
use DBM_Filter ;
use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File
$db = tie %hash, ...
$db->Filter_Push(Fetch => sub {...},
Store => sub {...});
$db->Filter_Push('my_filter1');
$db->Filter_Push('my_filter2', params...);
$db->Filter_Key_Push(...) ;
$db->Filter_Value_Push(...) ;
$db->Filter_Pop();
$db->Filtered();
package DBM_Filter::my_filter1;
sub Store { ... }
sub Fetch { ... }
1;
package DBM_Filter::my_filter2;
sub Filter
{
my @opts = @_;
...
return (
sub Store { ... },
sub Fetch { ... } );
}
1;
```
DESCRIPTION
-----------
This module provides an interface that allows filters to be applied to tied Hashes associated with DBM files. It builds on the DBM Filter hooks that are present in all the \*DB\*\_File modules included with the standard Perl source distribution from version 5.6.1 onwards. In addition to the \*DB\*\_File modules distributed with Perl, the BerkeleyDB module, available on CPAN, supports the DBM Filter hooks. See <perldbmfilter> for more details on the DBM Filter hooks.
What is a DBM Filter?
----------------------
A DBM Filter allows the keys and/or values in a tied hash to be modified by some user-defined code just before it is written to the DBM file and just after it is read back from the DBM file. For example, this snippet of code
```
$some_hash{"abc"} = 42;
```
could potentially trigger two filters, one for the writing of the key "abc" and another for writing the value 42. Similarly, this snippet
```
my ($key, $value) = each %some_hash
```
will trigger two filters, one for the reading of the key and one for the reading of the value.
Like the existing DBM Filter functionality, this module arranges for the `$_` variable to be populated with the key or value that a filter will check. This usually means that most DBM filters tend to be very short.
###
So what's new?
The main enhancements over the standard DBM Filter hooks are:
* A cleaner interface.
* The ability to easily apply multiple filters to a single DBM file.
* The ability to create "canned" filters. These allow commonly used filters to be packaged into a stand-alone module.
METHODS
-------
This module will arrange for the following methods to be available via the object returned from the `tie` call.
###
$db->Filter\_Push() / $db->Filter\_Key\_Push() / $db->Filter\_Value\_Push()
Add a filter to filter stack for the database, `$db`. The three formats vary only in whether they apply to the DBM key, the DBM value or both.
Filter\_Push The filter is applied to *both* keys and values.
Filter\_Key\_Push The filter is applied to the key *only*.
Filter\_Value\_Push The filter is applied to the value *only*.
###
$db->Filter\_Pop()
Removes the last filter that was applied to the DBM file associated with `$db`, if present.
###
$db->Filtered()
Returns TRUE if there are any filters applied to the DBM associated with `$db`. Otherwise returns FALSE.
Writing a Filter
-----------------
Filters can be created in two main ways
###
Immediate Filters
An immediate filter allows you to specify the filter code to be used at the point where the filter is applied to a dbm. In this mode the Filter\_\*\_Push methods expects to receive exactly two parameters.
```
my $db = tie %hash, 'SDBM_File', ...
$db->Filter_Push( Store => sub { },
Fetch => sub { });
```
The code reference associated with `Store` will be called before any key/value is written to the database and the code reference associated with `Fetch` will be called after any key/value is read from the database.
For example, here is a sample filter that adds a trailing NULL character to all strings before they are written to the DBM file, and removes the trailing NULL when they are read from the DBM file
```
my $db = tie %hash, 'SDBM_File', ...
$db->Filter_Push( Store => sub { $_ .= "\x00" ; },
Fetch => sub { s/\x00$// ; });
```
Points to note:
1. Both the Store and Fetch filters manipulate `$_`.
###
Canned Filters
Immediate filters are useful for one-off situations. For more generic problems it can be useful to package the filter up in its own module.
The usage is for a canned filter is:
```
$db->Filter_Push("name", params)
```
where
"name" is the name of the module to load. If the string specified does not contain the package separator characters "::", it is assumed to refer to the full module name "DBM\_Filter::name". This means that the full names for canned filters, "null" and "utf8", included with this module are:
```
DBM_Filter::null
DBM_Filter::utf8
```
params any optional parameters that need to be sent to the filter. See the encode filter for an example of a module that uses parameters.
The module that implements the canned filter can take one of two forms. Here is a template for the first
```
package DBM_Filter::null ;
use strict;
use warnings;
sub Store
{
# store code here
}
sub Fetch
{
# fetch code here
}
1;
```
Notes:
1. The package name uses the `DBM_Filter::` prefix.
2. The module *must* have both a Store and a Fetch method. If only one is present, or neither are present, a fatal error will be thrown.
The second form allows the filter to hold state information using a closure, thus:
```
package DBM_Filter::encoding ;
use strict;
use warnings;
sub Filter
{
my @params = @_ ;
...
return {
Store => sub { $_ = $encoding->encode($_) },
Fetch => sub { $_ = $encoding->decode($_) }
} ;
}
1;
```
In this instance the "Store" and "Fetch" methods are encapsulated inside a "Filter" method.
Filters Included
-----------------
A number of canned filers are provided with this module. They cover a number of the main areas that filters are needed when interfacing with DBM files. They also act as templates for your own filters.
The filter included are:
* utf8
This module will ensure that all data written to the DBM will be encoded in UTF-8.
This module needs the Encode module.
* encode
Allows you to choose the character encoding will be store in the DBM file.
* compress
This filter will compress all data before it is written to the database and uncompressed it on reading.
This module needs Compress::Zlib.
* int32
This module is used when interoperating with a C/C++ application that uses a C int as either the key and/or value in the DBM file.
* null
This module ensures that all data written to the DBM file is null terminated. This is useful when you have a perl script that needs to interoperate with a DBM file that a C program also uses. A fairly common issue is for the C application to include the terminating null in a string when it writes to the DBM file. This filter will ensure that all data written to the DBM file can be read by the C application.
NOTES
-----
###
Maintain Round Trip Integrity
When writing a DBM filter it is *very* important to ensure that it is possible to retrieve all data that you have written when the DBM filter is in place. In practice, this means that whatever transformation is applied to the data in the Store method, the *exact* inverse operation should be applied in the Fetch method.
If you don't provide an exact inverse transformation, you will find that code like this will not behave as you expect.
```
while (my ($k, $v) = each %hash)
{
...
}
```
Depending on the transformation, you will find that one or more of the following will happen
1. The loop will never terminate.
2. Too few records will be retrieved.
3. Too many will be retrieved.
4. The loop will do the right thing for a while, but it will unexpectedly fail.
###
Don't mix filtered & non-filtered data in the same database file.
This is just a restatement of the previous section. Unless you are completely certain you know what you are doing, avoid mixing filtered & non-filtered data.
EXAMPLE
-------
Say you need to interoperate with a legacy C application that stores keys as C ints and the values and null terminated UTF-8 strings. Here is how you would set that up
```
my $db = tie %hash, 'SDBM_File', ...
$db->Filter_Key_Push('int32') ;
$db->Filter_Value_Push('utf8');
$db->Filter_Value_Push('null');
```
SEE ALSO
---------
<DB\_File>, [GDBM\_File](gdbm_file), [NDBM\_File](ndbm_file), [ODBM\_File](odbm_file), [SDBM\_File](sdbm_file), <perldbmfilter>
AUTHOR
------
Paul Marquess <[email protected]>
perl Unicode::Collate::CJK::Big5 Unicode::Collate::CJK::Big5
===========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::Big5 - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::Big5;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::Big5::weightBig5
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::Big5` provides `weightBig5()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's big5han ordering.
SEE ALSO
---------
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
<Unicode::Collate>
<Unicode::Collate::Locale>
perl perluniprops perluniprops
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Properties accessible through \p{} and \P{}](#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D)
+ [Legal \p{} and \P{} constructs that match no characters](#Legal-%5Cp%7B%7D-and-%5CP%7B%7D-constructs-that-match-no-characters)
* [Properties accessible through Unicode::UCD](#Properties-accessible-through-Unicode::UCD)
* [Properties accessible through other means](#Properties-accessible-through-other-means)
* [Unicode character properties that are NOT accepted by Perl](#Unicode-character-properties-that-are-NOT-accepted-by-Perl)
* [Other information in the Unicode data base](#Other-information-in-the-Unicode-data-base)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perluniprops - Index of Unicode Version 14.0.0 character properties in Perl
DESCRIPTION
-----------
This document provides information about the portion of the Unicode database that deals with character properties, that is the portion that is defined on single code points. (["Other information in the Unicode data base"](#Other-information-in-the-Unicode-data-base) below briefly mentions other data that Unicode provides.)
Perl can provide access to all non-provisional Unicode character properties, though not all are enabled by default. The omitted ones are the Unihan properties and certain deprecated or Unicode-internal properties. (An installation may choose to recompile Perl's tables to change this. See ["Unicode character properties that are NOT accepted by Perl"](#Unicode-character-properties-that-are-NOT-accepted-by-Perl).)
For most purposes, access to Unicode properties from the Perl core is through regular expression matches, as described in the next section. For some special purposes, and to access the properties that are not suitable for regular expression matching, all the Unicode character properties that Perl handles are accessible via the standard <Unicode::UCD> module, as described in the section ["Properties accessible through Unicode::UCD"](#Properties-accessible-through-Unicode%3A%3AUCD).
Perl also provides some additional extensions and short-cut synonyms for Unicode properties.
This document merely lists all available properties and does not attempt to explain what each property really means. There is a brief description of each Perl extension; see ["Other Properties" in perlunicode](perlunicode#Other-Properties) for more information on these. There is some detail about Blocks, Scripts, General\_Category, and Bidi\_Class in <perlunicode>, but to find out about the intricacies of the official Unicode properties, refer to the Unicode standard. A good starting place is <http://www.unicode.org/reports/tr44/>.
Note that you can define your own properties; see ["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties).
Properties accessible through `\p{}` and `\P{}`
------------------------------------------------
The Perl regular expression `\p{}` and `\P{}` constructs give access to most of the Unicode character properties. The table below shows all these constructs, both single and compound forms.
**Compound forms** consist of two components, separated by an equals sign or a colon. The first component is the property name, and the second component is the particular value of the property to match against, for example, `\p{Script_Extensions: Greek}` and `\p{Script_Extensions=Greek}` both mean to match characters whose Script\_Extensions property value is Greek. (`Script_Extensions` is an improved version of the `Script` property.)
**Single forms**, like `\p{Greek}`, are mostly Perl-defined shortcuts for their equivalent compound forms. The table shows these equivalences. (In our example, `\p{Greek}` is a just a shortcut for `\p{Script_Extensions=Greek}`). There are also a few Perl-defined single forms that are not shortcuts for a compound form. One such is `\p{Word}`. These are also listed in the table.
In parsing these constructs, Perl always ignores Upper/lower case differences everywhere within the {braces}. Thus `\p{Greek}` means the same thing as `\p{greek}`. But note that changing the case of the `"p"` or `"P"` before the left brace completely changes the meaning of the construct, from "match" (for `\p{}`) to "doesn't match" (for `\P{}`). Casing in this document is for improved legibility.
Also, white space, hyphens, and underscores are normally ignored everywhere between the {braces}, and hence can be freely added or removed even if the `/x` modifier hasn't been specified on the regular expression. But in the table below a '**T**' at the beginning of an entry means that tighter (stricter) rules are used for that entry:
Single form (`\p{name}`) tighter rules: White space, hyphens, and underscores ARE significant except for:
+ white space adjacent to a non-word character
+ underscores separating digits in numbers
That means, for example, that you can freely add or remove white space adjacent to (but within) the braces without affecting the meaning.
Compound form (`\p{name=value}` or `\p{name:value}`) tighter rules: The tighter rules given above for the single form apply to everything to the right of the colon or equals; the looser rules still apply to everything to the left.
That means, for example, that you can freely add or remove white space adjacent to (but within) the braces and the colon or equal sign.
Some properties are considered obsolete by Unicode, but still available. There are several varieties of obsolescence:
Stabilized A property may be stabilized. Such a determination does not indicate that the property should or should not be used; instead it is a declaration that the property will not be maintained nor extended for newly encoded characters. Such properties are marked with an '**S**' in the table.
Deprecated A property may be deprecated, perhaps because its original intent has been replaced by another property, or because its specification was somehow defective. This means that its use is strongly discouraged, so much so that a warning will be issued if used, unless the regular expression is in the scope of a `no warnings 'deprecated'` statement. A '**D**' flags each such entry in the table, and the entry there for the longest, most descriptive version of the property will give the reason it is deprecated, and perhaps advice. Perl may issue such a warning, even for properties that aren't officially deprecated by Unicode, when there used to be characters or code points that were matched by them, but no longer. This is to warn you that your program may not work like it did on earlier Unicode releases.
A deprecated property may be made unavailable in a future Perl version, so it is best to move away from them.
A deprecated property may also be stabilized, but this fact is not shown.
Obsolete Properties marked with an '**O**' in the table are considered (plain) obsolete. Generally this designation is given to properties that Unicode once used for internal purposes (but not any longer).
Discouraged This is not actually a Unicode-specified obsolescence, but applies to certain Perl extensions that are present for backwards compatibility, but are discouraged from being used. These are not obsolete, but their meanings are not stable. Future Unicode versions could force any of these extensions to be removed without warning, replaced by another property with the same name that means something different. An '**X**' flags each such entry in the table. Use the equivalent shown instead.
In particular, matches in the Block property have single forms defined by Perl that begin with `"In_"`, `"Is_`, or even with no prefix at all, Like all **DISCOURAGED** forms, these are not stable. For example, `\p{Block=Deseret}` can currently be written as `\p{In_Deseret}`, `\p{Is_Deseret}`, or `\p{Deseret}`. But, a new Unicode version may come along that would force Perl to change the meaning of one or more of these, and your program would no longer be correct. Currently there are no such conflicts with the form that begins `"In_"`, but there are many with the other two shortcuts, and Unicode continues to define new properties that begin with `"In"`, so it's quite possible that a conflict will occur in the future. The compound form is guaranteed to not become obsolete, and its meaning is clearer anyway. See ["Blocks" in perlunicode](perlunicode#Blocks) for more information about this.
User-defined properties must begin with "In" or "Is". These override any Unicode property of the same name.
The table below has two columns. The left column contains the `\p{}` constructs to look up, possibly preceded by the flags mentioned above; and the right column contains information about them, like a description, or synonyms. The table shows both the single and compound forms for each property that has them. If the left column is a short name for a property, the right column will give its longer, more descriptive name; and if the left column is the longest name, the right column will show any equivalent shortest name, in both single and compound forms if applicable.
If braces are not needed to specify a property (e.g., `\pL`), the left column contains both forms, with and without braces.
The right column will also caution you if a property means something different than what might normally be expected.
All single forms are Perl extensions; a few compound forms are as well, and are noted as such.
Numbers in (parentheses) indicate the total number of Unicode code points matched by the property. For the entries that give the longest, most descriptive version of the property, the count is followed by a list of some of the code points matched by it. The list includes all the matched characters in the 0-255 range, enclosed in the familiar [brackets] the same as a regular expression bracketed character class. Following that, the next few higher matching ranges are also given. To avoid visual ambiguity, the SPACE character is represented as `\x20`.
For emphasis, those properties that match no code points at all are listed as well in a separate section following the table.
Most properties match the same code points regardless of whether `"/i"` case-insensitive matching is specified or not. But a few properties are affected. These are shown with the notation `(/i= *other\_property*)` in the second column. Under case-insensitive matching they match the same code pode points as the property *other\_property*.
There is no description given for most non-Perl defined properties (See <http://www.unicode.org/reports/tr44/> for that).
For compactness, '**\***' is used as a wildcard instead of showing all possible combinations. For example, entries like:
```
\p{Gc: *} \p{General_Category: *}
```
mean that 'Gc' is a synonym for 'General\_Category', and anything that is valid for the latter is also valid for the former. Similarly,
```
\p{Is_*} \p{*}
```
means that if and only if, for example, `\p{Foo}` exists, then `\p{Is_Foo}` and `\p{IsFoo}` are also valid and all mean the same thing. And similarly, `\p{Foo=Bar}` means the same as `\p{Is_Foo=Bar}` and `\p{IsFoo=Bar}`. "\*" here is restricted to something not beginning with an underscore.
Also, in binary properties, 'Yes', 'T', and 'True' are all synonyms for 'Y'. And 'No', 'F', and 'False' are all synonyms for 'N'. The table shows 'Y\*' and 'N\*' to indicate this, and doesn't have separate entries for the other possibilities. Note that not all properties which have values 'Yes' and 'No' are binary, and they have all their values spelled out without using this wild card, and a `NOT` clause in their description that highlights their not being binary. These also require the compound form to match them, whereas true binary properties have both single and compound forms available.
Note that all non-essential underscores are removed in the display of the short names below.
**Legend summary:**
**\*** is a wild-card
**(\d+)** in the info column gives the number of Unicode code points matched by this property.
**D** means this is deprecated.
**O** means this is obsolete.
**S** means this is stabilized.
**T** means tighter (stricter) name matching applies.
**X** means use of this form is discouraged, and may not be stable.
```
NAME INFO
\p{Adlam} \p{Script_Extensions=Adlam} (Short:
\p{Adlm}; NOT \p{Block=Adlam}) (90)
\p{Adlm} \p{Adlam} (= \p{Script_Extensions=Adlam})
(NOT \p{Block=Adlam}) (90)
X \p{Aegean_Numbers} \p{Block=Aegean_Numbers} (64)
T \p{Age: 1.1} \p{Age=V1_1} (33_979)
\p{Age: V1_1} Code point's usage introduced in version
1.1 (33_979: U+0000..01F5, U+01FA..0217,
U+0250..02A8, U+02B0..02DE,
U+02E0..02E9, U+0300..0345 ...)
T \p{Age: 2.0} \p{Age=V2_0} (144_521)
\p{Age: V2_0} Code point's usage was introduced in
version 2.0; See also Property
'Present_In' (144_521: U+0591..05A1,
U+05A3..05AF, U+05C4, U+0F00..0F47,
U+0F49..0F69, U+0F71..0F8B ...)
T \p{Age: 2.1} \p{Age=V2_1} (2)
\p{Age: V2_1} Code point's usage was introduced in
version 2.1; See also Property
'Present_In' (2: U+20AC, U+FFFC)
T \p{Age: 3.0} \p{Age=V3_0} (10_307)
\p{Age: V3_0} Code point's usage was introduced in
version 3.0; See also Property
'Present_In' (10_307: U+01F6..01F9,
U+0218..021F, U+0222..0233,
U+02A9..02AD, U+02DF, U+02EA..02EE ...)
T \p{Age: 3.1} \p{Age=V3_1} (44_978)
\p{Age: V3_1} Code point's usage was introduced in
version 3.1; See also Property
'Present_In' (44_978: U+03F4..03F5,
U+FDD0..FDEF, U+10300..1031E,
U+10320..10323, U+10330..1034A,
U+10400..10425 ...)
T \p{Age: 3.2} \p{Age=V3_2} (1016)
\p{Age: V3_2} Code point's usage was introduced in
version 3.2; See also Property
'Present_In' (1016: U+0220, U+034F,
U+0363..036F, U+03D8..03D9, U+03F6,
U+048A..048B ...)
T \p{Age: 4.0} \p{Age=V4_0} (1226)
\p{Age: V4_0} Code point's usage was introduced in
version 4.0; See also Property
'Present_In' (1226: U+0221,
U+0234..0236, U+02AE..02AF,
U+02EF..02FF, U+0350..0357, U+035D..035F
...)
T \p{Age: 4.1} \p{Age=V4_1} (1273)
\p{Age: V4_1} Code point's usage was introduced in
version 4.1; See also Property
'Present_In' (1273: U+0237..0241,
U+0358..035C, U+03FC..03FF,
U+04F6..04F7, U+05A2, U+05C5..05C7 ...)
T \p{Age: 5.0} \p{Age=V5_0} (1369)
\p{Age: V5_0} Code point's usage was introduced in
version 5.0; See also Property
'Present_In' (1369: U+0242..024F,
U+037B..037D, U+04CF, U+04FA..04FF,
U+0510..0513, U+05BA ...)
T \p{Age: 5.1} \p{Age=V5_1} (1624)
\p{Age: V5_1} Code point's usage was introduced in
version 5.1; See also Property
'Present_In' (1624: U+0370..0373,
U+0376..0377, U+03CF, U+0487,
U+0514..0523, U+0606..060A ...)
T \p{Age: 5.2} \p{Age=V5_2} (6648)
\p{Age: V5_2} Code point's usage was introduced in
version 5.2; See also Property
'Present_In' (6648: U+0524..0525,
U+0800..082D, U+0830..083E, U+0900,
U+094E, U+0955 ...)
T \p{Age: 6.0} \p{Age=V6_0} (2088)
\p{Age: V6_0} Code point's usage was introduced in
version 6.0; See also Property
'Present_In' (2088: U+0526..0527,
U+0620, U+065F, U+0840..085B, U+085E,
U+093A..093B ...)
T \p{Age: 6.1} \p{Age=V6_1} (732)
\p{Age: V6_1} Code point's usage was introduced in
version 6.1; See also Property
'Present_In' (732: U+058F, U+0604,
U+08A0, U+08A2..08AC, U+08E4..08FE,
U+0AF0 ...)
T \p{Age: 6.2} \p{Age=V6_2} (1)
\p{Age: V6_2} Code point's usage was introduced in
version 6.2; See also Property
'Present_In' (1: U+20BA)
T \p{Age: 6.3} \p{Age=V6_3} (5)
\p{Age: V6_3} Code point's usage was introduced in
version 6.3; See also Property
'Present_In' (5: U+061C, U+2066..2069)
T \p{Age: 7.0} \p{Age=V7_0} (2834)
\p{Age: V7_0} Code point's usage was introduced in
version 7.0; See also Property
'Present_In' (2834: U+037F,
U+0528..052F, U+058D..058E, U+0605,
U+08A1, U+08AD..08B2 ...)
T \p{Age: 8.0} \p{Age=V8_0} (7716)
\p{Age: V8_0} Code point's usage was introduced in
version 8.0; See also Property
'Present_In' (7716: U+08B3..08B4,
U+08E3, U+0AF9, U+0C5A, U+0D5F, U+13F5
...)
T \p{Age: 9.0} \p{Age=V9_0} (7500)
\p{Age: V9_0} Code point's usage was introduced in
version 9.0; See also Property
'Present_In' (7500: U+08B6..08BD,
U+08D4..08E2, U+0C80, U+0D4F,
U+0D54..0D56, U+0D58..0D5E ...)
T \p{Age: 10.0} \p{Age=V10_0} (8518)
\p{Age: V10_0} Code point's usage was introduced in
version 10.0; See also Property
'Present_In' (8518: U+0860..086A,
U+09FC..09FD, U+0AFA..0AFF, U+0D00,
U+0D3B..0D3C, U+1CF7 ...)
T \p{Age: 11.0} \p{Age=V11_0} (684)
\p{Age: V11_0} Code point's usage was introduced in
version 11.0; See also Property
'Present_In' (684: U+0560, U+0588,
U+05EF, U+07FD..07FF, U+08D3, U+09FE ...)
T \p{Age: 12.0} \p{Age=V12_0} (554)
\p{Age: V12_0} Code point's usage was introduced in
version 12.0; See also Property
'Present_In' (554: U+0C77, U+0E86,
U+0E89, U+0E8C, U+0E8E..0E93, U+0E98 ...)
T \p{Age: 12.1} \p{Age=V12_1} (1)
\p{Age: V12_1} Code point's usage was introduced in
version 12.1; See also Property
'Present_In' (1: U+32FF)
T \p{Age: 13.0} \p{Age=V13_0} (5930)
\p{Age: V13_0} Code point's usage was introduced in
version 13.0; See also Property
'Present_In' (5930: U+08BE..08C7,
U+0B55, U+0D04, U+0D81, U+1ABF..1AC0,
U+2B97 ...)
T \p{Age: 14.0} \p{Age=V14_0} (838)
\p{Age: V14_0} Code point's usage was introduced in
version 14.0; See also Property
'Present_In' (838: U+061D, U+0870..088E,
U+0890..0891, U+0898..089F, U+08B5,
U+08C8..08D2 ...)
\p{Age: NA} \p{Age=Unassigned} (829_768 plus all
above-Unicode code points)
\p{Age: Unassigned} Code point's usage has not been assigned
in any Unicode release thus far.
(Short: \p{Age=NA}) (829_768 plus all above-Unicode code points:
U+0378..0379, U+0380..0383, U+038B,
U+038D, U+03A2, U+0530 ...)
\p{Aghb} \p{Caucasian_Albanian} (=
\p{Script_Extensions=
Caucasian_Albanian}) (NOT \p{Block=
Caucasian_Albanian}) (53)
\p{AHex} \p{PosixXDigit} (= \p{ASCII_Hex_Digit=Y})
(22)
\p{AHex: *} \p{ASCII_Hex_Digit: *}
\p{Ahom} \p{Script_Extensions=Ahom} (NOT \p{Block=
Ahom}) (65)
X \p{Alchemical} \p{Alchemical_Symbols} (= \p{Block=
Alchemical_Symbols}) (128)
X \p{Alchemical_Symbols} \p{Block=Alchemical_Symbols} (Short:
\p{InAlchemical}) (128)
\p{All} All code points, including those above
Unicode. Same as qr/./s (1_114_112 plus
all above-Unicode code points:
U+0000..infinity)
\p{Alnum} \p{XPosixAlnum} (134_056)
\p{Alpha} \p{XPosixAlpha} (= \p{Alphabetic=Y})
(133_396)
\p{Alpha: *} \p{Alphabetic: *}
\p{Alphabetic} \p{XPosixAlpha} (= \p{Alphabetic=Y})
(133_396)
\p{Alphabetic: N*} (Short: \p{Alpha=N}, \P{Alpha}) (980_716
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=
>?\@\[\\\]\^_`\{\|\}~\x7f-\xa9\xab-\xb4
\xb6-\xb9\xbb-\xbf\xd7\xf7],
U+02C2..02C5, U+02D2..02DF,
U+02E5..02EB, U+02ED, U+02EF..0344 ...)
\p{Alphabetic: Y*} (Short: \p{Alpha=Y}, \p{Alpha}) (133_396:
[A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6
\xf8-\xff], U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
X \p{Alphabetic_PF} \p{Alphabetic_Presentation_Forms} (=
\p{Block=Alphabetic_Presentation_Forms})
(80)
X \p{Alphabetic_Presentation_Forms} \p{Block=
Alphabetic_Presentation_Forms} (Short:
\p{InAlphabeticPF}) (80)
\p{Anatolian_Hieroglyphs} \p{Script_Extensions=
Anatolian_Hieroglyphs} (Short: \p{Hluw};
NOT \p{Block=Anatolian_Hieroglyphs})
(583)
X \p{Ancient_Greek_Music} \p{Ancient_Greek_Musical_Notation} (=
\p{Block=
Ancient_Greek_Musical_Notation}) (80)
X \p{Ancient_Greek_Musical_Notation} \p{Block=
Ancient_Greek_Musical_Notation} (Short:
\p{InAncientGreekMusic}) (80)
X \p{Ancient_Greek_Numbers} \p{Block=Ancient_Greek_Numbers} (80)
X \p{Ancient_Symbols} \p{Block=Ancient_Symbols} (64)
\p{Any} All Unicode code points (1_114_112:
U+0000..10FFFF)
\p{Arab} \p{Arabic} (= \p{Script_Extensions=
Arabic}) (NOT \p{Block=Arabic}) (1411)
\p{Arabic} \p{Script_Extensions=Arabic} (Short:
\p{Arab}; NOT \p{Block=Arabic}) (1411)
X \p{Arabic_Ext_A} \p{Arabic_Extended_A} (= \p{Block=
Arabic_Extended_A}) (96)
X \p{Arabic_Ext_B} \p{Arabic_Extended_B} (= \p{Block=
Arabic_Extended_B}) (48)
X \p{Arabic_Extended_A} \p{Block=Arabic_Extended_A} (Short:
\p{InArabicExtA}) (96)
X \p{Arabic_Extended_B} \p{Block=Arabic_Extended_B} (Short:
\p{InArabicExtB}) (48)
X \p{Arabic_Math} \p{Arabic_Mathematical_Alphabetic_Symbols}
(= \p{Block=
Arabic_Mathematical_Alphabetic_Symbols})
(256)
X \p{Arabic_Mathematical_Alphabetic_Symbols} \p{Block=
Arabic_Mathematical_Alphabetic_Symbols}
(Short: \p{InArabicMath}) (256)
X \p{Arabic_PF_A} \p{Arabic_Presentation_Forms_A} (=
\p{Block=Arabic_Presentation_Forms_A})
(688)
X \p{Arabic_PF_B} \p{Arabic_Presentation_Forms_B} (=
\p{Block=Arabic_Presentation_Forms_B})
(144)
X \p{Arabic_Presentation_Forms_A} \p{Block=
Arabic_Presentation_Forms_A} (Short:
\p{InArabicPFA}) (688)
X \p{Arabic_Presentation_Forms_B} \p{Block=
Arabic_Presentation_Forms_B} (Short:
\p{InArabicPFB}) (144)
X \p{Arabic_Sup} \p{Arabic_Supplement} (= \p{Block=
Arabic_Supplement}) (48)
X \p{Arabic_Supplement} \p{Block=Arabic_Supplement} (Short:
\p{InArabicSup}) (48)
\p{Armenian} \p{Script_Extensions=Armenian} (Short:
\p{Armn}; NOT \p{Block=Armenian}) (96)
\p{Armi} \p{Imperial_Aramaic} (=
\p{Script_Extensions=Imperial_Aramaic})
(NOT \p{Block=Imperial_Aramaic}) (31)
\p{Armn} \p{Armenian} (= \p{Script_Extensions=
Armenian}) (NOT \p{Block=Armenian}) (96)
X \p{Arrows} \p{Block=Arrows} (112)
\p{ASCII} \p{Block=Basic_Latin} (128)
\p{ASCII_Hex_Digit} \p{PosixXDigit} (= \p{ASCII_Hex_Digit=Y})
(22)
\p{ASCII_Hex_Digit: N*} (Short: \p{AHex=N}, \P{AHex}) (1_114_090
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/:;<=>?
\@G-Z\[\\\]\^_`g-z\{\|\}~\x7f-\xff],
U+0100..infinity)
\p{ASCII_Hex_Digit: Y*} (Short: \p{AHex=Y}, \p{AHex}) (22: [0-9A-
Fa-f])
\p{Assigned} All assigned code points (284_278:
U+0000..0377, U+037A..037F,
U+0384..038A, U+038C, U+038E..03A1,
U+03A3..052F ...)
\p{Avestan} \p{Script_Extensions=Avestan} (Short:
\p{Avst}; NOT \p{Block=Avestan}) (61)
\p{Avst} \p{Avestan} (= \p{Script_Extensions=
Avestan}) (NOT \p{Block=Avestan}) (61)
\p{Bali} \p{Balinese} (= \p{Script_Extensions=
Balinese}) (NOT \p{Block=Balinese}) (124)
\p{Balinese} \p{Script_Extensions=Balinese} (Short:
\p{Bali}; NOT \p{Block=Balinese}) (124)
\p{Bamu} \p{Bamum} (= \p{Script_Extensions=Bamum})
(NOT \p{Block=Bamum}) (657)
\p{Bamum} \p{Script_Extensions=Bamum} (Short:
\p{Bamu}; NOT \p{Block=Bamum}) (657)
X \p{Bamum_Sup} \p{Bamum_Supplement} (= \p{Block=
Bamum_Supplement}) (576)
X \p{Bamum_Supplement} \p{Block=Bamum_Supplement} (Short:
\p{InBamumSup}) (576)
X \p{Basic_Latin} \p{ASCII} (= \p{Block=Basic_Latin}) (128)
\p{Bass} \p{Bassa_Vah} (= \p{Script_Extensions=
Bassa_Vah}) (NOT \p{Block=Bassa_Vah})
(36)
\p{Bassa_Vah} \p{Script_Extensions=Bassa_Vah} (Short:
\p{Bass}; NOT \p{Block=Bassa_Vah}) (36)
\p{Batak} \p{Script_Extensions=Batak} (Short:
\p{Batk}; NOT \p{Block=Batak}) (56)
\p{Batk} \p{Batak} (= \p{Script_Extensions=Batak})
(NOT \p{Block=Batak}) (56)
\p{Bc: *} \p{Bidi_Class: *}
\p{Beng} \p{Bengali} (= \p{Script_Extensions=
Bengali}) (NOT \p{Block=Bengali}) (113)
\p{Bengali} \p{Script_Extensions=Bengali} (Short:
\p{Beng}; NOT \p{Block=Bengali}) (113)
\p{Bhaiksuki} \p{Script_Extensions=Bhaiksuki} (Short:
\p{Bhks}; NOT \p{Block=Bhaiksuki}) (97)
\p{Bhks} \p{Bhaiksuki} (= \p{Script_Extensions=
Bhaiksuki}) (NOT \p{Block=Bhaiksuki})
(97)
\p{Bidi_C} \p{Bidi_Control} (= \p{Bidi_Control=Y})
(12)
\p{Bidi_C: *} \p{Bidi_Control: *}
\p{Bidi_Class: AL} \p{Bidi_Class=Arabic_Letter} (1708)
\p{Bidi_Class: AN} \p{Bidi_Class=Arabic_Number} (63)
\p{Bidi_Class: Arabic_Letter} (Short: \p{Bc=AL}) (1708: U+0608,
U+060B, U+060D, U+061B..064A,
U+066D..066F, U+0671..06D5 ...)
\p{Bidi_Class: Arabic_Number} (Short: \p{Bc=AN}) (63:
U+0600..0605, U+0660..0669,
U+066B..066C, U+06DD, U+0890..0891,
U+08E2 ...)
\p{Bidi_Class: B} \p{Bidi_Class=Paragraph_Separator} (7)
\p{Bidi_Class: BN} \p{Bidi_Class=Boundary_Neutral} (4016)
\p{Bidi_Class: Boundary_Neutral} (Short: \p{Bc=BN}) (4016: [^\t\n
\cK\f\r\x1c-\x7e\x85\xa0-\xac\xae-\xff],
U+180E, U+200B..200D, U+2060..2065,
U+206A..206F, U+FDD0..FDEF ...)
\p{Bidi_Class: Common_Separator} (Short: \p{Bc=CS}) (15: [,.\/:
\xa0], U+060C, U+202F, U+2044, U+FE50,
U+FE52 ...)
\p{Bidi_Class: CS} \p{Bidi_Class=Common_Separator} (15)
\p{Bidi_Class: EN} \p{Bidi_Class=European_Number} (168)
\p{Bidi_Class: ES} \p{Bidi_Class=European_Separator} (12)
\p{Bidi_Class: ET} \p{Bidi_Class=European_Terminator} (92)
\p{Bidi_Class: European_Number} (Short: \p{Bc=EN}) (168: [0-9\xb2-
\xb3\xb9], U+06F0..06F9, U+2070,
U+2074..2079, U+2080..2089, U+2488..249B
...)
\p{Bidi_Class: European_Separator} (Short: \p{Bc=ES}) (12: [+\-],
U+207A..207B, U+208A..208B, U+2212,
U+FB29, U+FE62..FE63 ...)
\p{Bidi_Class: European_Terminator} (Short: \p{Bc=ET}) (92: [#\$
\%\xa2-\xa5\xb0-\xb1], U+058F,
U+0609..060A, U+066A, U+09F2..09F3,
U+09FB ...)
\p{Bidi_Class: First_Strong_Isolate} (Short: \p{Bc=FSI}) (1:
U+2068)
\p{Bidi_Class: FSI} \p{Bidi_Class=First_Strong_Isolate} (1)
\p{Bidi_Class: L} \p{Bidi_Class=Left_To_Right} (1_096_333
plus all above-Unicode code points)
\p{Bidi_Class: Left_To_Right} (Short: \p{Bc=L}) (1_096_333 plus
all above-Unicode code points: [A-Za-z
\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-
\xff], U+0100..02B8, U+02BB..02C1,
U+02D0..02D1, U+02E0..02E4, U+02EE ...)
\p{Bidi_Class: Left_To_Right_Embedding} (Short: \p{Bc=LRE}) (1:
U+202A)
\p{Bidi_Class: Left_To_Right_Isolate} (Short: \p{Bc=LRI}) (1:
U+2066)
\p{Bidi_Class: Left_To_Right_Override} (Short: \p{Bc=LRO}) (1:
U+202D)
\p{Bidi_Class: LRE} \p{Bidi_Class=Left_To_Right_Embedding} (1)
\p{Bidi_Class: LRI} \p{Bidi_Class=Left_To_Right_Isolate} (1)
\p{Bidi_Class: LRO} \p{Bidi_Class=Left_To_Right_Override} (1)
\p{Bidi_Class: Nonspacing_Mark} (Short: \p{Bc=NSM}) (1958:
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{Bidi_Class: NSM} \p{Bidi_Class=Nonspacing_Mark} (1958)
\p{Bidi_Class: ON} \p{Bidi_Class=Other_Neutral} (6000)
\p{Bidi_Class: Other_Neutral} (Short: \p{Bc=ON}) (6000: [!\"&\'
\(\)*;<=>?\@\[\\\]\^_`\{\|\}~\xa1\xa6-
\xa9\xab-\xac\xae-\xaf\xb4\xb6-\xb8\xbb-
\xbf\xd7\xf7], U+02B9..02BA,
U+02C2..02CF, U+02D2..02DF,
U+02E5..02ED, U+02EF..02FF ...)
\p{Bidi_Class: Paragraph_Separator} (Short: \p{Bc=B}) (7: [\n\r
\x1c-\x1e\x85], U+2029)
\p{Bidi_Class: PDF} \p{Bidi_Class=Pop_Directional_Format} (1)
\p{Bidi_Class: PDI} \p{Bidi_Class=Pop_Directional_Isolate} (1)
\p{Bidi_Class: Pop_Directional_Format} (Short: \p{Bc=PDF}) (1:
U+202C)
\p{Bidi_Class: Pop_Directional_Isolate} (Short: \p{Bc=PDI}) (1:
U+2069)
\p{Bidi_Class: R} \p{Bidi_Class=Right_To_Left} (3711)
\p{Bidi_Class: Right_To_Left} (Short: \p{Bc=R}) (3711: U+0590,
U+05BE, U+05C0, U+05C3, U+05C6,
U+05C8..05FF ...)
\p{Bidi_Class: Right_To_Left_Embedding} (Short: \p{Bc=RLE}) (1:
U+202B)
\p{Bidi_Class: Right_To_Left_Isolate} (Short: \p{Bc=RLI}) (1:
U+2067)
\p{Bidi_Class: Right_To_Left_Override} (Short: \p{Bc=RLO}) (1:
U+202E)
\p{Bidi_Class: RLE} \p{Bidi_Class=Right_To_Left_Embedding} (1)
\p{Bidi_Class: RLI} \p{Bidi_Class=Right_To_Left_Isolate} (1)
\p{Bidi_Class: RLO} \p{Bidi_Class=Right_To_Left_Override} (1)
\p{Bidi_Class: S} \p{Bidi_Class=Segment_Separator} (3)
\p{Bidi_Class: Segment_Separator} (Short: \p{Bc=S}) (3: [\t\cK
\x1f])
\p{Bidi_Class: White_Space} (Short: \p{Bc=WS}) (17: [\f\x20],
U+1680, U+2000..200A, U+2028, U+205F,
U+3000)
\p{Bidi_Class: WS} \p{Bidi_Class=White_Space} (17)
\p{Bidi_Control} \p{Bidi_Control=Y} (Short: \p{BidiC}) (12)
\p{Bidi_Control: N*} (Short: \p{BidiC=N}, \P{BidiC}) (1_114_100
plus all above-Unicode code points:
U+0000..061B, U+061D..200D,
U+2010..2029, U+202F..2065,
U+206A..infinity)
\p{Bidi_Control: Y*} (Short: \p{BidiC=Y}, \p{BidiC}) (12:
U+061C, U+200E..200F, U+202A..202E,
U+2066..2069)
\p{Bidi_M} \p{Bidi_Mirrored} (= \p{Bidi_Mirrored=Y})
(553)
\p{Bidi_M: *} \p{Bidi_Mirrored: *}
\p{Bidi_Mirrored} \p{Bidi_Mirrored=Y} (Short: \p{BidiM})
(553)
\p{Bidi_Mirrored: N*} (Short: \p{BidiM=N}, \P{BidiM}) (1_113_559
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'*+,\-.\/0-9:;=?\@A-
Z\\\^_`a-z\|~\x7f-\xaa\xac-\xba\xbc-
\xff], U+0100..0F39, U+0F3E..169A,
U+169D..2038, U+203B..2044, U+2047..207C
...)
\p{Bidi_Mirrored: Y*} (Short: \p{BidiM=Y}, \p{BidiM}) (553:
[\(\)<>\[\]\{\}\xab\xbb], U+0F3A..0F3D,
U+169B..169C, U+2039..203A,
U+2045..2046, U+207D..207E ...)
\p{Bidi_Paired_Bracket_Type: C} \p{Bidi_Paired_Bracket_Type=Close}
(64)
\p{Bidi_Paired_Bracket_Type: Close} (Short: \p{Bpt=C}) (64: [\)\]
\}], U+0F3B, U+0F3D, U+169C, U+2046,
U+207E ...)
\p{Bidi_Paired_Bracket_Type: N} \p{Bidi_Paired_Bracket_Type=None}
(1_113_984 plus all above-Unicode code
points)
\p{Bidi_Paired_Bracket_Type: None} (Short: \p{Bpt=N}) (1_113_984
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'*+,\-.\/0-9:;<=>?
\@A-Z\\\^_`a-z\|~\x7f-\xff],
U+0100..0F39, U+0F3E..169A,
U+169D..2044, U+2047..207C, U+207F..208C
...)
\p{Bidi_Paired_Bracket_Type: O} \p{Bidi_Paired_Bracket_Type=Open}
(64)
\p{Bidi_Paired_Bracket_Type: Open} (Short: \p{Bpt=O}) (64:
[\(\[\{], U+0F3A, U+0F3C, U+169B,
U+2045, U+207D ...)
\p{Blank} \p{XPosixBlank} (18)
\p{Blk: *} \p{Block: *}
\p{Block: Adlam} (NOT \p{Adlam} NOR \p{Is_Adlam}) (96:
U+1E900..1E95F)
\p{Block: Aegean_Numbers} (64: U+10100..1013F)
\p{Block: Ahom} (NOT \p{Ahom} NOR \p{Is_Ahom}) (80:
U+11700..1174F)
\p{Block: Alchemical} \p{Block=Alchemical_Symbols} (128)
\p{Block: Alchemical_Symbols} (Short: \p{Blk=Alchemical}) (128:
U+1F700..1F77F)
\p{Block: Alphabetic_PF} \p{Block=Alphabetic_Presentation_Forms}
(80)
\p{Block: Alphabetic_Presentation_Forms} (Short: \p{Blk=
AlphabeticPF}) (80: U+FB00..FB4F)
\p{Block: Anatolian_Hieroglyphs} (NOT \p{Anatolian_Hieroglyphs}
NOR \p{Is_Anatolian_Hieroglyphs}) (640:
U+14400..1467F)
\p{Block: Ancient_Greek_Music} \p{Block=
Ancient_Greek_Musical_Notation} (80)
\p{Block: Ancient_Greek_Musical_Notation} (Short: \p{Blk=
AncientGreekMusic}) (80: U+1D200..1D24F)
\p{Block: Ancient_Greek_Numbers} (80: U+10140..1018F)
\p{Block: Ancient_Symbols} (64: U+10190..101CF)
\p{Block: Arabic} (NOT \p{Arabic} NOR \p{Is_Arabic}) (256:
U+0600..06FF)
\p{Block: Arabic_Ext_A} \p{Block=Arabic_Extended_A} (96)
\p{Block: Arabic_Ext_B} \p{Block=Arabic_Extended_B} (48)
\p{Block: Arabic_Extended_A} (Short: \p{Blk=ArabicExtA}) (96:
U+08A0..08FF)
\p{Block: Arabic_Extended_B} (Short: \p{Blk=ArabicExtB}) (48:
U+0870..089F)
\p{Block: Arabic_Math} \p{Block=
Arabic_Mathematical_Alphabetic_Symbols}
(256)
\p{Block: Arabic_Mathematical_Alphabetic_Symbols} (Short: \p{Blk=
ArabicMath}) (256: U+1EE00..1EEFF)
\p{Block: Arabic_PF_A} \p{Block=Arabic_Presentation_Forms_A} (688)
\p{Block: Arabic_PF_B} \p{Block=Arabic_Presentation_Forms_B} (144)
\p{Block: Arabic_Presentation_Forms_A} (Short: \p{Blk=ArabicPFA})
(688: U+FB50..FDFF)
\p{Block: Arabic_Presentation_Forms_B} (Short: \p{Blk=ArabicPFB})
(144: U+FE70..FEFF)
\p{Block: Arabic_Sup} \p{Block=Arabic_Supplement} (48)
\p{Block: Arabic_Supplement} (Short: \p{Blk=ArabicSup}) (48:
U+0750..077F)
\p{Block: Armenian} (NOT \p{Armenian} NOR \p{Is_Armenian})
(96: U+0530..058F)
\p{Block: Arrows} (112: U+2190..21FF)
\p{Block: ASCII} \p{Block=Basic_Latin} (128)
\p{Block: Avestan} (NOT \p{Avestan} NOR \p{Is_Avestan}) (64:
U+10B00..10B3F)
\p{Block: Balinese} (NOT \p{Balinese} NOR \p{Is_Balinese})
(128: U+1B00..1B7F)
\p{Block: Bamum} (NOT \p{Bamum} NOR \p{Is_Bamum}) (96:
U+A6A0..A6FF)
\p{Block: Bamum_Sup} \p{Block=Bamum_Supplement} (576)
\p{Block: Bamum_Supplement} (Short: \p{Blk=BamumSup}) (576:
U+16800..16A3F)
\p{Block: Basic_Latin} (Short: \p{Blk=ASCII}) (128: [\x00-\x7f])
\p{Block: Bassa_Vah} (NOT \p{Bassa_Vah} NOR \p{Is_Bassa_Vah})
(48: U+16AD0..16AFF)
\p{Block: Batak} (NOT \p{Batak} NOR \p{Is_Batak}) (64:
U+1BC0..1BFF)
\p{Block: Bengali} (NOT \p{Bengali} NOR \p{Is_Bengali}) (128:
U+0980..09FF)
\p{Block: Bhaiksuki} (NOT \p{Bhaiksuki} NOR \p{Is_Bhaiksuki})
(112: U+11C00..11C6F)
\p{Block: Block_Elements} (32: U+2580..259F)
\p{Block: Bopomofo} (NOT \p{Bopomofo} NOR \p{Is_Bopomofo})
(48: U+3100..312F)
\p{Block: Bopomofo_Ext} \p{Block=Bopomofo_Extended} (32)
\p{Block: Bopomofo_Extended} (Short: \p{Blk=BopomofoExt}) (32:
U+31A0..31BF)
\p{Block: Box_Drawing} (128: U+2500..257F)
\p{Block: Brahmi} (NOT \p{Brahmi} NOR \p{Is_Brahmi}) (128:
U+11000..1107F)
\p{Block: Braille} \p{Block=Braille_Patterns} (256)
\p{Block: Braille_Patterns} (Short: \p{Blk=Braille}) (256:
U+2800..28FF)
\p{Block: Buginese} (NOT \p{Buginese} NOR \p{Is_Buginese})
(32: U+1A00..1A1F)
\p{Block: Buhid} (NOT \p{Buhid} NOR \p{Is_Buhid}) (32:
U+1740..175F)
\p{Block: Byzantine_Music} \p{Block=Byzantine_Musical_Symbols}
(256)
\p{Block: Byzantine_Musical_Symbols} (Short: \p{Blk=
ByzantineMusic}) (256: U+1D000..1D0FF)
\p{Block: Canadian_Syllabics} \p{Block=
Unified_Canadian_Aboriginal_Syllabics}
(640)
\p{Block: Carian} (NOT \p{Carian} NOR \p{Is_Carian}) (64:
U+102A0..102DF)
\p{Block: Caucasian_Albanian} (NOT \p{Caucasian_Albanian} NOR
\p{Is_Caucasian_Albanian}) (64:
U+10530..1056F)
\p{Block: Chakma} (NOT \p{Chakma} NOR \p{Is_Chakma}) (80:
U+11100..1114F)
\p{Block: Cham} (NOT \p{Cham} NOR \p{Is_Cham}) (96:
U+AA00..AA5F)
\p{Block: Cherokee} (NOT \p{Cherokee} NOR \p{Is_Cherokee})
(96: U+13A0..13FF)
\p{Block: Cherokee_Sup} \p{Block=Cherokee_Supplement} (80)
\p{Block: Cherokee_Supplement} (Short: \p{Blk=CherokeeSup}) (80:
U+AB70..ABBF)
\p{Block: Chess_Symbols} (112: U+1FA00..1FA6F)
\p{Block: Chorasmian} (NOT \p{Chorasmian} NOR \p{Is_Chorasmian})
(48: U+10FB0..10FDF)
\p{Block: CJK} \p{Block=CJK_Unified_Ideographs} (20_992)
\p{Block: CJK_Compat} \p{Block=CJK_Compatibility} (256)
\p{Block: CJK_Compat_Forms} \p{Block=CJK_Compatibility_Forms} (32)
\p{Block: CJK_Compat_Ideographs} \p{Block=
CJK_Compatibility_Ideographs} (512)
\p{Block: CJK_Compat_Ideographs_Sup} \p{Block=
CJK_Compatibility_Ideographs_Supplement}
(544)
\p{Block: CJK_Compatibility} (Short: \p{Blk=CJKCompat}) (256:
U+3300..33FF)
\p{Block: CJK_Compatibility_Forms} (Short: \p{Blk=CJKCompatForms})
(32: U+FE30..FE4F)
\p{Block: CJK_Compatibility_Ideographs} (Short: \p{Blk=
CJKCompatIdeographs}) (512: U+F900..FAFF)
\p{Block: CJK_Compatibility_Ideographs_Supplement} (Short: \p{Blk=
CJKCompatIdeographsSup}) (544:
U+2F800..2FA1F)
\p{Block: CJK_Ext_A} \p{Block=
CJK_Unified_Ideographs_Extension_A}
(6592)
\p{Block: CJK_Ext_B} \p{Block=
CJK_Unified_Ideographs_Extension_B}
(42_720)
\p{Block: CJK_Ext_C} \p{Block=
CJK_Unified_Ideographs_Extension_C}
(4160)
\p{Block: CJK_Ext_D} \p{Block=
CJK_Unified_Ideographs_Extension_D} (224)
\p{Block: CJK_Ext_E} \p{Block=
CJK_Unified_Ideographs_Extension_E}
(5776)
\p{Block: CJK_Ext_F} \p{Block=
CJK_Unified_Ideographs_Extension_F}
(7488)
\p{Block: CJK_Ext_G} \p{Block=
CJK_Unified_Ideographs_Extension_G}
(4944)
\p{Block: CJK_Radicals_Sup} \p{Block=CJK_Radicals_Supplement} (128)
\p{Block: CJK_Radicals_Supplement} (Short: \p{Blk=CJKRadicalsSup})
(128: U+2E80..2EFF)
\p{Block: CJK_Strokes} (48: U+31C0..31EF)
\p{Block: CJK_Symbols} \p{Block=CJK_Symbols_And_Punctuation} (64)
\p{Block: CJK_Symbols_And_Punctuation} (Short: \p{Blk=CJKSymbols})
(64: U+3000..303F)
\p{Block: CJK_Unified_Ideographs} (Short: \p{Blk=CJK}) (20_992:
U+4E00..9FFF)
\p{Block: CJK_Unified_Ideographs_Extension_A} (Short: \p{Blk=
CJKExtA}) (6592: U+3400..4DBF)
\p{Block: CJK_Unified_Ideographs_Extension_B} (Short: \p{Blk=
CJKExtB}) (42_720: U+20000..2A6DF)
\p{Block: CJK_Unified_Ideographs_Extension_C} (Short: \p{Blk=
CJKExtC}) (4160: U+2A700..2B73F)
\p{Block: CJK_Unified_Ideographs_Extension_D} (Short: \p{Blk=
CJKExtD}) (224: U+2B740..2B81F)
\p{Block: CJK_Unified_Ideographs_Extension_E} (Short: \p{Blk=
CJKExtE}) (5776: U+2B820..2CEAF)
\p{Block: CJK_Unified_Ideographs_Extension_F} (Short: \p{Blk=
CJKExtF}) (7488: U+2CEB0..2EBEF)
\p{Block: CJK_Unified_Ideographs_Extension_G} (Short: \p{Blk=
CJKExtG}) (4944: U+30000..3134F)
\p{Block: Combining_Diacritical_Marks} (Short: \p{Blk=
Diacriticals}) (112: U+0300..036F)
\p{Block: Combining_Diacritical_Marks_Extended} (Short: \p{Blk=
DiacriticalsExt}) (80: U+1AB0..1AFF)
\p{Block: Combining_Diacritical_Marks_For_Symbols} (Short: \p{Blk=
DiacriticalsForSymbols}) (48:
U+20D0..20FF)
\p{Block: Combining_Diacritical_Marks_Supplement} (Short: \p{Blk=
DiacriticalsSup}) (64: U+1DC0..1DFF)
\p{Block: Combining_Half_Marks} (Short: \p{Blk=HalfMarks}) (16:
U+FE20..FE2F)
\p{Block: Combining_Marks_For_Symbols} \p{Block=
Combining_Diacritical_Marks_For_Symbols}
(48)
\p{Block: Common_Indic_Number_Forms} (Short: \p{Blk=
IndicNumberForms}) (16: U+A830..A83F)
\p{Block: Compat_Jamo} \p{Block=Hangul_Compatibility_Jamo} (96)
\p{Block: Control_Pictures} (64: U+2400..243F)
\p{Block: Coptic} (NOT \p{Coptic} NOR \p{Is_Coptic}) (128:
U+2C80..2CFF)
\p{Block: Coptic_Epact_Numbers} (32: U+102E0..102FF)
\p{Block: Counting_Rod} \p{Block=Counting_Rod_Numerals} (32)
\p{Block: Counting_Rod_Numerals} (Short: \p{Blk=CountingRod}) (32:
U+1D360..1D37F)
\p{Block: Cuneiform} (NOT \p{Cuneiform} NOR \p{Is_Cuneiform})
(1024: U+12000..123FF)
\p{Block: Cuneiform_Numbers} \p{Block=
Cuneiform_Numbers_And_Punctuation} (128)
\p{Block: Cuneiform_Numbers_And_Punctuation} (Short: \p{Blk=
CuneiformNumbers}) (128: U+12400..1247F)
\p{Block: Currency_Symbols} (48: U+20A0..20CF)
\p{Block: Cypriot_Syllabary} (64: U+10800..1083F)
\p{Block: Cypro_Minoan} (NOT \p{Cypro_Minoan} NOR
\p{Is_Cypro_Minoan}) (112:
U+12F90..12FFF)
\p{Block: Cyrillic} (NOT \p{Cyrillic} NOR \p{Is_Cyrillic})
(256: U+0400..04FF)
\p{Block: Cyrillic_Ext_A} \p{Block=Cyrillic_Extended_A} (32)
\p{Block: Cyrillic_Ext_B} \p{Block=Cyrillic_Extended_B} (96)
\p{Block: Cyrillic_Ext_C} \p{Block=Cyrillic_Extended_C} (16)
\p{Block: Cyrillic_Extended_A} (Short: \p{Blk=CyrillicExtA}) (32:
U+2DE0..2DFF)
\p{Block: Cyrillic_Extended_B} (Short: \p{Blk=CyrillicExtB}) (96:
U+A640..A69F)
\p{Block: Cyrillic_Extended_C} (Short: \p{Blk=CyrillicExtC}) (16:
U+1C80..1C8F)
\p{Block: Cyrillic_Sup} \p{Block=Cyrillic_Supplement} (48)
\p{Block: Cyrillic_Supplement} (Short: \p{Blk=CyrillicSup}) (48:
U+0500..052F)
\p{Block: Cyrillic_Supplementary} \p{Block=Cyrillic_Supplement}
(48)
\p{Block: Deseret} (80: U+10400..1044F)
\p{Block: Devanagari} (NOT \p{Devanagari} NOR \p{Is_Devanagari})
(128: U+0900..097F)
\p{Block: Devanagari_Ext} \p{Block=Devanagari_Extended} (32)
\p{Block: Devanagari_Extended} (Short: \p{Blk=DevanagariExt}) (32:
U+A8E0..A8FF)
\p{Block: Diacriticals} \p{Block=Combining_Diacritical_Marks} (112)
\p{Block: Diacriticals_Ext} \p{Block=
Combining_Diacritical_Marks_Extended}
(80)
\p{Block: Diacriticals_For_Symbols} \p{Block=
Combining_Diacritical_Marks_For_Symbols}
(48)
\p{Block: Diacriticals_Sup} \p{Block=
Combining_Diacritical_Marks_Supplement}
(64)
\p{Block: Dingbats} (192: U+2700..27BF)
\p{Block: Dives_Akuru} (NOT \p{Dives_Akuru} NOR
\p{Is_Dives_Akuru}) (96: U+11900..1195F)
\p{Block: Dogra} (NOT \p{Dogra} NOR \p{Is_Dogra}) (80:
U+11800..1184F)
\p{Block: Domino} \p{Block=Domino_Tiles} (112)
\p{Block: Domino_Tiles} (Short: \p{Blk=Domino}) (112:
U+1F030..1F09F)
\p{Block: Duployan} (NOT \p{Duployan} NOR \p{Is_Duployan})
(160: U+1BC00..1BC9F)
\p{Block: Early_Dynastic_Cuneiform} (208: U+12480..1254F)
\p{Block: Egyptian_Hieroglyph_Format_Controls} (16: U+13430..1343F)
\p{Block: Egyptian_Hieroglyphs} (NOT \p{Egyptian_Hieroglyphs} NOR
\p{Is_Egyptian_Hieroglyphs}) (1072:
U+13000..1342F)
\p{Block: Elbasan} (NOT \p{Elbasan} NOR \p{Is_Elbasan}) (48:
U+10500..1052F)
\p{Block: Elymaic} (NOT \p{Elymaic} NOR \p{Is_Elymaic}) (32:
U+10FE0..10FFF)
\p{Block: Emoticons} (80: U+1F600..1F64F)
\p{Block: Enclosed_Alphanum} \p{Block=Enclosed_Alphanumerics} (160)
\p{Block: Enclosed_Alphanum_Sup} \p{Block=
Enclosed_Alphanumeric_Supplement} (256)
\p{Block: Enclosed_Alphanumeric_Supplement} (Short: \p{Blk=
EnclosedAlphanumSup}) (256:
U+1F100..1F1FF)
\p{Block: Enclosed_Alphanumerics} (Short: \p{Blk=
EnclosedAlphanum}) (160: U+2460..24FF)
\p{Block: Enclosed_CJK} \p{Block=Enclosed_CJK_Letters_And_Months}
(256)
\p{Block: Enclosed_CJK_Letters_And_Months} (Short: \p{Blk=
EnclosedCJK}) (256: U+3200..32FF)
\p{Block: Enclosed_Ideographic_Sup} \p{Block=
Enclosed_Ideographic_Supplement} (256)
\p{Block: Enclosed_Ideographic_Supplement} (Short: \p{Blk=
EnclosedIdeographicSup}) (256:
U+1F200..1F2FF)
\p{Block: Ethiopic} (NOT \p{Ethiopic} NOR \p{Is_Ethiopic})
(384: U+1200..137F)
\p{Block: Ethiopic_Ext} \p{Block=Ethiopic_Extended} (96)
\p{Block: Ethiopic_Ext_A} \p{Block=Ethiopic_Extended_A} (48)
\p{Block: Ethiopic_Ext_B} \p{Block=Ethiopic_Extended_B} (32)
\p{Block: Ethiopic_Extended} (Short: \p{Blk=EthiopicExt}) (96:
U+2D80..2DDF)
\p{Block: Ethiopic_Extended_A} (Short: \p{Blk=EthiopicExtA}) (48:
U+AB00..AB2F)
\p{Block: Ethiopic_Extended_B} (Short: \p{Blk=EthiopicExtB}) (32:
U+1E7E0..1E7FF)
\p{Block: Ethiopic_Sup} \p{Block=Ethiopic_Supplement} (32)
\p{Block: Ethiopic_Supplement} (Short: \p{Blk=EthiopicSup}) (32:
U+1380..139F)
\p{Block: General_Punctuation} (Short: \p{Blk=Punctuation}; NOT
\p{Punct} NOR \p{Is_Punctuation}) (112:
U+2000..206F)
\p{Block: Geometric_Shapes} (96: U+25A0..25FF)
\p{Block: Geometric_Shapes_Ext} \p{Block=
Geometric_Shapes_Extended} (128)
\p{Block: Geometric_Shapes_Extended} (Short: \p{Blk=
GeometricShapesExt}) (128:
U+1F780..1F7FF)
\p{Block: Georgian} (NOT \p{Georgian} NOR \p{Is_Georgian})
(96: U+10A0..10FF)
\p{Block: Georgian_Ext} \p{Block=Georgian_Extended} (48)
\p{Block: Georgian_Extended} (Short: \p{Blk=GeorgianExt}) (48:
U+1C90..1CBF)
\p{Block: Georgian_Sup} \p{Block=Georgian_Supplement} (48)
\p{Block: Georgian_Supplement} (Short: \p{Blk=GeorgianSup}) (48:
U+2D00..2D2F)
\p{Block: Glagolitic} (NOT \p{Glagolitic} NOR \p{Is_Glagolitic})
(96: U+2C00..2C5F)
\p{Block: Glagolitic_Sup} \p{Block=Glagolitic_Supplement} (48)
\p{Block: Glagolitic_Supplement} (Short: \p{Blk=GlagoliticSup})
(48: U+1E000..1E02F)
\p{Block: Gothic} (NOT \p{Gothic} NOR \p{Is_Gothic}) (32:
U+10330..1034F)
\p{Block: Grantha} (NOT \p{Grantha} NOR \p{Is_Grantha}) (128:
U+11300..1137F)
\p{Block: Greek} \p{Block=Greek_And_Coptic} (NOT \p{Greek}
NOR \p{Is_Greek}) (144)
\p{Block: Greek_And_Coptic} (Short: \p{Blk=Greek}; NOT \p{Greek}
NOR \p{Is_Greek}) (144: U+0370..03FF)
\p{Block: Greek_Ext} \p{Block=Greek_Extended} (256)
\p{Block: Greek_Extended} (Short: \p{Blk=GreekExt}) (256:
U+1F00..1FFF)
\p{Block: Gujarati} (NOT \p{Gujarati} NOR \p{Is_Gujarati})
(128: U+0A80..0AFF)
\p{Block: Gunjala_Gondi} (NOT \p{Gunjala_Gondi} NOR
\p{Is_Gunjala_Gondi}) (80:
U+11D60..11DAF)
\p{Block: Gurmukhi} (NOT \p{Gurmukhi} NOR \p{Is_Gurmukhi})
(128: U+0A00..0A7F)
\p{Block: Half_And_Full_Forms} \p{Block=
Halfwidth_And_Fullwidth_Forms} (240)
\p{Block: Half_Marks} \p{Block=Combining_Half_Marks} (16)
\p{Block: Halfwidth_And_Fullwidth_Forms} (Short: \p{Blk=
HalfAndFullForms}) (240: U+FF00..FFEF)
\p{Block: Hangul} \p{Block=Hangul_Syllables} (NOT \p{Hangul}
NOR \p{Is_Hangul}) (11_184)
\p{Block: Hangul_Compatibility_Jamo} (Short: \p{Blk=CompatJamo})
(96: U+3130..318F)
\p{Block: Hangul_Jamo} (Short: \p{Blk=Jamo}) (256: U+1100..11FF)
\p{Block: Hangul_Jamo_Extended_A} (Short: \p{Blk=JamoExtA}) (32:
U+A960..A97F)
\p{Block: Hangul_Jamo_Extended_B} (Short: \p{Blk=JamoExtB}) (80:
U+D7B0..D7FF)
\p{Block: Hangul_Syllables} (Short: \p{Blk=Hangul}; NOT \p{Hangul}
NOR \p{Is_Hangul}) (11_184: U+AC00..D7AF)
\p{Block: Hanifi_Rohingya} (NOT \p{Hanifi_Rohingya} NOR
\p{Is_Hanifi_Rohingya}) (64:
U+10D00..10D3F)
\p{Block: Hanunoo} (NOT \p{Hanunoo} NOR \p{Is_Hanunoo}) (32:
U+1720..173F)
\p{Block: Hatran} (NOT \p{Hatran} NOR \p{Is_Hatran}) (32:
U+108E0..108FF)
\p{Block: Hebrew} (NOT \p{Hebrew} NOR \p{Is_Hebrew}) (112:
U+0590..05FF)
\p{Block: High_Private_Use_Surrogates} (Short: \p{Blk=
HighPUSurrogates}) (128: U+DB80..DBFF)
\p{Block: High_PU_Surrogates} \p{Block=
High_Private_Use_Surrogates} (128)
\p{Block: High_Surrogates} (896: U+D800..DB7F)
\p{Block: Hiragana} (NOT \p{Hiragana} NOR \p{Is_Hiragana})
(96: U+3040..309F)
\p{Block: IDC} \p{Block=
Ideographic_Description_Characters} (NOT
\p{ID_Continue} NOR \p{Is_IDC}) (16)
\p{Block: Ideographic_Description_Characters} (Short: \p{Blk=IDC};
NOT \p{ID_Continue} NOR \p{Is_IDC}) (16:
U+2FF0..2FFF)
\p{Block: Ideographic_Symbols} \p{Block=
Ideographic_Symbols_And_Punctuation} (32)
\p{Block: Ideographic_Symbols_And_Punctuation} (Short: \p{Blk=
IdeographicSymbols}) (32: U+16FE0..16FFF)
\p{Block: Imperial_Aramaic} (NOT \p{Imperial_Aramaic} NOR
\p{Is_Imperial_Aramaic}) (32:
U+10840..1085F)
\p{Block: Indic_Number_Forms} \p{Block=Common_Indic_Number_Forms}
(16)
\p{Block: Indic_Siyaq_Numbers} (80: U+1EC70..1ECBF)
\p{Block: Inscriptional_Pahlavi} (NOT \p{Inscriptional_Pahlavi}
NOR \p{Is_Inscriptional_Pahlavi}) (32:
U+10B60..10B7F)
\p{Block: Inscriptional_Parthian} (NOT \p{Inscriptional_Parthian}
NOR \p{Is_Inscriptional_Parthian}) (32:
U+10B40..10B5F)
\p{Block: IPA_Ext} \p{Block=IPA_Extensions} (96)
\p{Block: IPA_Extensions} (Short: \p{Blk=IPAExt}) (96:
U+0250..02AF)
\p{Block: Jamo} \p{Block=Hangul_Jamo} (256)
\p{Block: Jamo_Ext_A} \p{Block=Hangul_Jamo_Extended_A} (32)
\p{Block: Jamo_Ext_B} \p{Block=Hangul_Jamo_Extended_B} (80)
\p{Block: Javanese} (NOT \p{Javanese} NOR \p{Is_Javanese})
(96: U+A980..A9DF)
\p{Block: Kaithi} (NOT \p{Kaithi} NOR \p{Is_Kaithi}) (80:
U+11080..110CF)
\p{Block: Kana_Ext_A} \p{Block=Kana_Extended_A} (48)
\p{Block: Kana_Ext_B} \p{Block=Kana_Extended_B} (16)
\p{Block: Kana_Extended_A} (Short: \p{Blk=KanaExtA}) (48:
U+1B100..1B12F)
\p{Block: Kana_Extended_B} (Short: \p{Blk=KanaExtB}) (16:
U+1AFF0..1AFFF)
\p{Block: Kana_Sup} \p{Block=Kana_Supplement} (256)
\p{Block: Kana_Supplement} (Short: \p{Blk=KanaSup}) (256:
U+1B000..1B0FF)
\p{Block: Kanbun} (16: U+3190..319F)
\p{Block: Kangxi} \p{Block=Kangxi_Radicals} (224)
\p{Block: Kangxi_Radicals} (Short: \p{Blk=Kangxi}) (224:
U+2F00..2FDF)
\p{Block: Kannada} (NOT \p{Kannada} NOR \p{Is_Kannada}) (128:
U+0C80..0CFF)
\p{Block: Katakana} (NOT \p{Katakana} NOR \p{Is_Katakana})
(96: U+30A0..30FF)
\p{Block: Katakana_Ext} \p{Block=Katakana_Phonetic_Extensions} (16)
\p{Block: Katakana_Phonetic_Extensions} (Short: \p{Blk=
KatakanaExt}) (16: U+31F0..31FF)
\p{Block: Kayah_Li} (48: U+A900..A92F)
\p{Block: Kharoshthi} (NOT \p{Kharoshthi} NOR \p{Is_Kharoshthi})
(96: U+10A00..10A5F)
\p{Block: Khitan_Small_Script} (NOT \p{Khitan_Small_Script} NOR
\p{Is_Khitan_Small_Script}) (512:
U+18B00..18CFF)
\p{Block: Khmer} (NOT \p{Khmer} NOR \p{Is_Khmer}) (128:
U+1780..17FF)
\p{Block: Khmer_Symbols} (32: U+19E0..19FF)
\p{Block: Khojki} (NOT \p{Khojki} NOR \p{Is_Khojki}) (80:
U+11200..1124F)
\p{Block: Khudawadi} (NOT \p{Khudawadi} NOR \p{Is_Khudawadi})
(80: U+112B0..112FF)
\p{Block: Lao} (NOT \p{Lao} NOR \p{Is_Lao}) (128:
U+0E80..0EFF)
\p{Block: Latin_1} \p{Block=Latin_1_Supplement} (128)
\p{Block: Latin_1_Sup} \p{Block=Latin_1_Supplement} (128)
\p{Block: Latin_1_Supplement} (Short: \p{Blk=Latin1}) (128: [\x80-
\xff])
\p{Block: Latin_Ext_A} \p{Block=Latin_Extended_A} (128)
\p{Block: Latin_Ext_Additional} \p{Block=
Latin_Extended_Additional} (256)
\p{Block: Latin_Ext_B} \p{Block=Latin_Extended_B} (208)
\p{Block: Latin_Ext_C} \p{Block=Latin_Extended_C} (32)
\p{Block: Latin_Ext_D} \p{Block=Latin_Extended_D} (224)
\p{Block: Latin_Ext_E} \p{Block=Latin_Extended_E} (64)
\p{Block: Latin_Ext_F} \p{Block=Latin_Extended_F} (64)
\p{Block: Latin_Ext_G} \p{Block=Latin_Extended_G} (256)
\p{Block: Latin_Extended_A} (Short: \p{Blk=LatinExtA}) (128:
U+0100..017F)
\p{Block: Latin_Extended_Additional} (Short: \p{Blk=
LatinExtAdditional}) (256: U+1E00..1EFF)
\p{Block: Latin_Extended_B} (Short: \p{Blk=LatinExtB}) (208:
U+0180..024F)
\p{Block: Latin_Extended_C} (Short: \p{Blk=LatinExtC}) (32:
U+2C60..2C7F)
\p{Block: Latin_Extended_D} (Short: \p{Blk=LatinExtD}) (224:
U+A720..A7FF)
\p{Block: Latin_Extended_E} (Short: \p{Blk=LatinExtE}) (64:
U+AB30..AB6F)
\p{Block: Latin_Extended_F} (Short: \p{Blk=LatinExtF}) (64:
U+10780..107BF)
\p{Block: Latin_Extended_G} (Short: \p{Blk=LatinExtG}) (256:
U+1DF00..1DFFF)
\p{Block: Lepcha} (NOT \p{Lepcha} NOR \p{Is_Lepcha}) (80:
U+1C00..1C4F)
\p{Block: Letterlike_Symbols} (80: U+2100..214F)
\p{Block: Limbu} (NOT \p{Limbu} NOR \p{Is_Limbu}) (80:
U+1900..194F)
\p{Block: Linear_A} (NOT \p{Linear_A} NOR \p{Is_Linear_A})
(384: U+10600..1077F)
\p{Block: Linear_B_Ideograms} (128: U+10080..100FF)
\p{Block: Linear_B_Syllabary} (128: U+10000..1007F)
\p{Block: Lisu} (NOT \p{Lisu} NOR \p{Is_Lisu}) (48:
U+A4D0..A4FF)
\p{Block: Lisu_Sup} \p{Block=Lisu_Supplement} (16)
\p{Block: Lisu_Supplement} (Short: \p{Blk=LisuSup}) (16:
U+11FB0..11FBF)
\p{Block: Low_Surrogates} (1024: U+DC00..DFFF)
\p{Block: Lycian} (NOT \p{Lycian} NOR \p{Is_Lycian}) (32:
U+10280..1029F)
\p{Block: Lydian} (NOT \p{Lydian} NOR \p{Is_Lydian}) (32:
U+10920..1093F)
\p{Block: Mahajani} (NOT \p{Mahajani} NOR \p{Is_Mahajani})
(48: U+11150..1117F)
\p{Block: Mahjong} \p{Block=Mahjong_Tiles} (48)
\p{Block: Mahjong_Tiles} (Short: \p{Blk=Mahjong}) (48:
U+1F000..1F02F)
\p{Block: Makasar} (NOT \p{Makasar} NOR \p{Is_Makasar}) (32:
U+11EE0..11EFF)
\p{Block: Malayalam} (NOT \p{Malayalam} NOR \p{Is_Malayalam})
(128: U+0D00..0D7F)
\p{Block: Mandaic} (NOT \p{Mandaic} NOR \p{Is_Mandaic}) (32:
U+0840..085F)
\p{Block: Manichaean} (NOT \p{Manichaean} NOR \p{Is_Manichaean})
(64: U+10AC0..10AFF)
\p{Block: Marchen} (NOT \p{Marchen} NOR \p{Is_Marchen}) (80:
U+11C70..11CBF)
\p{Block: Masaram_Gondi} (NOT \p{Masaram_Gondi} NOR
\p{Is_Masaram_Gondi}) (96:
U+11D00..11D5F)
\p{Block: Math_Alphanum} \p{Block=
Mathematical_Alphanumeric_Symbols} (1024)
\p{Block: Math_Operators} \p{Block=Mathematical_Operators} (256)
\p{Block: Mathematical_Alphanumeric_Symbols} (Short: \p{Blk=
MathAlphanum}) (1024: U+1D400..1D7FF)
\p{Block: Mathematical_Operators} (Short: \p{Blk=MathOperators})
(256: U+2200..22FF)
\p{Block: Mayan_Numerals} (32: U+1D2E0..1D2FF)
\p{Block: Medefaidrin} (NOT \p{Medefaidrin} NOR
\p{Is_Medefaidrin}) (96: U+16E40..16E9F)
\p{Block: Meetei_Mayek} (NOT \p{Meetei_Mayek} NOR
\p{Is_Meetei_Mayek}) (64: U+ABC0..ABFF)
\p{Block: Meetei_Mayek_Ext} \p{Block=Meetei_Mayek_Extensions} (32)
\p{Block: Meetei_Mayek_Extensions} (Short: \p{Blk=MeeteiMayekExt})
(32: U+AAE0..AAFF)
\p{Block: Mende_Kikakui} (NOT \p{Mende_Kikakui} NOR
\p{Is_Mende_Kikakui}) (224:
U+1E800..1E8DF)
\p{Block: Meroitic_Cursive} (NOT \p{Meroitic_Cursive} NOR
\p{Is_Meroitic_Cursive}) (96:
U+109A0..109FF)
\p{Block: Meroitic_Hieroglyphs} (32: U+10980..1099F)
\p{Block: Miao} (NOT \p{Miao} NOR \p{Is_Miao}) (160:
U+16F00..16F9F)
\p{Block: Misc_Arrows} \p{Block=Miscellaneous_Symbols_And_Arrows}
(256)
\p{Block: Misc_Math_Symbols_A} \p{Block=
Miscellaneous_Mathematical_Symbols_A}
(48)
\p{Block: Misc_Math_Symbols_B} \p{Block=
Miscellaneous_Mathematical_Symbols_B}
(128)
\p{Block: Misc_Pictographs} \p{Block=
Miscellaneous_Symbols_And_Pictographs}
(768)
\p{Block: Misc_Symbols} \p{Block=Miscellaneous_Symbols} (256)
\p{Block: Misc_Technical} \p{Block=Miscellaneous_Technical} (256)
\p{Block: Miscellaneous_Mathematical_Symbols_A} (Short: \p{Blk=
MiscMathSymbolsA}) (48: U+27C0..27EF)
\p{Block: Miscellaneous_Mathematical_Symbols_B} (Short: \p{Blk=
MiscMathSymbolsB}) (128: U+2980..29FF)
\p{Block: Miscellaneous_Symbols} (Short: \p{Blk=MiscSymbols})
(256: U+2600..26FF)
\p{Block: Miscellaneous_Symbols_And_Arrows} (Short: \p{Blk=
MiscArrows}) (256: U+2B00..2BFF)
\p{Block: Miscellaneous_Symbols_And_Pictographs} (Short: \p{Blk=
MiscPictographs}) (768: U+1F300..1F5FF)
\p{Block: Miscellaneous_Technical} (Short: \p{Blk=MiscTechnical})
(256: U+2300..23FF)
\p{Block: Modi} (NOT \p{Modi} NOR \p{Is_Modi}) (96:
U+11600..1165F)
\p{Block: Modifier_Letters} \p{Block=Spacing_Modifier_Letters} (80)
\p{Block: Modifier_Tone_Letters} (32: U+A700..A71F)
\p{Block: Mongolian} (NOT \p{Mongolian} NOR \p{Is_Mongolian})
(176: U+1800..18AF)
\p{Block: Mongolian_Sup} \p{Block=Mongolian_Supplement} (32)
\p{Block: Mongolian_Supplement} (Short: \p{Blk=MongolianSup}) (32:
U+11660..1167F)
\p{Block: Mro} (NOT \p{Mro} NOR \p{Is_Mro}) (48:
U+16A40..16A6F)
\p{Block: Multani} (NOT \p{Multani} NOR \p{Is_Multani}) (48:
U+11280..112AF)
\p{Block: Music} \p{Block=Musical_Symbols} (256)
\p{Block: Musical_Symbols} (Short: \p{Blk=Music}) (256:
U+1D100..1D1FF)
\p{Block: Myanmar} (NOT \p{Myanmar} NOR \p{Is_Myanmar}) (160:
U+1000..109F)
\p{Block: Myanmar_Ext_A} \p{Block=Myanmar_Extended_A} (32)
\p{Block: Myanmar_Ext_B} \p{Block=Myanmar_Extended_B} (32)
\p{Block: Myanmar_Extended_A} (Short: \p{Blk=MyanmarExtA}) (32:
U+AA60..AA7F)
\p{Block: Myanmar_Extended_B} (Short: \p{Blk=MyanmarExtB}) (32:
U+A9E0..A9FF)
\p{Block: Nabataean} (NOT \p{Nabataean} NOR \p{Is_Nabataean})
(48: U+10880..108AF)
\p{Block: Nandinagari} (NOT \p{Nandinagari} NOR
\p{Is_Nandinagari}) (96: U+119A0..119FF)
\p{Block: NB} \p{Block=No_Block} (825_600 plus all
above-Unicode code points)
\p{Block: New_Tai_Lue} (NOT \p{New_Tai_Lue} NOR
\p{Is_New_Tai_Lue}) (96: U+1980..19DF)
\p{Block: Newa} (NOT \p{Newa} NOR \p{Is_Newa}) (128:
U+11400..1147F)
\p{Block: NKo} (NOT \p{Nko} NOR \p{Is_NKo}) (64:
U+07C0..07FF)
\p{Block: No_Block} (Short: \p{Blk=NB}) (825_600 plus all
above-Unicode code points: U+2FE0..2FEF,
U+10200..1027F, U+103E0..103FF,
U+105C0..105FF, U+107C0..107FF,
U+108B0..108DF ...)
\p{Block: Number_Forms} (64: U+2150..218F)
\p{Block: Nushu} (NOT \p{Nushu} NOR \p{Is_Nushu}) (400:
U+1B170..1B2FF)
\p{Block: Nyiakeng_Puachue_Hmong} (NOT \p{Nyiakeng_Puachue_Hmong}
NOR \p{Is_Nyiakeng_Puachue_Hmong}) (80:
U+1E100..1E14F)
\p{Block: OCR} \p{Block=Optical_Character_Recognition}
(32)
\p{Block: Ogham} (NOT \p{Ogham} NOR \p{Is_Ogham}) (32:
U+1680..169F)
\p{Block: Ol_Chiki} (48: U+1C50..1C7F)
\p{Block: Old_Hungarian} (NOT \p{Old_Hungarian} NOR
\p{Is_Old_Hungarian}) (128:
U+10C80..10CFF)
\p{Block: Old_Italic} (NOT \p{Old_Italic} NOR \p{Is_Old_Italic})
(48: U+10300..1032F)
\p{Block: Old_North_Arabian} (32: U+10A80..10A9F)
\p{Block: Old_Permic} (NOT \p{Old_Permic} NOR \p{Is_Old_Permic})
(48: U+10350..1037F)
\p{Block: Old_Persian} (NOT \p{Old_Persian} NOR
\p{Is_Old_Persian}) (64: U+103A0..103DF)
\p{Block: Old_Sogdian} (NOT \p{Old_Sogdian} NOR
\p{Is_Old_Sogdian}) (48: U+10F00..10F2F)
\p{Block: Old_South_Arabian} (32: U+10A60..10A7F)
\p{Block: Old_Turkic} (NOT \p{Old_Turkic} NOR \p{Is_Old_Turkic})
(80: U+10C00..10C4F)
\p{Block: Old_Uyghur} (NOT \p{Old_Uyghur} NOR \p{Is_Old_Uyghur})
(64: U+10F70..10FAF)
\p{Block: Optical_Character_Recognition} (Short: \p{Blk=OCR}) (32:
U+2440..245F)
\p{Block: Oriya} (NOT \p{Oriya} NOR \p{Is_Oriya}) (128:
U+0B00..0B7F)
\p{Block: Ornamental_Dingbats} (48: U+1F650..1F67F)
\p{Block: Osage} (NOT \p{Osage} NOR \p{Is_Osage}) (80:
U+104B0..104FF)
\p{Block: Osmanya} (NOT \p{Osmanya} NOR \p{Is_Osmanya}) (48:
U+10480..104AF)
\p{Block: Ottoman_Siyaq_Numbers} (80: U+1ED00..1ED4F)
\p{Block: Pahawh_Hmong} (NOT \p{Pahawh_Hmong} NOR
\p{Is_Pahawh_Hmong}) (144:
U+16B00..16B8F)
\p{Block: Palmyrene} (32: U+10860..1087F)
\p{Block: Pau_Cin_Hau} (NOT \p{Pau_Cin_Hau} NOR
\p{Is_Pau_Cin_Hau}) (64: U+11AC0..11AFF)
\p{Block: Phags_Pa} (NOT \p{Phags_Pa} NOR \p{Is_Phags_Pa})
(64: U+A840..A87F)
\p{Block: Phaistos} \p{Block=Phaistos_Disc} (48)
\p{Block: Phaistos_Disc} (Short: \p{Blk=Phaistos}) (48:
U+101D0..101FF)
\p{Block: Phoenician} (NOT \p{Phoenician} NOR \p{Is_Phoenician})
(32: U+10900..1091F)
\p{Block: Phonetic_Ext} \p{Block=Phonetic_Extensions} (128)
\p{Block: Phonetic_Ext_Sup} \p{Block=
Phonetic_Extensions_Supplement} (64)
\p{Block: Phonetic_Extensions} (Short: \p{Blk=PhoneticExt}) (128:
U+1D00..1D7F)
\p{Block: Phonetic_Extensions_Supplement} (Short: \p{Blk=
PhoneticExtSup}) (64: U+1D80..1DBF)
\p{Block: Playing_Cards} (96: U+1F0A0..1F0FF)
\p{Block: Private_Use} \p{Block=Private_Use_Area} (NOT
\p{Private_Use} NOR \p{Is_Private_Use})
(6400)
\p{Block: Private_Use_Area} (Short: \p{Blk=PUA}; NOT
\p{Private_Use} NOR \p{Is_Private_Use})
(6400: U+E000..F8FF)
\p{Block: Psalter_Pahlavi} (NOT \p{Psalter_Pahlavi} NOR
\p{Is_Psalter_Pahlavi}) (48:
U+10B80..10BAF)
\p{Block: PUA} \p{Block=Private_Use_Area} (NOT
\p{Private_Use} NOR \p{Is_Private_Use})
(6400)
\p{Block: Punctuation} \p{Block=General_Punctuation} (NOT
\p{Punct} NOR \p{Is_Punctuation}) (112)
\p{Block: Rejang} (NOT \p{Rejang} NOR \p{Is_Rejang}) (48:
U+A930..A95F)
\p{Block: Rumi} \p{Block=Rumi_Numeral_Symbols} (32)
\p{Block: Rumi_Numeral_Symbols} (Short: \p{Blk=Rumi}) (32:
U+10E60..10E7F)
\p{Block: Runic} (NOT \p{Runic} NOR \p{Is_Runic}) (96:
U+16A0..16FF)
\p{Block: Samaritan} (NOT \p{Samaritan} NOR \p{Is_Samaritan})
(64: U+0800..083F)
\p{Block: Saurashtra} (NOT \p{Saurashtra} NOR \p{Is_Saurashtra})
(96: U+A880..A8DF)
\p{Block: Sharada} (NOT \p{Sharada} NOR \p{Is_Sharada}) (96:
U+11180..111DF)
\p{Block: Shavian} (48: U+10450..1047F)
\p{Block: Shorthand_Format_Controls} (16: U+1BCA0..1BCAF)
\p{Block: Siddham} (NOT \p{Siddham} NOR \p{Is_Siddham}) (128:
U+11580..115FF)
\p{Block: Sinhala} (NOT \p{Sinhala} NOR \p{Is_Sinhala}) (128:
U+0D80..0DFF)
\p{Block: Sinhala_Archaic_Numbers} (32: U+111E0..111FF)
\p{Block: Small_Form_Variants} (Short: \p{Blk=SmallForms}) (32:
U+FE50..FE6F)
\p{Block: Small_Forms} \p{Block=Small_Form_Variants} (32)
\p{Block: Small_Kana_Ext} \p{Block=Small_Kana_Extension} (64)
\p{Block: Small_Kana_Extension} (Short: \p{Blk=SmallKanaExt}) (64:
U+1B130..1B16F)
\p{Block: Sogdian} (NOT \p{Sogdian} NOR \p{Is_Sogdian}) (64:
U+10F30..10F6F)
\p{Block: Sora_Sompeng} (NOT \p{Sora_Sompeng} NOR
\p{Is_Sora_Sompeng}) (48: U+110D0..110FF)
\p{Block: Soyombo} (NOT \p{Soyombo} NOR \p{Is_Soyombo}) (96:
U+11A50..11AAF)
\p{Block: Spacing_Modifier_Letters} (Short: \p{Blk=
ModifierLetters}) (80: U+02B0..02FF)
\p{Block: Specials} (16: U+FFF0..FFFF)
\p{Block: Sundanese} (NOT \p{Sundanese} NOR \p{Is_Sundanese})
(64: U+1B80..1BBF)
\p{Block: Sundanese_Sup} \p{Block=Sundanese_Supplement} (16)
\p{Block: Sundanese_Supplement} (Short: \p{Blk=SundaneseSup}) (16:
U+1CC0..1CCF)
\p{Block: Sup_Arrows_A} \p{Block=Supplemental_Arrows_A} (16)
\p{Block: Sup_Arrows_B} \p{Block=Supplemental_Arrows_B} (128)
\p{Block: Sup_Arrows_C} \p{Block=Supplemental_Arrows_C} (256)
\p{Block: Sup_Math_Operators} \p{Block=
Supplemental_Mathematical_Operators}
(256)
\p{Block: Sup_PUA_A} \p{Block=Supplementary_Private_Use_Area_A}
(65_536)
\p{Block: Sup_PUA_B} \p{Block=Supplementary_Private_Use_Area_B}
(65_536)
\p{Block: Sup_Punctuation} \p{Block=Supplemental_Punctuation} (128)
\p{Block: Sup_Symbols_And_Pictographs} \p{Block=
Supplemental_Symbols_And_Pictographs}
(256)
\p{Block: Super_And_Sub} \p{Block=Superscripts_And_Subscripts} (48)
\p{Block: Superscripts_And_Subscripts} (Short: \p{Blk=
SuperAndSub}) (48: U+2070..209F)
\p{Block: Supplemental_Arrows_A} (Short: \p{Blk=SupArrowsA}) (16:
U+27F0..27FF)
\p{Block: Supplemental_Arrows_B} (Short: \p{Blk=SupArrowsB}) (128:
U+2900..297F)
\p{Block: Supplemental_Arrows_C} (Short: \p{Blk=SupArrowsC}) (256:
U+1F800..1F8FF)
\p{Block: Supplemental_Mathematical_Operators} (Short: \p{Blk=
SupMathOperators}) (256: U+2A00..2AFF)
\p{Block: Supplemental_Punctuation} (Short: \p{Blk=
SupPunctuation}) (128: U+2E00..2E7F)
\p{Block: Supplemental_Symbols_And_Pictographs} (Short: \p{Blk=
SupSymbolsAndPictographs}) (256:
U+1F900..1F9FF)
\p{Block: Supplementary_Private_Use_Area_A} (Short: \p{Blk=
SupPUAA}) (65_536: U+F0000..FFFFF)
\p{Block: Supplementary_Private_Use_Area_B} (Short: \p{Blk=
SupPUAB}) (65_536: U+100000..10FFFF)
\p{Block: Sutton_SignWriting} (688: U+1D800..1DAAF)
\p{Block: Syloti_Nagri} (NOT \p{Syloti_Nagri} NOR
\p{Is_Syloti_Nagri}) (48: U+A800..A82F)
\p{Block: Symbols_And_Pictographs_Ext_A} \p{Block=
Symbols_And_Pictographs_Extended_A} (144)
\p{Block: Symbols_And_Pictographs_Extended_A} (Short: \p{Blk=
SymbolsAndPictographsExtA}) (144:
U+1FA70..1FAFF)
\p{Block: Symbols_For_Legacy_Computing} (256: U+1FB00..1FBFF)
\p{Block: Syriac} (NOT \p{Syriac} NOR \p{Is_Syriac}) (80:
U+0700..074F)
\p{Block: Syriac_Sup} \p{Block=Syriac_Supplement} (16)
\p{Block: Syriac_Supplement} (Short: \p{Blk=SyriacSup}) (16:
U+0860..086F)
\p{Block: Tagalog} (NOT \p{Tagalog} NOR \p{Is_Tagalog}) (32:
U+1700..171F)
\p{Block: Tagbanwa} (NOT \p{Tagbanwa} NOR \p{Is_Tagbanwa})
(32: U+1760..177F)
\p{Block: Tags} (128: U+E0000..E007F)
\p{Block: Tai_Le} (NOT \p{Tai_Le} NOR \p{Is_Tai_Le}) (48:
U+1950..197F)
\p{Block: Tai_Tham} (NOT \p{Tai_Tham} NOR \p{Is_Tai_Tham})
(144: U+1A20..1AAF)
\p{Block: Tai_Viet} (NOT \p{Tai_Viet} NOR \p{Is_Tai_Viet})
(96: U+AA80..AADF)
\p{Block: Tai_Xuan_Jing} \p{Block=Tai_Xuan_Jing_Symbols} (96)
\p{Block: Tai_Xuan_Jing_Symbols} (Short: \p{Blk=TaiXuanJing}) (96:
U+1D300..1D35F)
\p{Block: Takri} (NOT \p{Takri} NOR \p{Is_Takri}) (80:
U+11680..116CF)
\p{Block: Tamil} (NOT \p{Tamil} NOR \p{Is_Tamil}) (128:
U+0B80..0BFF)
\p{Block: Tamil_Sup} \p{Block=Tamil_Supplement} (64)
\p{Block: Tamil_Supplement} (Short: \p{Blk=TamilSup}) (64:
U+11FC0..11FFF)
\p{Block: Tangsa} (NOT \p{Tangsa} NOR \p{Is_Tangsa}) (96:
U+16A70..16ACF)
\p{Block: Tangut} (NOT \p{Tangut} NOR \p{Is_Tangut}) (6144:
U+17000..187FF)
\p{Block: Tangut_Components} (768: U+18800..18AFF)
\p{Block: Tangut_Sup} \p{Block=Tangut_Supplement} (128)
\p{Block: Tangut_Supplement} (Short: \p{Blk=TangutSup}) (128:
U+18D00..18D7F)
\p{Block: Telugu} (NOT \p{Telugu} NOR \p{Is_Telugu}) (128:
U+0C00..0C7F)
\p{Block: Thaana} (NOT \p{Thaana} NOR \p{Is_Thaana}) (64:
U+0780..07BF)
\p{Block: Thai} (NOT \p{Thai} NOR \p{Is_Thai}) (128:
U+0E00..0E7F)
\p{Block: Tibetan} (NOT \p{Tibetan} NOR \p{Is_Tibetan}) (256:
U+0F00..0FFF)
\p{Block: Tifinagh} (NOT \p{Tifinagh} NOR \p{Is_Tifinagh})
(80: U+2D30..2D7F)
\p{Block: Tirhuta} (NOT \p{Tirhuta} NOR \p{Is_Tirhuta}) (96:
U+11480..114DF)
\p{Block: Toto} (NOT \p{Toto} NOR \p{Is_Toto}) (48:
U+1E290..1E2BF)
\p{Block: Transport_And_Map} \p{Block=Transport_And_Map_Symbols}
(128)
\p{Block: Transport_And_Map_Symbols} (Short: \p{Blk=
TransportAndMap}) (128: U+1F680..1F6FF)
\p{Block: UCAS} \p{Block=
Unified_Canadian_Aboriginal_Syllabics}
(640)
\p{Block: UCAS_Ext} \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended} (80)
\p{Block: UCAS_Ext_A} \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended_A} (16)
\p{Block: Ugaritic} (NOT \p{Ugaritic} NOR \p{Is_Ugaritic})
(32: U+10380..1039F)
\p{Block: Unified_Canadian_Aboriginal_Syllabics} (Short: \p{Blk=
UCAS}) (640: U+1400..167F)
\p{Block: Unified_Canadian_Aboriginal_Syllabics_Extended} (Short:
\p{Blk=UCASExt}) (80: U+18B0..18FF)
\p{Block: Unified_Canadian_Aboriginal_Syllabics_Extended_A}
(Short: \p{Blk=UCASExtA}) (16:
U+11AB0..11ABF)
\p{Block: Vai} (NOT \p{Vai} NOR \p{Is_Vai}) (320:
U+A500..A63F)
\p{Block: Variation_Selectors} (Short: \p{Blk=VS}; NOT
\p{Variation_Selector} NOR \p{Is_VS})
(16: U+FE00..FE0F)
\p{Block: Variation_Selectors_Supplement} (Short: \p{Blk=VSSup})
(240: U+E0100..E01EF)
\p{Block: Vedic_Ext} \p{Block=Vedic_Extensions} (48)
\p{Block: Vedic_Extensions} (Short: \p{Blk=VedicExt}) (48:
U+1CD0..1CFF)
\p{Block: Vertical_Forms} (16: U+FE10..FE1F)
\p{Block: Vithkuqi} (NOT \p{Vithkuqi} NOR \p{Is_Vithkuqi})
(80: U+10570..105BF)
\p{Block: VS} \p{Block=Variation_Selectors} (NOT
\p{Variation_Selector} NOR \p{Is_VS})
(16)
\p{Block: VS_Sup} \p{Block=Variation_Selectors_Supplement}
(240)
\p{Block: Wancho} (NOT \p{Wancho} NOR \p{Is_Wancho}) (64:
U+1E2C0..1E2FF)
\p{Block: Warang_Citi} (NOT \p{Warang_Citi} NOR
\p{Is_Warang_Citi}) (96: U+118A0..118FF)
\p{Block: Yezidi} (NOT \p{Yezidi} NOR \p{Is_Yezidi}) (64:
U+10E80..10EBF)
\p{Block: Yi_Radicals} (64: U+A490..A4CF)
\p{Block: Yi_Syllables} (1168: U+A000..A48F)
\p{Block: Yijing} \p{Block=Yijing_Hexagram_Symbols} (64)
\p{Block: Yijing_Hexagram_Symbols} (Short: \p{Blk=Yijing}) (64:
U+4DC0..4DFF)
\p{Block: Zanabazar_Square} (NOT \p{Zanabazar_Square} NOR
\p{Is_Zanabazar_Square}) (80:
U+11A00..11A4F)
\p{Block: Znamenny_Music} \p{Block=Znamenny_Musical_Notation} (208)
\p{Block: Znamenny_Musical_Notation} (Short: \p{Blk=
ZnamennyMusic}) (208: U+1CF00..1CFCF)
X \p{Block_Elements} \p{Block=Block_Elements} (32)
\p{Bopo} \p{Bopomofo} (= \p{Script_Extensions=
Bopomofo}) (NOT \p{Block=Bopomofo}) (117)
\p{Bopomofo} \p{Script_Extensions=Bopomofo} (Short:
\p{Bopo}; NOT \p{Block=Bopomofo}) (117)
X \p{Bopomofo_Ext} \p{Bopomofo_Extended} (= \p{Block=
Bopomofo_Extended}) (32)
X \p{Bopomofo_Extended} \p{Block=Bopomofo_Extended} (Short:
\p{InBopomofoExt}) (32)
X \p{Box_Drawing} \p{Block=Box_Drawing} (128)
\p{Bpt: *} \p{Bidi_Paired_Bracket_Type: *}
\p{Brah} \p{Brahmi} (= \p{Script_Extensions=
Brahmi}) (NOT \p{Block=Brahmi}) (115)
\p{Brahmi} \p{Script_Extensions=Brahmi} (Short:
\p{Brah}; NOT \p{Block=Brahmi}) (115)
\p{Brai} \p{Braille} (= \p{Script_Extensions=
Braille}) (256)
\p{Braille} \p{Script_Extensions=Braille} (Short:
\p{Brai}) (256)
X \p{Braille_Patterns} \p{Block=Braille_Patterns} (Short:
\p{InBraille}) (256)
\p{Bugi} \p{Buginese} (= \p{Script_Extensions=
Buginese}) (NOT \p{Block=Buginese}) (31)
\p{Buginese} \p{Script_Extensions=Buginese} (Short:
\p{Bugi}; NOT \p{Block=Buginese}) (31)
\p{Buhd} \p{Buhid} (= \p{Script_Extensions=Buhid})
(NOT \p{Block=Buhid}) (22)
\p{Buhid} \p{Script_Extensions=Buhid} (Short:
\p{Buhd}; NOT \p{Block=Buhid}) (22)
X \p{Byzantine_Music} \p{Byzantine_Musical_Symbols} (= \p{Block=
Byzantine_Musical_Symbols}) (256)
X \p{Byzantine_Musical_Symbols} \p{Block=Byzantine_Musical_Symbols}
(Short: \p{InByzantineMusic}) (256)
\p{C} \pC \p{Other} (= \p{General_Category=Other})
(969_578 plus all above-Unicode code
points)
\p{Cakm} \p{Chakma} (= \p{Script_Extensions=
Chakma}) (NOT \p{Block=Chakma}) (91)
\p{Canadian_Aboriginal} \p{Script_Extensions=Canadian_Aboriginal}
(Short: \p{Cans}) (726)
X \p{Canadian_Syllabics} \p{Unified_Canadian_Aboriginal_Syllabics}
(= \p{Block=
Unified_Canadian_Aboriginal_Syllabics})
(640)
T \p{Canonical_Combining_Class: 0} \p{Canonical_Combining_Class=
Not_Reordered} (1_113_200 plus all
above-Unicode code points)
T \p{Canonical_Combining_Class: 1} \p{Canonical_Combining_Class=
Overlay} (32)
T \p{Canonical_Combining_Class: 6} \p{Canonical_Combining_Class=
Han_Reading} (2)
T \p{Canonical_Combining_Class: 7} \p{Canonical_Combining_Class=
Nukta} (27)
T \p{Canonical_Combining_Class: 8} \p{Canonical_Combining_Class=
Kana_Voicing} (2)
T \p{Canonical_Combining_Class: 9} \p{Canonical_Combining_Class=
Virama} (63)
T \p{Canonical_Combining_Class: 10} \p{Canonical_Combining_Class=
CCC10} (1)
\p{Canonical_Combining_Class: CCC10} (Short: \p{Ccc=CCC10}) (1:
U+05B0)
T \p{Canonical_Combining_Class: 11} \p{Canonical_Combining_Class=
CCC11} (1)
\p{Canonical_Combining_Class: CCC11} (Short: \p{Ccc=CCC11}) (1:
U+05B1)
T \p{Canonical_Combining_Class: 12} \p{Canonical_Combining_Class=
CCC12} (1)
\p{Canonical_Combining_Class: CCC12} (Short: \p{Ccc=CCC12}) (1:
U+05B2)
T \p{Canonical_Combining_Class: 13} \p{Canonical_Combining_Class=
CCC13} (1)
\p{Canonical_Combining_Class: CCC13} (Short: \p{Ccc=CCC13}) (1:
U+05B3)
T \p{Canonical_Combining_Class: 14} \p{Canonical_Combining_Class=
CCC14} (1)
\p{Canonical_Combining_Class: CCC14} (Short: \p{Ccc=CCC14}) (1:
U+05B4)
T \p{Canonical_Combining_Class: 15} \p{Canonical_Combining_Class=
CCC15} (1)
\p{Canonical_Combining_Class: CCC15} (Short: \p{Ccc=CCC15}) (1:
U+05B5)
T \p{Canonical_Combining_Class: 16} \p{Canonical_Combining_Class=
CCC16} (1)
\p{Canonical_Combining_Class: CCC16} (Short: \p{Ccc=CCC16}) (1:
U+05B6)
T \p{Canonical_Combining_Class: 17} \p{Canonical_Combining_Class=
CCC17} (1)
\p{Canonical_Combining_Class: CCC17} (Short: \p{Ccc=CCC17}) (1:
U+05B7)
T \p{Canonical_Combining_Class: 18} \p{Canonical_Combining_Class=
CCC18} (2)
\p{Canonical_Combining_Class: CCC18} (Short: \p{Ccc=CCC18}) (2:
U+05B8, U+05C7)
T \p{Canonical_Combining_Class: 19} \p{Canonical_Combining_Class=
CCC19} (2)
\p{Canonical_Combining_Class: CCC19} (Short: \p{Ccc=CCC19}) (2:
U+05B9..05BA)
T \p{Canonical_Combining_Class: 20} \p{Canonical_Combining_Class=
CCC20} (1)
\p{Canonical_Combining_Class: CCC20} (Short: \p{Ccc=CCC20}) (1:
U+05BB)
T \p{Canonical_Combining_Class: 21} \p{Canonical_Combining_Class=
CCC21} (1)
\p{Canonical_Combining_Class: CCC21} (Short: \p{Ccc=CCC21}) (1:
U+05BC)
T \p{Canonical_Combining_Class: 22} \p{Canonical_Combining_Class=
CCC22} (1)
\p{Canonical_Combining_Class: CCC22} (Short: \p{Ccc=CCC22}) (1:
U+05BD)
T \p{Canonical_Combining_Class: 23} \p{Canonical_Combining_Class=
CCC23} (1)
\p{Canonical_Combining_Class: CCC23} (Short: \p{Ccc=CCC23}) (1:
U+05BF)
T \p{Canonical_Combining_Class: 24} \p{Canonical_Combining_Class=
CCC24} (1)
\p{Canonical_Combining_Class: CCC24} (Short: \p{Ccc=CCC24}) (1:
U+05C1)
T \p{Canonical_Combining_Class: 25} \p{Canonical_Combining_Class=
CCC25} (1)
\p{Canonical_Combining_Class: CCC25} (Short: \p{Ccc=CCC25}) (1:
U+05C2)
T \p{Canonical_Combining_Class: 26} \p{Canonical_Combining_Class=
CCC26} (1)
\p{Canonical_Combining_Class: CCC26} (Short: \p{Ccc=CCC26}) (1:
U+FB1E)
T \p{Canonical_Combining_Class: 27} \p{Canonical_Combining_Class=
CCC27} (2)
\p{Canonical_Combining_Class: CCC27} (Short: \p{Ccc=CCC27}) (2:
U+064B, U+08F0)
T \p{Canonical_Combining_Class: 28} \p{Canonical_Combining_Class=
CCC28} (2)
\p{Canonical_Combining_Class: CCC28} (Short: \p{Ccc=CCC28}) (2:
U+064C, U+08F1)
T \p{Canonical_Combining_Class: 29} \p{Canonical_Combining_Class=
CCC29} (2)
\p{Canonical_Combining_Class: CCC29} (Short: \p{Ccc=CCC29}) (2:
U+064D, U+08F2)
T \p{Canonical_Combining_Class: 30} \p{Canonical_Combining_Class=
CCC30} (2)
\p{Canonical_Combining_Class: CCC30} (Short: \p{Ccc=CCC30}) (2:
U+0618, U+064E)
T \p{Canonical_Combining_Class: 31} \p{Canonical_Combining_Class=
CCC31} (2)
\p{Canonical_Combining_Class: CCC31} (Short: \p{Ccc=CCC31}) (2:
U+0619, U+064F)
T \p{Canonical_Combining_Class: 32} \p{Canonical_Combining_Class=
CCC32} (2)
\p{Canonical_Combining_Class: CCC32} (Short: \p{Ccc=CCC32}) (2:
U+061A, U+0650)
T \p{Canonical_Combining_Class: 33} \p{Canonical_Combining_Class=
CCC33} (1)
\p{Canonical_Combining_Class: CCC33} (Short: \p{Ccc=CCC33}) (1:
U+0651)
T \p{Canonical_Combining_Class: 34} \p{Canonical_Combining_Class=
CCC34} (1)
\p{Canonical_Combining_Class: CCC34} (Short: \p{Ccc=CCC34}) (1:
U+0652)
T \p{Canonical_Combining_Class: 35} \p{Canonical_Combining_Class=
CCC35} (1)
\p{Canonical_Combining_Class: CCC35} (Short: \p{Ccc=CCC35}) (1:
U+0670)
T \p{Canonical_Combining_Class: 36} \p{Canonical_Combining_Class=
CCC36} (1)
\p{Canonical_Combining_Class: CCC36} (Short: \p{Ccc=CCC36}) (1:
U+0711)
T \p{Canonical_Combining_Class: 84} \p{Canonical_Combining_Class=
CCC84} (1)
\p{Canonical_Combining_Class: CCC84} (Short: \p{Ccc=CCC84}) (1:
U+0C55)
T \p{Canonical_Combining_Class: 91} \p{Canonical_Combining_Class=
CCC91} (1)
\p{Canonical_Combining_Class: CCC91} (Short: \p{Ccc=CCC91}) (1:
U+0C56)
T \p{Canonical_Combining_Class: 103} \p{Canonical_Combining_Class=
CCC103} (2)
\p{Canonical_Combining_Class: CCC103} (Short: \p{Ccc=CCC103}) (2:
U+0E38..0E39)
T \p{Canonical_Combining_Class: 107} \p{Canonical_Combining_Class=
CCC107} (4)
\p{Canonical_Combining_Class: CCC107} (Short: \p{Ccc=CCC107}) (4:
U+0E48..0E4B)
T \p{Canonical_Combining_Class: 118} \p{Canonical_Combining_Class=
CCC118} (2)
\p{Canonical_Combining_Class: CCC118} (Short: \p{Ccc=CCC118}) (2:
U+0EB8..0EB9)
T \p{Canonical_Combining_Class: 122} \p{Canonical_Combining_Class=
CCC122} (4)
\p{Canonical_Combining_Class: CCC122} (Short: \p{Ccc=CCC122}) (4:
U+0EC8..0ECB)
T \p{Canonical_Combining_Class: 129} \p{Canonical_Combining_Class=
CCC129} (1)
\p{Canonical_Combining_Class: CCC129} (Short: \p{Ccc=CCC129}) (1:
U+0F71)
T \p{Canonical_Combining_Class: 130} \p{Canonical_Combining_Class=
CCC130} (6)
\p{Canonical_Combining_Class: CCC130} (Short: \p{Ccc=CCC130}) (6:
U+0F72, U+0F7A..0F7D, U+0F80)
T \p{Canonical_Combining_Class: 132} \p{Canonical_Combining_Class=
CCC132} (1)
\p{Canonical_Combining_Class: CCC132} (Short: \p{Ccc=CCC132}) (1:
U+0F74)
T \p{Canonical_Combining_Class: 133} \p{Canonical_Combining_Class=
CCC133} (0)
\p{Canonical_Combining_Class: CCC133} (Short: \p{Ccc=CCC133}) (0)
T \p{Canonical_Combining_Class: 200} \p{Canonical_Combining_Class=
Attached_Below_Left} (0)
T \p{Canonical_Combining_Class: 202} \p{Canonical_Combining_Class=
Attached_Below} (5)
T \p{Canonical_Combining_Class: 214} \p{Canonical_Combining_Class=
Attached_Above} (1)
T \p{Canonical_Combining_Class: 216} \p{Canonical_Combining_Class=
Attached_Above_Right} (9)
T \p{Canonical_Combining_Class: 218} \p{Canonical_Combining_Class=
Below_Left} (2)
T \p{Canonical_Combining_Class: 220} \p{Canonical_Combining_Class=
Below} (177)
T \p{Canonical_Combining_Class: 222} \p{Canonical_Combining_Class=
Below_Right} (4)
T \p{Canonical_Combining_Class: 224} \p{Canonical_Combining_Class=
Left} (2)
T \p{Canonical_Combining_Class: 226} \p{Canonical_Combining_Class=
Right} (1)
T \p{Canonical_Combining_Class: 228} \p{Canonical_Combining_Class=
Above_Left} (5)
T \p{Canonical_Combining_Class: 230} \p{Canonical_Combining_Class=
Above} (508)
T \p{Canonical_Combining_Class: 232} \p{Canonical_Combining_Class=
Above_Right} (5)
T \p{Canonical_Combining_Class: 233} \p{Canonical_Combining_Class=
Double_Below} (4)
T \p{Canonical_Combining_Class: 234} \p{Canonical_Combining_Class=
Double_Above} (5)
T \p{Canonical_Combining_Class: 240} \p{Canonical_Combining_Class=
Iota_Subscript} (1)
\p{Canonical_Combining_Class: A} \p{Canonical_Combining_Class=
Above} (508)
\p{Canonical_Combining_Class: Above} (Short: \p{Ccc=A}) (508:
U+0300..0314, U+033D..0344, U+0346,
U+034A..034C, U+0350..0352, U+0357 ...)
\p{Canonical_Combining_Class: Above_Left} (Short: \p{Ccc=AL}) (5:
U+05AE, U+18A9, U+1DF7..1DF8, U+302B)
\p{Canonical_Combining_Class: Above_Right} (Short: \p{Ccc=AR}) (5:
U+0315, U+031A, U+0358, U+1DF6, U+302C)
\p{Canonical_Combining_Class: AL} \p{Canonical_Combining_Class=
Above_Left} (5)
\p{Canonical_Combining_Class: AR} \p{Canonical_Combining_Class=
Above_Right} (5)
\p{Canonical_Combining_Class: ATA} \p{Canonical_Combining_Class=
Attached_Above} (1)
\p{Canonical_Combining_Class: ATAR} \p{Canonical_Combining_Class=
Attached_Above_Right} (9)
\p{Canonical_Combining_Class: ATB} \p{Canonical_Combining_Class=
Attached_Below} (5)
\p{Canonical_Combining_Class: ATBL} \p{Canonical_Combining_Class=
Attached_Below_Left} (0)
\p{Canonical_Combining_Class: Attached_Above} (Short: \p{Ccc=ATA})
(1: U+1DCE)
\p{Canonical_Combining_Class: Attached_Above_Right} (Short:
\p{Ccc=ATAR}) (9: U+031B, U+0F39,
U+1D165..1D166, U+1D16E..1D172)
\p{Canonical_Combining_Class: Attached_Below} (Short: \p{Ccc=ATB})
(5: U+0321..0322, U+0327..0328, U+1DD0)
\p{Canonical_Combining_Class: Attached_Below_Left} (Short: \p{Ccc=
ATBL}) (0)
\p{Canonical_Combining_Class: B} \p{Canonical_Combining_Class=
Below} (177)
\p{Canonical_Combining_Class: Below} (Short: \p{Ccc=B}) (177:
U+0316..0319, U+031C..0320,
U+0323..0326, U+0329..0333,
U+0339..033C, U+0347..0349 ...)
\p{Canonical_Combining_Class: Below_Left} (Short: \p{Ccc=BL}) (2:
U+1DFA, U+302A)
\p{Canonical_Combining_Class: Below_Right} (Short: \p{Ccc=BR}) (4:
U+059A, U+05AD, U+1939, U+302D)
\p{Canonical_Combining_Class: BL} \p{Canonical_Combining_Class=
Below_Left} (2)
\p{Canonical_Combining_Class: BR} \p{Canonical_Combining_Class=
Below_Right} (4)
\p{Canonical_Combining_Class: DA} \p{Canonical_Combining_Class=
Double_Above} (5)
\p{Canonical_Combining_Class: DB} \p{Canonical_Combining_Class=
Double_Below} (4)
\p{Canonical_Combining_Class: Double_Above} (Short: \p{Ccc=DA})
(5: U+035D..035E, U+0360..0361, U+1DCD)
\p{Canonical_Combining_Class: Double_Below} (Short: \p{Ccc=DB})
(4: U+035C, U+035F, U+0362, U+1DFC)
\p{Canonical_Combining_Class: Han_Reading} (Short: \p{Ccc=HANR})
(2: U+16FF0..16FF1)
\p{Canonical_Combining_Class: HANR} \p{Canonical_Combining_Class=
Han_Reading} (2)
\p{Canonical_Combining_Class: Iota_Subscript} (Short: \p{Ccc=IS})
(1: U+0345)
\p{Canonical_Combining_Class: IS} \p{Canonical_Combining_Class=
Iota_Subscript} (1)
\p{Canonical_Combining_Class: Kana_Voicing} (Short: \p{Ccc=KV})
(2: U+3099..309A)
\p{Canonical_Combining_Class: KV} \p{Canonical_Combining_Class=
Kana_Voicing} (2)
\p{Canonical_Combining_Class: L} \p{Canonical_Combining_Class=
Left} (2)
\p{Canonical_Combining_Class: Left} (Short: \p{Ccc=L}) (2:
U+302E..302F)
\p{Canonical_Combining_Class: NK} \p{Canonical_Combining_Class=
Nukta} (27)
\p{Canonical_Combining_Class: Not_Reordered} (Short: \p{Ccc=NR})
(1_113_200 plus all above-Unicode code
points: U+0000..02FF, U+034F,
U+0370..0482, U+0488..0590, U+05BE,
U+05C0 ...)
\p{Canonical_Combining_Class: NR} \p{Canonical_Combining_Class=
Not_Reordered} (1_113_200 plus all
above-Unicode code points)
\p{Canonical_Combining_Class: Nukta} (Short: \p{Ccc=NK}) (27:
U+093C, U+09BC, U+0A3C, U+0ABC, U+0B3C,
U+0C3C ...)
\p{Canonical_Combining_Class: OV} \p{Canonical_Combining_Class=
Overlay} (32)
\p{Canonical_Combining_Class: Overlay} (Short: \p{Ccc=OV}) (32:
U+0334..0338, U+1CD4, U+1CE2..1CE8,
U+20D2..20D3, U+20D8..20DA, U+20E5..20E6
...)
\p{Canonical_Combining_Class: R} \p{Canonical_Combining_Class=
Right} (1)
\p{Canonical_Combining_Class: Right} (Short: \p{Ccc=R}) (1:
U+1D16D)
\p{Canonical_Combining_Class: Virama} (Short: \p{Ccc=VR}) (63:
U+094D, U+09CD, U+0A4D, U+0ACD, U+0B4D,
U+0BCD ...)
\p{Canonical_Combining_Class: VR} \p{Canonical_Combining_Class=
Virama} (63)
\p{Cans} \p{Canadian_Aboriginal} (=
\p{Script_Extensions=
Canadian_Aboriginal}) (726)
\p{Cari} \p{Carian} (= \p{Script_Extensions=
Carian}) (NOT \p{Block=Carian}) (49)
\p{Carian} \p{Script_Extensions=Carian} (Short:
\p{Cari}; NOT \p{Block=Carian}) (49)
\p{Case_Ignorable} \p{Case_Ignorable=Y} (Short: \p{CI}) (2602)
\p{Case_Ignorable: N*} (Short: \p{CI=N}, \P{CI}) (1_111_510 plus
all above-Unicode code points: [\x00-
\x20!\"#\$\%&\(\)*+,\-\/0-9;<=>?\@A-Z
\[\\\]_a-z\{\|\}~\x7f-\xa7\xa9-\xac\xae
\xb0-\xb3\xb5-\xb6\xb9-\xff],
U+0100..02AF, U+0370..0373,
U+0376..0379, U+037B..0383, U+0386 ...)
\p{Case_Ignorable: Y*} (Short: \p{CI=Y}, \p{CI}) (2602: [\'.:\^`
\xa8\xad\xaf\xb4\xb7-\xb8],
U+02B0..036F, U+0374..0375, U+037A,
U+0384..0385, U+0387 ...)
\p{Cased} \p{Cased=Y} (4453)
\p{Cased: N*} (Single: \P{Cased}) (1_109_659 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*+,\-.\/0-9:;<=>?\@\[\\\]
\^_`\{\|\}~\x7f-\xa9\xab-\xb4\xb6-\xb9
\xbb-\xbf\xd7\xf7], U+01BB,
U+01C0..01C3, U+0294, U+02B9..02BF,
U+02C2..02DF ...)
\p{Cased: Y*} (Single: \p{Cased}) (4453: [A-Za-z\xaa
\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..01BA, U+01BC..01BF,
U+01C4..0293, U+0295..02B8, U+02C0..02C1
...)
\p{Cased_Letter} \p{General_Category=Cased_Letter} (Short:
\p{LC}) (4089)
\p{Category: *} \p{General_Category: *}
\p{Caucasian_Albanian} \p{Script_Extensions=Caucasian_Albanian}
(Short: \p{Aghb}; NOT \p{Block=
Caucasian_Albanian}) (53)
\p{Cc} \p{XPosixCntrl} (= \p{General_Category=
Control}) (65)
\p{Ccc: *} \p{Canonical_Combining_Class: *}
\p{CE} \p{Composition_Exclusion} (=
\p{Composition_Exclusion=Y}) (81)
\p{CE: *} \p{Composition_Exclusion: *}
\p{Cf} \p{Format} (= \p{General_Category=Format})
(163)
\p{Chakma} \p{Script_Extensions=Chakma} (Short:
\p{Cakm}; NOT \p{Block=Chakma}) (91)
\p{Cham} \p{Script_Extensions=Cham} (NOT \p{Block=
Cham}) (83)
\p{Changes_When_Casefolded} \p{Changes_When_Casefolded=Y} (Short:
\p{CWCF}) (1506)
\p{Changes_When_Casefolded: N*} (Short: \p{CWCF=N}, \P{CWCF})
(1_112_606 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@\[\\\]\^_`a-z\{\|\}~\x7f-
\xb4\xb6-\xbf\xd7\xe0-\xff], U+0101,
U+0103, U+0105, U+0107, U+0109 ...)
\p{Changes_When_Casefolded: Y*} (Short: \p{CWCF=Y}, \p{CWCF})
(1506: [A-Z\xb5\xc0-\xd6\xd8-\xdf],
U+0100, U+0102, U+0104, U+0106, U+0108
...)
\p{Changes_When_Casemapped} \p{Changes_When_Casemapped=Y} (Short:
\p{CWCM}) (2927)
\p{Changes_When_Casemapped: N*} (Short: \p{CWCM=N}, \P{CWCM})
(1_111_185 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@\[\\\]\^_`\{\|\}~\x7f-\xb4
\xb6-\xbf\xd7\xf7], U+0138, U+018D,
U+019B, U+01AA..01AB, U+01BA..01BB ...)
\p{Changes_When_Casemapped: Y*} (Short: \p{CWCM=Y}, \p{CWCM})
(2927: [A-Za-z\xb5\xc0-\xd6\xd8-\xf6
\xf8-\xff], U+0100..0137, U+0139..018C,
U+018E..019A, U+019C..01A9, U+01AC..01B9
...)
\p{Changes_When_Lowercased} \p{Changes_When_Lowercased=Y} (Short:
\p{CWL}) (1433)
\p{Changes_When_Lowercased: N*} (Short: \p{CWL=N}, \P{CWL})
(1_112_679 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@\[\\\]\^_`a-z\{\|\}~\x7f-
\xbf\xd7\xdf-\xff], U+0101, U+0103,
U+0105, U+0107, U+0109 ...)
\p{Changes_When_Lowercased: Y*} (Short: \p{CWL=Y}, \p{CWL}) (1433:
[A-Z\xc0-\xd6\xd8-\xde], U+0100, U+0102,
U+0104, U+0106, U+0108 ...)
\p{Changes_When_NFKC_Casefolded} \p{Changes_When_NFKC_Casefolded=
Y} (Short: \p{CWKCF}) (10_429)
\p{Changes_When_NFKC_Casefolded: N*} (Short: \p{CWKCF=N},
\P{CWKCF}) (1_103_683 plus all above-
Unicode code points: [\x00-\x20!\"#\$
\%&\'\(\)*+,\-.\/0-9:;<=>?\@\[\\\]\^_`a-
z\{\|\}~\x7f-\x9f\xa1-\xa7\xa9\xab-\xac
\xae\xb0-\xb1\xb6-\xb7\xbb\xbf\xd7\xe0-
\xff], U+0101, U+0103, U+0105, U+0107,
U+0109 ...)
\p{Changes_When_NFKC_Casefolded: Y*} (Short: \p{CWKCF=Y},
\p{CWKCF}) (10_429: [A-Z\xa0\xa8\xaa
\xad\xaf\xb2-\xb5\xb8-\xba\xbc-\xbe\xc0-
\xd6\xd8-\xdf], U+0100, U+0102, U+0104,
U+0106, U+0108 ...)
\p{Changes_When_Titlecased} \p{Changes_When_Titlecased=Y} (Short:
\p{CWT}) (1452)
\p{Changes_When_Titlecased: N*} (Short: \p{CWT=N}, \P{CWT})
(1_112_660 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@A-Z\[\\\]\^_`\{\|\}~\x7f-
\xb4\xb6-\xde\xf7], U+0100, U+0102,
U+0104, U+0106, U+0108 ...)
\p{Changes_When_Titlecased: Y*} (Short: \p{CWT=Y}, \p{CWT}) (1452:
[a-z\xb5\xdf-\xf6\xf8-\xff], U+0101,
U+0103, U+0105, U+0107, U+0109 ...)
\p{Changes_When_Uppercased} \p{Changes_When_Uppercased=Y} (Short:
\p{CWU}) (1525)
\p{Changes_When_Uppercased: N*} (Short: \p{CWU=N}, \P{CWU})
(1_112_587 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@A-Z\[\\\]\^_`\{\|\}~\x7f-
\xb4\xb6-\xde\xf7], U+0100, U+0102,
U+0104, U+0106, U+0108 ...)
\p{Changes_When_Uppercased: Y*} (Short: \p{CWU=Y}, \p{CWU}) (1525:
[a-z\xb5\xdf-\xf6\xf8-\xff], U+0101,
U+0103, U+0105, U+0107, U+0109 ...)
\p{Cher} \p{Cherokee} (= \p{Script_Extensions=
Cherokee}) (NOT \p{Block=Cherokee}) (172)
\p{Cherokee} \p{Script_Extensions=Cherokee} (Short:
\p{Cher}; NOT \p{Block=Cherokee}) (172)
X \p{Cherokee_Sup} \p{Cherokee_Supplement} (= \p{Block=
Cherokee_Supplement}) (80)
X \p{Cherokee_Supplement} \p{Block=Cherokee_Supplement} (Short:
\p{InCherokeeSup}) (80)
X \p{Chess_Symbols} \p{Block=Chess_Symbols} (112)
\p{Chorasmian} \p{Script_Extensions=Chorasmian} (Short:
\p{Chrs}; NOT \p{Block=Chorasmian}) (28)
\p{Chrs} \p{Chorasmian} (= \p{Script_Extensions=
Chorasmian}) (NOT \p{Block=Chorasmian})
(28)
\p{CI} \p{Case_Ignorable} (= \p{Case_Ignorable=
Y}) (2602)
\p{CI: *} \p{Case_Ignorable: *}
X \p{CJK} \p{CJK_Unified_Ideographs} (= \p{Block=
CJK_Unified_Ideographs}) (20_992)
X \p{CJK_Compat} \p{CJK_Compatibility} (= \p{Block=
CJK_Compatibility}) (256)
X \p{CJK_Compat_Forms} \p{CJK_Compatibility_Forms} (= \p{Block=
CJK_Compatibility_Forms}) (32)
X \p{CJK_Compat_Ideographs} \p{CJK_Compatibility_Ideographs} (=
\p{Block=CJK_Compatibility_Ideographs})
(512)
X \p{CJK_Compat_Ideographs_Sup}
\p{CJK_Compatibility_Ideographs_-
Supplement} (= \p{Block=
CJK_Compatibility_Ideographs_-
Supplement}) (544)
X \p{CJK_Compatibility} \p{Block=CJK_Compatibility} (Short:
\p{InCJKCompat}) (256)
X \p{CJK_Compatibility_Forms} \p{Block=CJK_Compatibility_Forms}
(Short: \p{InCJKCompatForms}) (32)
X \p{CJK_Compatibility_Ideographs} \p{Block=
CJK_Compatibility_Ideographs} (Short:
\p{InCJKCompatIdeographs}) (512)
X \p{CJK_Compatibility_Ideographs_Supplement} \p{Block=
CJK_Compatibility_Ideographs_Supplement}
(Short: \p{InCJKCompatIdeographsSup})
(544)
X \p{CJK_Ext_A} \p{CJK_Unified_Ideographs_Extension_A} (=
\p{Block=
CJK_Unified_Ideographs_Extension_A})
(6592)
X \p{CJK_Ext_B} \p{CJK_Unified_Ideographs_Extension_B} (=
\p{Block=
CJK_Unified_Ideographs_Extension_B})
(42_720)
X \p{CJK_Ext_C} \p{CJK_Unified_Ideographs_Extension_C} (=
\p{Block=
CJK_Unified_Ideographs_Extension_C})
(4160)
X \p{CJK_Ext_D} \p{CJK_Unified_Ideographs_Extension_D} (=
\p{Block=
CJK_Unified_Ideographs_Extension_D})
(224)
X \p{CJK_Ext_E} \p{CJK_Unified_Ideographs_Extension_E} (=
\p{Block=
CJK_Unified_Ideographs_Extension_E})
(5776)
X \p{CJK_Ext_F} \p{CJK_Unified_Ideographs_Extension_F} (=
\p{Block=
CJK_Unified_Ideographs_Extension_F})
(7488)
X \p{CJK_Ext_G} \p{CJK_Unified_Ideographs_Extension_G} (=
\p{Block=
CJK_Unified_Ideographs_Extension_G})
(4944)
X \p{CJK_Radicals_Sup} \p{CJK_Radicals_Supplement} (= \p{Block=
CJK_Radicals_Supplement}) (128)
X \p{CJK_Radicals_Supplement} \p{Block=CJK_Radicals_Supplement}
(Short: \p{InCJKRadicalsSup}) (128)
X \p{CJK_Strokes} \p{Block=CJK_Strokes} (48)
X \p{CJK_Symbols} \p{CJK_Symbols_And_Punctuation} (=
\p{Block=CJK_Symbols_And_Punctuation})
(64)
X \p{CJK_Symbols_And_Punctuation} \p{Block=
CJK_Symbols_And_Punctuation} (Short:
\p{InCJKSymbols}) (64)
X \p{CJK_Unified_Ideographs} \p{Block=CJK_Unified_Ideographs}
(Short: \p{InCJK}) (20_992)
X \p{CJK_Unified_Ideographs_Extension_A} \p{Block=
CJK_Unified_Ideographs_Extension_A}
(Short: \p{InCJKExtA}) (6592)
X \p{CJK_Unified_Ideographs_Extension_B} \p{Block=
CJK_Unified_Ideographs_Extension_B}
(Short: \p{InCJKExtB}) (42_720)
X \p{CJK_Unified_Ideographs_Extension_C} \p{Block=
CJK_Unified_Ideographs_Extension_C}
(Short: \p{InCJKExtC}) (4160)
X \p{CJK_Unified_Ideographs_Extension_D} \p{Block=
CJK_Unified_Ideographs_Extension_D}
(Short: \p{InCJKExtD}) (224)
X \p{CJK_Unified_Ideographs_Extension_E} \p{Block=
CJK_Unified_Ideographs_Extension_E}
(Short: \p{InCJKExtE}) (5776)
X \p{CJK_Unified_Ideographs_Extension_F} \p{Block=
CJK_Unified_Ideographs_Extension_F}
(Short: \p{InCJKExtF}) (7488)
X \p{CJK_Unified_Ideographs_Extension_G} \p{Block=
CJK_Unified_Ideographs_Extension_G}
(Short: \p{InCJKExtG}) (4944)
\p{Close_Punctuation} \p{General_Category=Close_Punctuation}
(Short: \p{Pe}) (77)
\p{Cn} \p{Unassigned} (= \p{General_Category=
Unassigned}) (829_834 plus all above-
Unicode code points)
\p{Cntrl} \p{XPosixCntrl} (= \p{General_Category=
Control}) (65)
\p{Co} \p{Private_Use} (= \p{General_Category=
Private_Use}) (NOT \p{Private_Use_Area})
(137_468)
X \p{Combining_Diacritical_Marks} \p{Block=
Combining_Diacritical_Marks} (Short:
\p{InDiacriticals}) (112)
X \p{Combining_Diacritical_Marks_Extended} \p{Block=
Combining_Diacritical_Marks_Extended}
(Short: \p{InDiacriticalsExt}) (80)
X \p{Combining_Diacritical_Marks_For_Symbols} \p{Block=
Combining_Diacritical_Marks_For_Symbols}
(Short: \p{InDiacriticalsForSymbols})
(48)
X \p{Combining_Diacritical_Marks_Supplement} \p{Block=
Combining_Diacritical_Marks_Supplement}
(Short: \p{InDiacriticalsSup}) (64)
X \p{Combining_Half_Marks} \p{Block=Combining_Half_Marks} (Short:
\p{InHalfMarks}) (16)
\p{Combining_Mark} \p{Mark} (= \p{General_Category=Mark})
(2408)
X \p{Combining_Marks_For_Symbols}
\p{Combining_Diacritical_Marks_For_-
Symbols} (= \p{Block=
Combining_Diacritical_Marks_For_-
Symbols}) (48)
\p{Common} \p{Script_Extensions=Common} (Short:
\p{Zyyy}) (7824)
X \p{Common_Indic_Number_Forms} \p{Block=Common_Indic_Number_Forms}
(Short: \p{InIndicNumberForms}) (16)
\p{Comp_Ex} \p{Full_Composition_Exclusion} (=
\p{Full_Composition_Exclusion=Y}) (1120)
\p{Comp_Ex: *} \p{Full_Composition_Exclusion: *}
X \p{Compat_Jamo} \p{Hangul_Compatibility_Jamo} (= \p{Block=
Hangul_Compatibility_Jamo}) (96)
\p{Composition_Exclusion} \p{Composition_Exclusion=Y} (Short:
\p{CE}) (81)
\p{Composition_Exclusion: N*} (Short: \p{CE=N}, \P{CE}) (1_114_031
plus all above-Unicode code points:
U+0000..0957, U+0960..09DB, U+09DE,
U+09E0..0A32, U+0A34..0A35, U+0A37..0A58
...)
\p{Composition_Exclusion: Y*} (Short: \p{CE=Y}, \p{CE}) (81:
U+0958..095F, U+09DC..09DD, U+09DF,
U+0A33, U+0A36, U+0A59..0A5B ...)
\p{Connector_Punctuation} \p{General_Category=
Connector_Punctuation} (Short: \p{Pc})
(10)
\p{Control} \p{XPosixCntrl} (= \p{General_Category=
Control}) (65)
X \p{Control_Pictures} \p{Block=Control_Pictures} (64)
\p{Copt} \p{Coptic} (= \p{Script_Extensions=
Coptic}) (NOT \p{Block=Coptic}) (165)
\p{Coptic} \p{Script_Extensions=Coptic} (Short:
\p{Copt}; NOT \p{Block=Coptic}) (165)
X \p{Coptic_Epact_Numbers} \p{Block=Coptic_Epact_Numbers} (32)
X \p{Counting_Rod} \p{Counting_Rod_Numerals} (= \p{Block=
Counting_Rod_Numerals}) (32)
X \p{Counting_Rod_Numerals} \p{Block=Counting_Rod_Numerals} (Short:
\p{InCountingRod}) (32)
\p{Cpmn} \p{Cypro_Minoan} (= \p{Script_Extensions=
Cypro_Minoan}) (NOT \p{Block=
Cypro_Minoan}) (101)
\p{Cprt} \p{Cypriot} (= \p{Script_Extensions=
Cypriot}) (112)
\p{Cs} \p{Surrogate} (= \p{General_Category=
Surrogate}) (2048)
\p{Cuneiform} \p{Script_Extensions=Cuneiform} (Short:
\p{Xsux}; NOT \p{Block=Cuneiform}) (1234)
X \p{Cuneiform_Numbers} \p{Cuneiform_Numbers_And_Punctuation} (=
\p{Block=
Cuneiform_Numbers_And_Punctuation}) (128)
X \p{Cuneiform_Numbers_And_Punctuation} \p{Block=
Cuneiform_Numbers_And_Punctuation}
(Short: \p{InCuneiformNumbers}) (128)
\p{Currency_Symbol} \p{General_Category=Currency_Symbol}
(Short: \p{Sc}) (63)
X \p{Currency_Symbols} \p{Block=Currency_Symbols} (48)
\p{CWCF} \p{Changes_When_Casefolded} (=
\p{Changes_When_Casefolded=Y}) (1506)
\p{CWCF: *} \p{Changes_When_Casefolded: *}
\p{CWCM} \p{Changes_When_Casemapped} (=
\p{Changes_When_Casemapped=Y}) (2927)
\p{CWCM: *} \p{Changes_When_Casemapped: *}
\p{CWKCF} \p{Changes_When_NFKC_Casefolded} (=
\p{Changes_When_NFKC_Casefolded=Y})
(10_429)
\p{CWKCF: *} \p{Changes_When_NFKC_Casefolded: *}
\p{CWL} \p{Changes_When_Lowercased} (=
\p{Changes_When_Lowercased=Y}) (1433)
\p{CWL: *} \p{Changes_When_Lowercased: *}
\p{CWT} \p{Changes_When_Titlecased} (=
\p{Changes_When_Titlecased=Y}) (1452)
\p{CWT: *} \p{Changes_When_Titlecased: *}
\p{CWU} \p{Changes_When_Uppercased} (=
\p{Changes_When_Uppercased=Y}) (1525)
\p{CWU: *} \p{Changes_When_Uppercased: *}
\p{Cypriot} \p{Script_Extensions=Cypriot} (Short:
\p{Cprt}) (112)
X \p{Cypriot_Syllabary} \p{Block=Cypriot_Syllabary} (64)
\p{Cypro_Minoan} \p{Script_Extensions=Cypro_Minoan} (Short:
\p{Cpmn}; NOT \p{Block=Cypro_Minoan})
(101)
\p{Cyrillic} \p{Script_Extensions=Cyrillic} (Short:
\p{Cyrl}; NOT \p{Block=Cyrillic}) (447)
X \p{Cyrillic_Ext_A} \p{Cyrillic_Extended_A} (= \p{Block=
Cyrillic_Extended_A}) (32)
X \p{Cyrillic_Ext_B} \p{Cyrillic_Extended_B} (= \p{Block=
Cyrillic_Extended_B}) (96)
X \p{Cyrillic_Ext_C} \p{Cyrillic_Extended_C} (= \p{Block=
Cyrillic_Extended_C}) (16)
X \p{Cyrillic_Extended_A} \p{Block=Cyrillic_Extended_A} (Short:
\p{InCyrillicExtA}) (32)
X \p{Cyrillic_Extended_B} \p{Block=Cyrillic_Extended_B} (Short:
\p{InCyrillicExtB}) (96)
X \p{Cyrillic_Extended_C} \p{Block=Cyrillic_Extended_C} (Short:
\p{InCyrillicExtC}) (16)
X \p{Cyrillic_Sup} \p{Cyrillic_Supplement} (= \p{Block=
Cyrillic_Supplement}) (48)
X \p{Cyrillic_Supplement} \p{Block=Cyrillic_Supplement} (Short:
\p{InCyrillicSup}) (48)
X \p{Cyrillic_Supplementary} \p{Cyrillic_Supplement} (= \p{Block=
Cyrillic_Supplement}) (48)
\p{Cyrl} \p{Cyrillic} (= \p{Script_Extensions=
Cyrillic}) (NOT \p{Block=Cyrillic}) (447)
\p{Dash} \p{Dash=Y} (30)
\p{Dash: N*} (Single: \P{Dash}) (1_114_082 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*+,.\/0-9:;<=>?\@A-Z
\[\\\]\^_`a-z\{\|\}~\x7f-\xff],
U+0100..0589, U+058B..05BD,
U+05BF..13FF, U+1401..1805, U+1807..200F
...)
\p{Dash: Y*} (Single: \p{Dash}) (30: [\-], U+058A,
U+05BE, U+1400, U+1806, U+2010..2015 ...)
\p{Dash_Punctuation} \p{General_Category=Dash_Punctuation}
(Short: \p{Pd}) (26)
\p{Decimal_Number} \p{XPosixDigit} (= \p{General_Category=
Decimal_Number}) (660)
\p{Decomposition_Type: Can} \p{Decomposition_Type=Canonical}
(13_233)
\p{Decomposition_Type: Canonical} (Short: \p{Dt=Can}) (13_233:
[\xc0-\xc5\xc7-\xcf\xd1-\xd6\xd9-\xdd
\xe0-\xe5\xe7-\xef\xf1-\xf6\xf9-\xfd
\xff], U+0100..010F, U+0112..0125,
U+0128..0130, U+0134..0137, U+0139..013E
...)
\p{Decomposition_Type: Circle} (Short: \p{Dt=Enc}) (240:
U+2460..2473, U+24B6..24EA,
U+3244..3247, U+3251..327E,
U+3280..32BF, U+32D0..32FE ...)
\p{Decomposition_Type: Com} \p{Decomposition_Type=Compat} (720)
\p{Decomposition_Type: Compat} (Short: \p{Dt=Com}) (720: [\xa8
\xaf\xb4-\xb5\xb8], U+0132..0133,
U+013F..0140, U+0149, U+017F,
U+01C4..01CC ...)
\p{Decomposition_Type: Enc} \p{Decomposition_Type=Circle} (240)
\p{Decomposition_Type: Fin} \p{Decomposition_Type=Final} (240)
\p{Decomposition_Type: Final} (Short: \p{Dt=Fin}) (240: U+FB51,
U+FB53, U+FB57, U+FB5B, U+FB5F, U+FB63
...)
\p{Decomposition_Type: Font} (Short: \p{Dt=Font}) (1194: U+2102,
U+210A..2113, U+2115, U+2119..211D,
U+2124, U+2128 ...)
\p{Decomposition_Type: Fra} \p{Decomposition_Type=Fraction} (20)
\p{Decomposition_Type: Fraction} (Short: \p{Dt=Fra}) (20: [\xbc-
\xbe], U+2150..215F, U+2189)
\p{Decomposition_Type: Init} \p{Decomposition_Type=Initial} (171)
\p{Decomposition_Type: Initial} (Short: \p{Dt=Init}) (171: U+FB54,
U+FB58, U+FB5C, U+FB60, U+FB64, U+FB68
...)
\p{Decomposition_Type: Iso} \p{Decomposition_Type=Isolated} (238)
\p{Decomposition_Type: Isolated} (Short: \p{Dt=Iso}) (238: U+FB50,
U+FB52, U+FB56, U+FB5A, U+FB5E, U+FB62
...)
\p{Decomposition_Type: Med} \p{Decomposition_Type=Medial} (82)
\p{Decomposition_Type: Medial} (Short: \p{Dt=Med}) (82: U+FB55,
U+FB59, U+FB5D, U+FB61, U+FB65, U+FB69
...)
\p{Decomposition_Type: Nar} \p{Decomposition_Type=Narrow} (122)
\p{Decomposition_Type: Narrow} (Short: \p{Dt=Nar}) (122:
U+FF61..FFBE, U+FFC2..FFC7,
U+FFCA..FFCF, U+FFD2..FFD7,
U+FFDA..FFDC, U+FFE8..FFEE)
\p{Decomposition_Type: Nb} \p{Decomposition_Type=Nobreak} (5)
\p{Decomposition_Type: Nobreak} (Short: \p{Dt=Nb}) (5: [\xa0],
U+0F0C, U+2007, U+2011, U+202F)
\p{Decomposition_Type: Non_Canon} \p{Decomposition_Type=
Non_Canonical} (Perl extension) (3734)
\p{Decomposition_Type: Non_Canonical} Union of all non-canonical
decompositions (Short: \p{Dt=NonCanon})
(Perl extension) (3734: [\xa0\xa8\xaa
\xaf\xb2-\xb5\xb8-\xba\xbc-\xbe],
U+0132..0133, U+013F..0140, U+0149,
U+017F, U+01C4..01CC ...)
\p{Decomposition_Type: None} (Short: \p{Dt=None}) (1_097_145 plus
all above-Unicode code points: [\x00-
\x9f\xa1-\xa7\xa9\xab-\xae\xb0-\xb1\xb6-
\xb7\xbb\xbf\xc6\xd0\xd7-\xd8\xde-\xdf
\xe6\xf0\xf7-\xf8\xfe], U+0110..0111,
U+0126..0127, U+0131, U+0138,
U+0141..0142 ...)
\p{Decomposition_Type: Small} (Short: \p{Dt=Sml}) (26:
U+FE50..FE52, U+FE54..FE66, U+FE68..FE6B)
\p{Decomposition_Type: Sml} \p{Decomposition_Type=Small} (26)
\p{Decomposition_Type: Sqr} \p{Decomposition_Type=Square} (286)
\p{Decomposition_Type: Square} (Short: \p{Dt=Sqr}) (286: U+3250,
U+32CC..32CF, U+32FF..3357,
U+3371..33DF, U+33FF, U+1F130..1F14F ...)
\p{Decomposition_Type: Sub} (Short: \p{Dt=Sub}) (38: U+1D62..1D6A,
U+2080..208E, U+2090..209C, U+2C7C)
\p{Decomposition_Type: Sup} \p{Decomposition_Type=Super} (213)
\p{Decomposition_Type: Super} (Short: \p{Dt=Sup}) (213: [\xaa\xb2-
\xb3\xb9-\xba], U+02B0..02B8,
U+02E0..02E4, U+10FC, U+1D2C..1D2E,
U+1D30..1D3A ...)
\p{Decomposition_Type: Vert} \p{Decomposition_Type=Vertical} (35)
\p{Decomposition_Type: Vertical} (Short: \p{Dt=Vert}) (35: U+309F,
U+30FF, U+FE10..FE19, U+FE30..FE44,
U+FE47..FE48)
\p{Decomposition_Type: Wide} (Short: \p{Dt=Wide}) (104: U+3000,
U+FF01..FF60, U+FFE0..FFE6)
\p{Default_Ignorable_Code_Point} \p{Default_Ignorable_Code_Point=
Y} (Short: \p{DI}) (4174)
\p{Default_Ignorable_Code_Point: N*} (Short: \p{DI=N}, \P{DI})
(1_109_938 plus all above-Unicode code
points: [\x00-\xac\xae-\xff],
U+0100..034E, U+0350..061B,
U+061D..115E, U+1161..17B3, U+17B6..180A
...)
\p{Default_Ignorable_Code_Point: Y*} (Short: \p{DI=Y}, \p{DI})
(4174: [\xad], U+034F, U+061C,
U+115F..1160, U+17B4..17B5, U+180B..180F
...)
\p{Dep} \p{Deprecated} (= \p{Deprecated=Y}) (15)
\p{Dep: *} \p{Deprecated: *}
\p{Deprecated} \p{Deprecated=Y} (Short: \p{Dep}) (15)
\p{Deprecated: N*} (Short: \p{Dep=N}, \P{Dep}) (1_114_097
plus all above-Unicode code points:
U+0000..0148, U+014A..0672,
U+0674..0F76, U+0F78, U+0F7A..17A2,
U+17A5..2069 ...)
\p{Deprecated: Y*} (Short: \p{Dep=Y}, \p{Dep}) (15: U+0149,
U+0673, U+0F77, U+0F79, U+17A3..17A4,
U+206A..206F ...)
\p{Deseret} \p{Script_Extensions=Deseret} (Short:
\p{Dsrt}) (80)
\p{Deva} \p{Devanagari} (= \p{Script_Extensions=
Devanagari}) (NOT \p{Block=Devanagari})
(210)
\p{Devanagari} \p{Script_Extensions=Devanagari} (Short:
\p{Deva}; NOT \p{Block=Devanagari}) (210)
X \p{Devanagari_Ext} \p{Devanagari_Extended} (= \p{Block=
Devanagari_Extended}) (32)
X \p{Devanagari_Extended} \p{Block=Devanagari_Extended} (Short:
\p{InDevanagariExt}) (32)
\p{DI} \p{Default_Ignorable_Code_Point} (=
\p{Default_Ignorable_Code_Point=Y})
(4174)
\p{DI: *} \p{Default_Ignorable_Code_Point: *}
\p{Dia} \p{Diacritic} (= \p{Diacritic=Y}) (1064)
\p{Dia: *} \p{Diacritic: *}
\p{Diacritic} \p{Diacritic=Y} (Short: \p{Dia}) (1064)
\p{Diacritic: N*} (Short: \p{Dia=N}, \P{Dia}) (1_113_048
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=
>?\@A-Z\[\\\]_a-z\{\|\}~\x7f-\xa7\xa9-
\xae\xb0-\xb3\xb5-\xb6\xb9-\xff],
U+0100..02AF, U+034F, U+0358..035C,
U+0363..0373, U+0376..0379 ...)
\p{Diacritic: Y*} (Short: \p{Dia=Y}, \p{Dia}) (1064: [\^`
\xa8\xaf\xb4\xb7-\xb8], U+02B0..034E,
U+0350..0357, U+035D..0362,
U+0374..0375, U+037A ...)
X \p{Diacriticals} \p{Combining_Diacritical_Marks} (=
\p{Block=Combining_Diacritical_Marks})
(112)
X \p{Diacriticals_Ext} \p{Combining_Diacritical_Marks_Extended}
(= \p{Block=
Combining_Diacritical_Marks_Extended})
(80)
X \p{Diacriticals_For_Symbols}
\p{Combining_Diacritical_Marks_For_-
Symbols} (= \p{Block=
Combining_Diacritical_Marks_For_-
Symbols}) (48)
X \p{Diacriticals_Sup} \p{Combining_Diacritical_Marks_Supplement}
(= \p{Block=
Combining_Diacritical_Marks_Supplement})
(64)
\p{Diak} \p{Dives_Akuru} (= \p{Script_Extensions=
Dives_Akuru}) (NOT \p{Block=
Dives_Akuru}) (72)
\p{Digit} \p{XPosixDigit} (= \p{General_Category=
Decimal_Number}) (660)
X \p{Dingbats} \p{Block=Dingbats} (192)
\p{Dives_Akuru} \p{Script_Extensions=Dives_Akuru} (Short:
\p{Diak}; NOT \p{Block=Dives_Akuru}) (72)
\p{Dogr} \p{Dogra} (= \p{Script_Extensions=Dogra})
(NOT \p{Block=Dogra}) (82)
\p{Dogra} \p{Script_Extensions=Dogra} (Short:
\p{Dogr}; NOT \p{Block=Dogra}) (82)
X \p{Domino} \p{Domino_Tiles} (= \p{Block=
Domino_Tiles}) (112)
X \p{Domino_Tiles} \p{Block=Domino_Tiles} (Short:
\p{InDomino}) (112)
\p{Dsrt} \p{Deseret} (= \p{Script_Extensions=
Deseret}) (80)
\p{Dt: *} \p{Decomposition_Type: *}
\p{Dupl} \p{Duployan} (= \p{Script_Extensions=
Duployan}) (NOT \p{Block=Duployan}) (147)
\p{Duployan} \p{Script_Extensions=Duployan} (Short:
\p{Dupl}; NOT \p{Block=Duployan}) (147)
\p{Ea: *} \p{East_Asian_Width: *}
X \p{Early_Dynastic_Cuneiform} \p{Block=Early_Dynastic_Cuneiform}
(208)
\p{East_Asian_Width: A} \p{East_Asian_Width=Ambiguous} (138_739)
\p{East_Asian_Width: Ambiguous} (Short: \p{Ea=A}) (138_739: [\xa1
\xa4\xa7-\xa8\xaa\xad-\xae\xb0-\xb4\xb6-
\xba\xbc-\xbf\xc6\xd0\xd7-\xd8\xde-\xe1
\xe6\xe8-\xea\xec-\xed\xf0\xf2-\xf3\xf7-
\xfa\xfc\xfe], U+0101, U+0111, U+0113,
U+011B, U+0126..0127 ...)
\p{East_Asian_Width: F} \p{East_Asian_Width=Fullwidth} (104)
\p{East_Asian_Width: Fullwidth} (Short: \p{Ea=F}) (104: U+3000,
U+FF01..FF60, U+FFE0..FFE6)
\p{East_Asian_Width: H} \p{East_Asian_Width=Halfwidth} (123)
\p{East_Asian_Width: Halfwidth} (Short: \p{Ea=H}) (123: U+20A9,
U+FF61..FFBE, U+FFC2..FFC7,
U+FFCA..FFCF, U+FFD2..FFD7, U+FFDA..FFDC
...)
\p{East_Asian_Width: N} \p{East_Asian_Width=Neutral} (792_645 plus
all above-Unicode code points)
\p{East_Asian_Width: Na} \p{East_Asian_Width=Narrow} (111)
\p{East_Asian_Width: Narrow} (Short: \p{Ea=Na}) (111: [\x20-\x7e
\xa2-\xa3\xa5-\xa6\xac\xaf],
U+27E6..27ED, U+2985..2986)
\p{East_Asian_Width: Neutral} (Short: \p{Ea=N}) (792_645 plus all
above-Unicode code points: [\x00-\x1f
\x7f-\xa0\xa9\xab\xb5\xbb\xc0-\xc5\xc7-
\xcf\xd1-\xd6\xd9-\xdd\xe2-\xe5\xe7\xeb
\xee-\xef\xf1\xf4-\xf6\xfb\xfd\xff],
U+00FF..0100, U+0102..0110, U+0112,
U+0114..011A, U+011C..0125 ...)
\p{East_Asian_Width: W} \p{East_Asian_Width=Wide} (182_390)
\p{East_Asian_Width: Wide} (Short: \p{Ea=W}) (182_390:
U+1100..115F, U+231A..231B,
U+2329..232A, U+23E9..23EC, U+23F0,
U+23F3 ...)
\p{EBase} \p{Emoji_Modifier_Base} (=
\p{Emoji_Modifier_Base=Y}) (132)
\p{EBase: *} \p{Emoji_Modifier_Base: *}
\p{EComp} \p{Emoji_Component} (= \p{Emoji_Component=
Y}) (146)
\p{EComp: *} \p{Emoji_Component: *}
\p{Egyp} \p{Egyptian_Hieroglyphs} (=
\p{Script_Extensions=
Egyptian_Hieroglyphs}) (NOT \p{Block=
Egyptian_Hieroglyphs}) (1080)
X \p{Egyptian_Hieroglyph_Format_Controls} \p{Block=
Egyptian_Hieroglyph_Format_Controls} (16)
\p{Egyptian_Hieroglyphs} \p{Script_Extensions=
Egyptian_Hieroglyphs} (Short: \p{Egyp};
NOT \p{Block=Egyptian_Hieroglyphs})
(1080)
\p{Elba} \p{Elbasan} (= \p{Script_Extensions=
Elbasan}) (NOT \p{Block=Elbasan}) (40)
\p{Elbasan} \p{Script_Extensions=Elbasan} (Short:
\p{Elba}; NOT \p{Block=Elbasan}) (40)
\p{Elym} \p{Elymaic} (= \p{Script_Extensions=
Elymaic}) (NOT \p{Block=Elymaic}) (23)
\p{Elymaic} \p{Script_Extensions=Elymaic} (Short:
\p{Elym}; NOT \p{Block=Elymaic}) (23)
\p{EMod} \p{Emoji_Modifier} (= \p{Emoji_Modifier=
Y}) (5)
\p{EMod: *} \p{Emoji_Modifier: *}
\p{Emoji} \p{Emoji=Y} (1404)
\p{Emoji: N*} (Single: \P{Emoji}) (1_112_708 plus all
above-Unicode code points: [\x00-\x20!
\"\$\%&\'\(\)+,\-.\/:;<=>?\@A-Z\[\\\]
\^_`a-z\{\|\}~\x7f-\xa8\xaa-\xad\xaf-
\xff], U+0100..203B, U+203D..2048,
U+204A..2121, U+2123..2138, U+213A..2193
...)
\p{Emoji: Y*} (Single: \p{Emoji}) (1404: [#*0-9\xa9
\xae], U+203C, U+2049, U+2122, U+2139,
U+2194..2199 ...)
\p{Emoji_Component} \p{Emoji_Component=Y} (Short: \p{EComp})
(146)
\p{Emoji_Component: N*} (Short: \p{EComp=N}, \P{EComp}) (1_113_966
plus all above-Unicode code points:
[\x00-\x20!\"\$\%&\'\(\)+,\-.\/:;<=>?
\@A-Z\[\\\]\^_`a-z\{\|\}~\x7f-\xff],
U+0100..200C, U+200E..20E2,
U+20E4..FE0E, U+FE10..1F1E5,
U+1F200..1F3FA ...)
\p{Emoji_Component: Y*} (Short: \p{EComp=Y}, \p{EComp}) (146:
[#*0-9], U+200D, U+20E3, U+FE0F,
U+1F1E6..1F1FF, U+1F3FB..1F3FF ...)
\p{Emoji_Modifier} \p{Emoji_Modifier=Y} (Short: \p{EMod}) (5)
\p{Emoji_Modifier: N*} (Short: \p{EMod=N}, \P{EMod}) (1_114_107
plus all above-Unicode code points:
U+0000..1F3FA, U+1F400..infinity)
\p{Emoji_Modifier: Y*} (Short: \p{EMod=Y}, \p{EMod}) (5:
U+1F3FB..1F3FF)
\p{Emoji_Modifier_Base} \p{Emoji_Modifier_Base=Y} (Short:
\p{EBase}) (132)
\p{Emoji_Modifier_Base: N*} (Short: \p{EBase=N}, \P{EBase})
(1_113_980 plus all above-Unicode code
points: U+0000..261C, U+261E..26F8,
U+26FA..2709, U+270E..1F384,
U+1F386..1F3C1, U+1F3C5..1F3C6 ...)
\p{Emoji_Modifier_Base: Y*} (Short: \p{EBase=Y}, \p{EBase}) (132:
U+261D, U+26F9, U+270A..270D, U+1F385,
U+1F3C2..1F3C4, U+1F3C7 ...)
\p{Emoji_Presentation} \p{Emoji_Presentation=Y} (Short:
\p{EPres}) (1185)
\p{Emoji_Presentation: N*} (Short: \p{EPres=N}, \P{EPres})
(1_112_927 plus all above-Unicode code
points: U+0000..2319, U+231C..23E8,
U+23ED..23EF, U+23F1..23F2,
U+23F4..25FC, U+25FF..2613 ...)
\p{Emoji_Presentation: Y*} (Short: \p{EPres=Y}, \p{EPres}) (1185:
U+231A..231B, U+23E9..23EC, U+23F0,
U+23F3, U+25FD..25FE, U+2614..2615 ...)
X \p{Emoticons} \p{Block=Emoticons} (80)
X \p{Enclosed_Alphanum} \p{Enclosed_Alphanumerics} (= \p{Block=
Enclosed_Alphanumerics}) (160)
X \p{Enclosed_Alphanum_Sup} \p{Enclosed_Alphanumeric_Supplement} (=
\p{Block=
Enclosed_Alphanumeric_Supplement}) (256)
X \p{Enclosed_Alphanumeric_Supplement} \p{Block=
Enclosed_Alphanumeric_Supplement}
(Short: \p{InEnclosedAlphanumSup}) (256)
X \p{Enclosed_Alphanumerics} \p{Block=Enclosed_Alphanumerics}
(Short: \p{InEnclosedAlphanum}) (160)
X \p{Enclosed_CJK} \p{Enclosed_CJK_Letters_And_Months} (=
\p{Block=
Enclosed_CJK_Letters_And_Months}) (256)
X \p{Enclosed_CJK_Letters_And_Months} \p{Block=
Enclosed_CJK_Letters_And_Months} (Short:
\p{InEnclosedCJK}) (256)
X \p{Enclosed_Ideographic_Sup} \p{Enclosed_Ideographic_Supplement}
(= \p{Block=
Enclosed_Ideographic_Supplement}) (256)
X \p{Enclosed_Ideographic_Supplement} \p{Block=
Enclosed_Ideographic_Supplement} (Short:
\p{InEnclosedIdeographicSup}) (256)
\p{Enclosing_Mark} \p{General_Category=Enclosing_Mark}
(Short: \p{Me}) (13)
\p{EPres} \p{Emoji_Presentation} (=
\p{Emoji_Presentation=Y}) (1185)
\p{EPres: *} \p{Emoji_Presentation: *}
\p{Ethi} \p{Ethiopic} (= \p{Script_Extensions=
Ethiopic}) (NOT \p{Block=Ethiopic}) (523)
\p{Ethiopic} \p{Script_Extensions=Ethiopic} (Short:
\p{Ethi}; NOT \p{Block=Ethiopic}) (523)
X \p{Ethiopic_Ext} \p{Ethiopic_Extended} (= \p{Block=
Ethiopic_Extended}) (96)
X \p{Ethiopic_Ext_A} \p{Ethiopic_Extended_A} (= \p{Block=
Ethiopic_Extended_A}) (48)
X \p{Ethiopic_Ext_B} \p{Ethiopic_Extended_B} (= \p{Block=
Ethiopic_Extended_B}) (32)
X \p{Ethiopic_Extended} \p{Block=Ethiopic_Extended} (Short:
\p{InEthiopicExt}) (96)
X \p{Ethiopic_Extended_A} \p{Block=Ethiopic_Extended_A} (Short:
\p{InEthiopicExtA}) (48)
X \p{Ethiopic_Extended_B} \p{Block=Ethiopic_Extended_B} (Short:
\p{InEthiopicExtB}) (32)
X \p{Ethiopic_Sup} \p{Ethiopic_Supplement} (= \p{Block=
Ethiopic_Supplement}) (32)
X \p{Ethiopic_Supplement} \p{Block=Ethiopic_Supplement} (Short:
\p{InEthiopicSup}) (32)
\p{Ext} \p{Extender} (= \p{Extender=Y}) (50)
\p{Ext: *} \p{Extender: *}
\p{Extended_Pictographic} \p{Extended_Pictographic=Y} (Short:
\p{ExtPict}) (3537)
\p{Extended_Pictographic: N*} (Short: \p{ExtPict=N}, \P{ExtPict})
(1_110_575 plus all above-Unicode code
points: [\x00-\xa8\xaa-\xad\xaf-\xff],
U+0100..203B, U+203D..2048,
U+204A..2121, U+2123..2138, U+213A..2193
...)
\p{Extended_Pictographic: Y*} (Short: \p{ExtPict=Y}, \p{ExtPict})
(3537: [\xa9\xae], U+203C, U+2049,
U+2122, U+2139, U+2194..2199 ...)
\p{Extender} \p{Extender=Y} (Short: \p{Ext}) (50)
\p{Extender: N*} (Short: \p{Ext=N}, \P{Ext}) (1_114_062
plus all above-Unicode code points:
[\x00-\xb6\xb8-\xff], U+0100..02CF,
U+02D2..063F, U+0641..07F9,
U+07FB..0B54, U+0B56..0E45 ...)
\p{Extender: Y*} (Short: \p{Ext=Y}, \p{Ext}) (50: [\xb7],
U+02D0..02D1, U+0640, U+07FA, U+0B55,
U+0E46 ...)
\p{ExtPict} \p{Extended_Pictographic} (=
\p{Extended_Pictographic=Y}) (3537)
\p{ExtPict: *} \p{Extended_Pictographic: *}
\p{Final_Punctuation} \p{General_Category=Final_Punctuation}
(Short: \p{Pf}) (10)
\p{Format} \p{General_Category=Format} (Short:
\p{Cf}) (163)
\p{Full_Composition_Exclusion} \p{Full_Composition_Exclusion=Y}
(Short: \p{CompEx}) (1120)
\p{Full_Composition_Exclusion: N*} (Short: \p{CompEx=N},
\P{CompEx}) (1_112_992 plus all above-
Unicode code points: U+0000..033F,
U+0342, U+0345..0373, U+0375..037D,
U+037F..0386, U+0388..0957 ...)
\p{Full_Composition_Exclusion: Y*} (Short: \p{CompEx=Y},
\p{CompEx}) (1120: U+0340..0341,
U+0343..0344, U+0374, U+037E, U+0387,
U+0958..095F ...)
\p{Gc: *} \p{General_Category: *}
\p{GCB: *} \p{Grapheme_Cluster_Break: *}
\p{General_Category: C} \p{General_Category=Other} (969_578 plus
all above-Unicode code points)
\p{General_Category: Cased_Letter} [\p{Ll}\p{Lu}\p{Lt}] (Short:
\p{Gc=LC}, \p{LC}) (4089: [A-Za-z\xb5
\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..01BA, U+01BC..01BF,
U+01C4..0293, U+0295..02AF, U+0370..0373
...)
\p{General_Category: Cc} \p{General_Category=Control} (65)
\p{General_Category: Cf} \p{General_Category=Format} (163)
\p{General_Category: Close_Punctuation} (Short: \p{Gc=Pe}, \p{Pe})
(77: [\)\]\}], U+0F3B, U+0F3D, U+169C,
U+2046, U+207E ...)
\p{General_Category: Cn} \p{General_Category=Unassigned} (829_834
plus all above-Unicode code points)
\p{General_Category: Cntrl} \p{General_Category=Control} (65)
\p{General_Category: Co} \p{General_Category=Private_Use} (137_468)
\p{General_Category: Combining_Mark} \p{General_Category=Mark}
(2408)
\p{General_Category: Connector_Punctuation} (Short: \p{Gc=Pc},
\p{Pc}) (10: [_], U+203F..2040, U+2054,
U+FE33..FE34, U+FE4D..FE4F, U+FF3F)
\p{General_Category: Control} (Short: \p{Gc=Cc}, \p{Cc}) (65:
[\x00-\x1f\x7f-\x9f])
\p{General_Category: Cs} \p{General_Category=Surrogate} (2048)
\p{General_Category: Currency_Symbol} (Short: \p{Gc=Sc}, \p{Sc})
(63: [\$\xa2-\xa5], U+058F, U+060B,
U+07FE..07FF, U+09F2..09F3, U+09FB ...)
\p{General_Category: Dash_Punctuation} (Short: \p{Gc=Pd}, \p{Pd})
(26: [\-], U+058A, U+05BE, U+1400,
U+1806, U+2010..2015 ...)
\p{General_Category: Decimal_Number} (Short: \p{Gc=Nd}, \p{Nd})
(660: [0-9], U+0660..0669, U+06F0..06F9,
U+07C0..07C9, U+0966..096F, U+09E6..09EF
...)
\p{General_Category: Digit} \p{General_Category=Decimal_Number}
(660)
\p{General_Category: Enclosing_Mark} (Short: \p{Gc=Me}, \p{Me})
(13: U+0488..0489, U+1ABE, U+20DD..20E0,
U+20E2..20E4, U+A670..A672)
\p{General_Category: Final_Punctuation} (Short: \p{Gc=Pf}, \p{Pf})
(10: [\xbb], U+2019, U+201D, U+203A,
U+2E03, U+2E05 ...)
\p{General_Category: Format} (Short: \p{Gc=Cf}, \p{Cf}) (163:
[\xad], U+0600..0605, U+061C, U+06DD,
U+070F, U+0890..0891 ...)
\p{General_Category: Initial_Punctuation} (Short: \p{Gc=Pi},
\p{Pi}) (12: [\xab], U+2018,
U+201B..201C, U+201F, U+2039, U+2E02 ...)
\p{General_Category: L} \p{General_Category=Letter} (131_756)
X \p{General_Category: L&} \p{General_Category=Cased_Letter} (4089)
X \p{General_Category: L_} \p{General_Category=Cased_Letter} Note
the trailing '_' matters in spite of
loose matching rules. (4089)
\p{General_Category: LC} \p{General_Category=Cased_Letter} (4089)
\p{General_Category: Letter} (Short: \p{Gc=L}, \p{L}) (131_756:
[A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6
\xf8-\xff], U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
\p{General_Category: Letter_Number} (Short: \p{Gc=Nl}, \p{Nl})
(236: U+16EE..16F0, U+2160..2182,
U+2185..2188, U+3007, U+3021..3029,
U+3038..303A ...)
\p{General_Category: Line_Separator} (Short: \p{Gc=Zl}, \p{Zl})
(1: U+2028)
\p{General_Category: Ll} \p{General_Category=Lowercase_Letter}
(/i= General_Category=Cased_Letter)
(2227)
\p{General_Category: Lm} \p{General_Category=Modifier_Letter} (334)
\p{General_Category: Lo} \p{General_Category=Other_Letter}
(127_333)
\p{General_Category: Lowercase_Letter} (Short: \p{Gc=Ll}, \p{Ll};
/i= General_Category=Cased_Letter)
(2227: [a-z\xb5\xdf-\xf6\xf8-\xff],
U+0101, U+0103, U+0105, U+0107, U+0109
...)
\p{General_Category: Lt} \p{General_Category=Titlecase_Letter}
(/i= General_Category=Cased_Letter) (31)
\p{General_Category: Lu} \p{General_Category=Uppercase_Letter}
(/i= General_Category=Cased_Letter)
(1831)
\p{General_Category: M} \p{General_Category=Mark} (2408)
\p{General_Category: Mark} (Short: \p{Gc=M}, \p{M}) (2408:
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{General_Category: Math_Symbol} (Short: \p{Gc=Sm}, \p{Sm}) (948:
[+<=>\|~\xac\xb1\xd7\xf7], U+03F6,
U+0606..0608, U+2044, U+2052,
U+207A..207C ...)
\p{General_Category: Mc} \p{General_Category=Spacing_Mark} (445)
\p{General_Category: Me} \p{General_Category=Enclosing_Mark} (13)
\p{General_Category: Mn} \p{General_Category=Nonspacing_Mark}
(1950)
\p{General_Category: Modifier_Letter} (Short: \p{Gc=Lm}, \p{Lm})
(334: U+02B0..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE, U+0374 ...)
\p{General_Category: Modifier_Symbol} (Short: \p{Gc=Sk}, \p{Sk})
(125: [\^`\xa8\xaf\xb4\xb8],
U+02C2..02C5, U+02D2..02DF,
U+02E5..02EB, U+02ED, U+02EF..02FF ...)
\p{General_Category: N} \p{General_Category=Number} (1791)
\p{General_Category: Nd} \p{General_Category=Decimal_Number} (660)
\p{General_Category: Nl} \p{General_Category=Letter_Number} (236)
\p{General_Category: No} \p{General_Category=Other_Number} (895)
\p{General_Category: Nonspacing_Mark} (Short: \p{Gc=Mn}, \p{Mn})
(1950: U+0300..036F, U+0483..0487,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{General_Category: Number} (Short: \p{Gc=N}, \p{N}) (1791: [0-9
\xb2-\xb3\xb9\xbc-\xbe], U+0660..0669,
U+06F0..06F9, U+07C0..07C9,
U+0966..096F, U+09E6..09EF ...)
\p{General_Category: Open_Punctuation} (Short: \p{Gc=Ps}, \p{Ps})
(79: [\(\[\{], U+0F3A, U+0F3C, U+169B,
U+201A, U+201E ...)
\p{General_Category: Other} (Short: \p{Gc=C}, \p{C}) (969_578 plus
all above-Unicode code points: [\x00-
\x1f\x7f-\x9f\xad], U+0378..0379,
U+0380..0383, U+038B, U+038D, U+03A2 ...)
\p{General_Category: Other_Letter} (Short: \p{Gc=Lo}, \p{Lo})
(127_333: [\xaa\xba], U+01BB,
U+01C0..01C3, U+0294, U+05D0..05EA,
U+05EF..05F2 ...)
\p{General_Category: Other_Number} (Short: \p{Gc=No}, \p{No})
(895: [\xb2-\xb3\xb9\xbc-\xbe],
U+09F4..09F9, U+0B72..0B77,
U+0BF0..0BF2, U+0C78..0C7E, U+0D58..0D5E
...)
\p{General_Category: Other_Punctuation} (Short: \p{Gc=Po}, \p{Po})
(605: [!\"#\%&\'*,.\/:;?\@\\\xa1\xa7
\xb6-\xb7\xbf], U+037E, U+0387,
U+055A..055F, U+0589, U+05C0 ...)
\p{General_Category: Other_Symbol} (Short: \p{Gc=So}, \p{So})
(6605: [\xa6\xa9\xae\xb0], U+0482,
U+058D..058E, U+060E..060F, U+06DE,
U+06E9 ...)
\p{General_Category: P} \p{General_Category=Punctuation} (819)
\p{General_Category: Paragraph_Separator} (Short: \p{Gc=Zp},
\p{Zp}) (1: U+2029)
\p{General_Category: Pc} \p{General_Category=
Connector_Punctuation} (10)
\p{General_Category: Pd} \p{General_Category=Dash_Punctuation} (26)
\p{General_Category: Pe} \p{General_Category=Close_Punctuation}
(77)
\p{General_Category: Pf} \p{General_Category=Final_Punctuation}
(10)
\p{General_Category: Pi} \p{General_Category=Initial_Punctuation}
(12)
\p{General_Category: Po} \p{General_Category=Other_Punctuation}
(605)
\p{General_Category: Private_Use} (Short: \p{Gc=Co}, \p{Co})
(137_468: U+E000..F8FF, U+F0000..FFFFD,
U+100000..10FFFD)
\p{General_Category: Ps} \p{General_Category=Open_Punctuation} (79)
\p{General_Category: Punct} \p{General_Category=Punctuation} (819)
\p{General_Category: Punctuation} (Short: \p{Gc=P}, \p{P}) (819:
[!\"#\%&\'\(\)*,\-.\/:;?\@\[\\\]_\{\}
\xa1\xa7\xab\xb6-\xb7\xbb\xbf], U+037E,
U+0387, U+055A..055F, U+0589..058A,
U+05BE ...)
\p{General_Category: S} \p{General_Category=Symbol} (7741)
\p{General_Category: Sc} \p{General_Category=Currency_Symbol} (63)
\p{General_Category: Separator} (Short: \p{Gc=Z}, \p{Z}) (19:
[\x20\xa0], U+1680, U+2000..200A,
U+2028..2029, U+202F, U+205F ...)
\p{General_Category: Sk} \p{General_Category=Modifier_Symbol} (125)
\p{General_Category: Sm} \p{General_Category=Math_Symbol} (948)
\p{General_Category: So} \p{General_Category=Other_Symbol} (6605)
\p{General_Category: Space_Separator} (Short: \p{Gc=Zs}, \p{Zs})
(17: [\x20\xa0], U+1680, U+2000..200A,
U+202F, U+205F, U+3000)
\p{General_Category: Spacing_Mark} (Short: \p{Gc=Mc}, \p{Mc})
(445: U+0903, U+093B, U+093E..0940,
U+0949..094C, U+094E..094F, U+0982..0983
...)
\p{General_Category: Surrogate} (Short: \p{Gc=Cs}, \p{Cs}) (2048:
U+D800..DFFF)
\p{General_Category: Symbol} (Short: \p{Gc=S}, \p{S}) (7741:
[\$+<=>\^`\|~\xa2-\xa6\xa8-\xa9\xac\xae-
\xb1\xb4\xb8\xd7\xf7], U+02C2..02C5,
U+02D2..02DF, U+02E5..02EB, U+02ED,
U+02EF..02FF ...)
\p{General_Category: Titlecase_Letter} (Short: \p{Gc=Lt}, \p{Lt};
/i= General_Category=Cased_Letter) (31:
U+01C5, U+01C8, U+01CB, U+01F2,
U+1F88..1F8F, U+1F98..1F9F ...)
\p{General_Category: Unassigned} (Short: \p{Gc=Cn}, \p{Cn})
(829_834 plus all above-Unicode code
points: U+0378..0379, U+0380..0383,
U+038B, U+038D, U+03A2, U+0530 ...)
\p{General_Category: Uppercase_Letter} (Short: \p{Gc=Lu}, \p{Lu};
/i= General_Category=Cased_Letter)
(1831: [A-Z\xc0-\xd6\xd8-\xde], U+0100,
U+0102, U+0104, U+0106, U+0108 ...)
\p{General_Category: Z} \p{General_Category=Separator} (19)
\p{General_Category: Zl} \p{General_Category=Line_Separator} (1)
\p{General_Category: Zp} \p{General_Category=Paragraph_Separator}
(1)
\p{General_Category: Zs} \p{General_Category=Space_Separator} (17)
X \p{General_Punctuation} \p{Block=General_Punctuation} (Short:
\p{InPunctuation}) (112)
X \p{Geometric_Shapes} \p{Block=Geometric_Shapes} (96)
X \p{Geometric_Shapes_Ext} \p{Geometric_Shapes_Extended} (=
\p{Block=Geometric_Shapes_Extended})
(128)
X \p{Geometric_Shapes_Extended} \p{Block=Geometric_Shapes_Extended}
(Short: \p{InGeometricShapesExt}) (128)
\p{Geor} \p{Georgian} (= \p{Script_Extensions=
Georgian}) (NOT \p{Block=Georgian}) (174)
\p{Georgian} \p{Script_Extensions=Georgian} (Short:
\p{Geor}; NOT \p{Block=Georgian}) (174)
X \p{Georgian_Ext} \p{Georgian_Extended} (= \p{Block=
Georgian_Extended}) (48)
X \p{Georgian_Extended} \p{Block=Georgian_Extended} (Short:
\p{InGeorgianExt}) (48)
X \p{Georgian_Sup} \p{Georgian_Supplement} (= \p{Block=
Georgian_Supplement}) (48)
X \p{Georgian_Supplement} \p{Block=Georgian_Supplement} (Short:
\p{InGeorgianSup}) (48)
\p{Glag} \p{Glagolitic} (= \p{Script_Extensions=
Glagolitic}) (NOT \p{Block=Glagolitic})
(138)
\p{Glagolitic} \p{Script_Extensions=Glagolitic} (Short:
\p{Glag}; NOT \p{Block=Glagolitic}) (138)
X \p{Glagolitic_Sup} \p{Glagolitic_Supplement} (= \p{Block=
Glagolitic_Supplement}) (48)
X \p{Glagolitic_Supplement} \p{Block=Glagolitic_Supplement} (Short:
\p{InGlagoliticSup}) (48)
\p{Gong} \p{Gunjala_Gondi} (= \p{Script_Extensions=
Gunjala_Gondi}) (NOT \p{Block=
Gunjala_Gondi}) (65)
\p{Gonm} \p{Masaram_Gondi} (= \p{Script_Extensions=
Masaram_Gondi}) (NOT \p{Block=
Masaram_Gondi}) (77)
\p{Goth} \p{Gothic} (= \p{Script_Extensions=
Gothic}) (NOT \p{Block=Gothic}) (27)
\p{Gothic} \p{Script_Extensions=Gothic} (Short:
\p{Goth}; NOT \p{Block=Gothic}) (27)
\p{Gr_Base} \p{Grapheme_Base} (= \p{Grapheme_Base=Y})
(142_539)
\p{Gr_Base: *} \p{Grapheme_Base: *}
\p{Gr_Ext} \p{Grapheme_Extend} (= \p{Grapheme_Extend=
Y}) (2090)
\p{Gr_Ext: *} \p{Grapheme_Extend: *}
\p{Gran} \p{Grantha} (= \p{Script_Extensions=
Grantha}) (NOT \p{Block=Grantha}) (116)
\p{Grantha} \p{Script_Extensions=Grantha} (Short:
\p{Gran}; NOT \p{Block=Grantha}) (116)
\p{Graph} \p{XPosixGraph} (282_146)
\p{Grapheme_Base} \p{Grapheme_Base=Y} (Short: \p{GrBase})
(142_539)
\p{Grapheme_Base: N*} (Short: \p{GrBase=N}, \P{GrBase}) (971_573
plus all above-Unicode code points:
[\x00-\x1f\x7f-\x9f\xad], U+0300..036F,
U+0378..0379, U+0380..0383, U+038B,
U+038D ...)
\p{Grapheme_Base: Y*} (Short: \p{GrBase=Y}, \p{GrBase})
(142_539: [\x20-\x7e\xa0-\xac\xae-\xff],
U+0100..02FF, U+0370..0377,
U+037A..037F, U+0384..038A, U+038C ...)
\p{Grapheme_Cluster_Break: CN} \p{Grapheme_Cluster_Break=Control}
(3886)
\p{Grapheme_Cluster_Break: Control} (Short: \p{GCB=CN}) (3886: [^
\n\r\x20-\x7e\xa0-\xac\xae-\xff],
U+061C, U+180E, U+200B, U+200E..200F,
U+2028..202E ...)
\p{Grapheme_Cluster_Break: CR} (Short: \p{GCB=CR}) (1: [\r])
\p{Grapheme_Cluster_Break: E_Base} (Short: \p{GCB=EB}) (0)
\p{Grapheme_Cluster_Break: E_Base_GAZ} (Short: \p{GCB=EBG}) (0)
\p{Grapheme_Cluster_Break: E_Modifier} (Short: \p{GCB=EM}) (0)
\p{Grapheme_Cluster_Break: EB} \p{Grapheme_Cluster_Break=E_Base}
(0)
\p{Grapheme_Cluster_Break: EBG} \p{Grapheme_Cluster_Break=
E_Base_GAZ} (0)
\p{Grapheme_Cluster_Break: EM} \p{Grapheme_Cluster_Break=
E_Modifier} (0)
\p{Grapheme_Cluster_Break: EX} \p{Grapheme_Cluster_Break=Extend}
(2095)
\p{Grapheme_Cluster_Break: Extend} (Short: \p{GCB=EX}) (2095:
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{Grapheme_Cluster_Break: GAZ} \p{Grapheme_Cluster_Break=
Glue_After_Zwj} (0)
\p{Grapheme_Cluster_Break: Glue_After_Zwj} (Short: \p{GCB=GAZ}) (0)
\p{Grapheme_Cluster_Break: L} (Short: \p{GCB=L}) (125:
U+1100..115F, U+A960..A97C)
\p{Grapheme_Cluster_Break: LF} (Short: \p{GCB=LF}) (1: [\n])
\p{Grapheme_Cluster_Break: LV} (Short: \p{GCB=LV}) (399: U+AC00,
U+AC1C, U+AC38, U+AC54, U+AC70, U+AC8C
...)
\p{Grapheme_Cluster_Break: LVT} (Short: \p{GCB=LVT}) (10_773:
U+AC01..AC1B, U+AC1D..AC37,
U+AC39..AC53, U+AC55..AC6F,
U+AC71..AC8B, U+AC8D..ACA7 ...)
\p{Grapheme_Cluster_Break: Other} (Short: \p{GCB=XX}) (1_096_159
plus all above-Unicode code points:
[\x20-\x7e\xa0-\xac\xae-\xff],
U+0100..02FF, U+0370..0482,
U+048A..0590, U+05BE, U+05C0 ...)
\p{Grapheme_Cluster_Break: PP} \p{Grapheme_Cluster_Break=Prepend}
(26)
\p{Grapheme_Cluster_Break: Prepend} (Short: \p{GCB=PP}) (26:
U+0600..0605, U+06DD, U+070F,
U+0890..0891, U+08E2, U+0D4E ...)
\p{Grapheme_Cluster_Break: Regional_Indicator} (Short: \p{GCB=RI})
(26: U+1F1E6..1F1FF)
\p{Grapheme_Cluster_Break: RI} \p{Grapheme_Cluster_Break=
Regional_Indicator} (26)
\p{Grapheme_Cluster_Break: SM} \p{Grapheme_Cluster_Break=
SpacingMark} (388)
\p{Grapheme_Cluster_Break: SpacingMark} (Short: \p{GCB=SM}) (388:
U+0903, U+093B, U+093E..0940,
U+0949..094C, U+094E..094F, U+0982..0983
...)
\p{Grapheme_Cluster_Break: T} (Short: \p{GCB=T}) (137:
U+11A8..11FF, U+D7CB..D7FB)
\p{Grapheme_Cluster_Break: V} (Short: \p{GCB=V}) (95:
U+1160..11A7, U+D7B0..D7C6)
\p{Grapheme_Cluster_Break: XX} \p{Grapheme_Cluster_Break=Other}
(1_096_159 plus all above-Unicode code
points)
\p{Grapheme_Cluster_Break: ZWJ} (Short: \p{GCB=ZWJ}) (1: U+200D)
\p{Grapheme_Extend} \p{Grapheme_Extend=Y} (Short: \p{GrExt})
(2090)
\p{Grapheme_Extend: N*} (Short: \p{GrExt=N}, \P{GrExt}) (1_112_022
plus all above-Unicode code points:
U+0000..02FF, U+0370..0482,
U+048A..0590, U+05BE, U+05C0, U+05C3 ...)
\p{Grapheme_Extend: Y*} (Short: \p{GrExt=Y}, \p{GrExt}) (2090:
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{Greek} \p{Script_Extensions=Greek} (Short:
\p{Grek}; NOT \p{Greek_And_Coptic}) (522)
X \p{Greek_And_Coptic} \p{Block=Greek_And_Coptic} (Short:
\p{InGreek}) (144)
X \p{Greek_Ext} \p{Greek_Extended} (= \p{Block=
Greek_Extended}) (256)
X \p{Greek_Extended} \p{Block=Greek_Extended} (Short:
\p{InGreekExt}) (256)
\p{Grek} \p{Greek} (= \p{Script_Extensions=Greek})
(NOT \p{Greek_And_Coptic}) (522)
\p{Gujarati} \p{Script_Extensions=Gujarati} (Short:
\p{Gujr}; NOT \p{Block=Gujarati}) (105)
\p{Gujr} \p{Gujarati} (= \p{Script_Extensions=
Gujarati}) (NOT \p{Block=Gujarati}) (105)
\p{Gunjala_Gondi} \p{Script_Extensions=Gunjala_Gondi}
(Short: \p{Gong}; NOT \p{Block=
Gunjala_Gondi}) (65)
\p{Gurmukhi} \p{Script_Extensions=Gurmukhi} (Short:
\p{Guru}; NOT \p{Block=Gurmukhi}) (94)
\p{Guru} \p{Gurmukhi} (= \p{Script_Extensions=
Gurmukhi}) (NOT \p{Block=Gurmukhi}) (94)
X \p{Half_And_Full_Forms} \p{Halfwidth_And_Fullwidth_Forms} (=
\p{Block=Halfwidth_And_Fullwidth_Forms})
(240)
X \p{Half_Marks} \p{Combining_Half_Marks} (= \p{Block=
Combining_Half_Marks}) (16)
X \p{Halfwidth_And_Fullwidth_Forms} \p{Block=
Halfwidth_And_Fullwidth_Forms} (Short:
\p{InHalfAndFullForms}) (240)
\p{Han} \p{Script_Extensions=Han} (94_503)
\p{Hang} \p{Hangul} (= \p{Script_Extensions=
Hangul}) (NOT \p{Hangul_Syllables})
(11_775)
\p{Hangul} \p{Script_Extensions=Hangul} (Short:
\p{Hang}; NOT \p{Hangul_Syllables})
(11_775)
X \p{Hangul_Compatibility_Jamo} \p{Block=Hangul_Compatibility_Jamo}
(Short: \p{InCompatJamo}) (96)
X \p{Hangul_Jamo} \p{Block=Hangul_Jamo} (Short: \p{InJamo})
(256)
X \p{Hangul_Jamo_Extended_A} \p{Block=Hangul_Jamo_Extended_A}
(Short: \p{InJamoExtA}) (32)
X \p{Hangul_Jamo_Extended_B} \p{Block=Hangul_Jamo_Extended_B}
(Short: \p{InJamoExtB}) (80)
\p{Hangul_Syllable_Type: L} \p{Hangul_Syllable_Type=Leading_Jamo}
(125)
\p{Hangul_Syllable_Type: Leading_Jamo} (Short: \p{Hst=L}) (125:
U+1100..115F, U+A960..A97C)
\p{Hangul_Syllable_Type: LV} \p{Hangul_Syllable_Type=LV_Syllable}
(399)
\p{Hangul_Syllable_Type: LV_Syllable} (Short: \p{Hst=LV}) (399:
U+AC00, U+AC1C, U+AC38, U+AC54, U+AC70,
U+AC8C ...)
\p{Hangul_Syllable_Type: LVT} \p{Hangul_Syllable_Type=
LVT_Syllable} (10_773)
\p{Hangul_Syllable_Type: LVT_Syllable} (Short: \p{Hst=LVT})
(10_773: U+AC01..AC1B, U+AC1D..AC37,
U+AC39..AC53, U+AC55..AC6F,
U+AC71..AC8B, U+AC8D..ACA7 ...)
\p{Hangul_Syllable_Type: NA} \p{Hangul_Syllable_Type=
Not_Applicable} (1_102_583 plus all
above-Unicode code points)
\p{Hangul_Syllable_Type: Not_Applicable} (Short: \p{Hst=NA})
(1_102_583 plus all above-Unicode code
points: U+0000..10FF, U+1200..A95F,
U+A97D..ABFF, U+D7A4..D7AF,
U+D7C7..D7CA, U+D7FC..infinity)
\p{Hangul_Syllable_Type: T} \p{Hangul_Syllable_Type=Trailing_Jamo}
(137)
\p{Hangul_Syllable_Type: Trailing_Jamo} (Short: \p{Hst=T}) (137:
U+11A8..11FF, U+D7CB..D7FB)
\p{Hangul_Syllable_Type: V} \p{Hangul_Syllable_Type=Vowel_Jamo}
(95)
\p{Hangul_Syllable_Type: Vowel_Jamo} (Short: \p{Hst=V}) (95:
U+1160..11A7, U+D7B0..D7C6)
X \p{Hangul_Syllables} \p{Block=Hangul_Syllables} (Short:
\p{InHangul}) (11_184)
\p{Hani} \p{Han} (= \p{Script_Extensions=Han})
(94_503)
\p{Hanifi_Rohingya} \p{Script_Extensions=Hanifi_Rohingya}
(Short: \p{Rohg}; NOT \p{Block=
Hanifi_Rohingya}) (55)
\p{Hano} \p{Hanunoo} (= \p{Script_Extensions=
Hanunoo}) (NOT \p{Block=Hanunoo}) (23)
\p{Hanunoo} \p{Script_Extensions=Hanunoo} (Short:
\p{Hano}; NOT \p{Block=Hanunoo}) (23)
\p{Hatr} \p{Hatran} (= \p{Script_Extensions=
Hatran}) (NOT \p{Block=Hatran}) (26)
\p{Hatran} \p{Script_Extensions=Hatran} (Short:
\p{Hatr}; NOT \p{Block=Hatran}) (26)
\p{Hebr} \p{Hebrew} (= \p{Script_Extensions=
Hebrew}) (NOT \p{Block=Hebrew}) (134)
\p{Hebrew} \p{Script_Extensions=Hebrew} (Short:
\p{Hebr}; NOT \p{Block=Hebrew}) (134)
\p{Hex} \p{XPosixXDigit} (= \p{Hex_Digit=Y}) (44)
\p{Hex: *} \p{Hex_Digit: *}
\p{Hex_Digit} \p{XPosixXDigit} (= \p{Hex_Digit=Y}) (44)
\p{Hex_Digit: N*} (Short: \p{Hex=N}, \P{Hex}) (1_114_068
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/:;<=>?
\@G-Z\[\\\]\^_`g-z\{\|\}~\x7f-\xff],
U+0100..FF0F, U+FF1A..FF20,
U+FF27..FF40, U+FF47..infinity)
\p{Hex_Digit: Y*} (Short: \p{Hex=Y}, \p{Hex}) (44: [0-9A-Fa-
f], U+FF10..FF19, U+FF21..FF26,
U+FF41..FF46)
X \p{High_Private_Use_Surrogates} \p{Block=
High_Private_Use_Surrogates} (Short:
\p{InHighPUSurrogates}) (128)
X \p{High_PU_Surrogates} \p{High_Private_Use_Surrogates} (=
\p{Block=High_Private_Use_Surrogates})
(128)
X \p{High_Surrogates} \p{Block=High_Surrogates} (896)
\p{Hira} \p{Hiragana} (= \p{Script_Extensions=
Hiragana}) (NOT \p{Block=Hiragana}) (432)
\p{Hiragana} \p{Script_Extensions=Hiragana} (Short:
\p{Hira}; NOT \p{Block=Hiragana}) (432)
\p{Hluw} \p{Anatolian_Hieroglyphs} (=
\p{Script_Extensions=
Anatolian_Hieroglyphs}) (NOT \p{Block=
Anatolian_Hieroglyphs}) (583)
\p{Hmng} \p{Pahawh_Hmong} (= \p{Script_Extensions=
Pahawh_Hmong}) (NOT \p{Block=
Pahawh_Hmong}) (127)
\p{Hmnp} \p{Nyiakeng_Puachue_Hmong} (=
\p{Script_Extensions=
Nyiakeng_Puachue_Hmong}) (NOT \p{Block=
Nyiakeng_Puachue_Hmong}) (71)
\p{HorizSpace} \p{XPosixBlank} (18)
\p{Hst: *} \p{Hangul_Syllable_Type: *}
\p{Hung} \p{Old_Hungarian} (= \p{Script_Extensions=
Old_Hungarian}) (NOT \p{Block=
Old_Hungarian}) (108)
D \p{Hyphen} \p{Hyphen=Y} (11)
D \p{Hyphen: N*} Supplanted by Line_Break property values;
see www.unicode.org/reports/tr14
(Single: \P{Hyphen}) (1_114_101 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*+,.\/0-9:;<=>?\@A-Z
\[\\\]\^_`a-z\{\|\}~\x7f-\xac\xae-\xff],
U+0100..0589, U+058B..1805,
U+1807..200F, U+2012..2E16, U+2E18..30FA
...)
D \p{Hyphen: Y*} Supplanted by Line_Break property values;
see www.unicode.org/reports/tr14
(Single: \p{Hyphen}) (11: [\-\xad],
U+058A, U+1806, U+2010..2011, U+2E17,
U+30FB ...)
\p{ID_Continue} \p{ID_Continue=Y} (Short: \p{IDC}; NOT
\p{Ideographic_Description_Characters})
(135_072)
\p{ID_Continue: N*} (Short: \p{IDC=N}, \P{IDC}) (979_040 plus
all above-Unicode code points: [\x00-
\x20!\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@
\[\\\]\^`\{\|\}~\x7f-\xa9\xab-\xb4\xb6
\xb8-\xb9\xbb-\xbf\xd7\xf7],
U+02C2..02C5, U+02D2..02DF,
U+02E5..02EB, U+02ED, U+02EF..02FF ...)
\p{ID_Continue: Y*} (Short: \p{IDC=Y}, \p{IDC}) (135_072:
[0-9A-Z_a-z\xaa\xb5\xb7\xba\xc0-\xd6
\xd8-\xf6\xf8-\xff], U+0100..02C1,
U+02C6..02D1, U+02E0..02E4, U+02EC,
U+02EE ...)
\p{ID_Start} \p{ID_Start=Y} (Short: \p{IDS}) (131_997)
\p{ID_Start: N*} (Short: \p{IDS=N}, \P{IDS}) (982_115 plus
all above-Unicode code points: [\x00-
\x20!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=>?\@
\[\\\]\^_`\{\|\}~\x7f-\xa9\xab-\xb4\xb6-
\xb9\xbb-\xbf\xd7\xf7], U+02C2..02C5,
U+02D2..02DF, U+02E5..02EB, U+02ED,
U+02EF..036F ...)
\p{ID_Start: Y*} (Short: \p{IDS=Y}, \p{IDS}) (131_997: [A-
Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-
\xff], U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
\p{IDC} \p{ID_Continue} (= \p{ID_Continue=Y}) (NOT
\p{Ideographic_Description_Characters})
(135_072)
\p{IDC: *} \p{ID_Continue: *}
\p{Identifier_Status: Allowed} (107_957: [\'\-.0-9:A-Z_a-z\xb7
\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..0131, U+0134..013E,
U+0141..0148, U+014A..017E, U+018F ...)
\p{Identifier_Status: Restricted} (1_006_155 plus all above-
Unicode code points: [\x00-\x20!\"#\$
\%&\(\)*+,\/;<=>?\@\[\\\]\^`\{\|\}~\x7f-
\xb6\xb8-\xbf\xd7\xf7], U+0132..0133,
U+013F..0140, U+0149, U+017F..018E,
U+0190..019F ...)
\p{Identifier_Type: Default_Ignorable} (396: [\xad], U+034F,
U+061C, U+115F..1160, U+17B4..17B5,
U+180B..180F ...)
\p{Identifier_Type: Deprecated} (15: U+0149, U+0673, U+0F77,
U+0F79, U+17A3..17A4, U+206A..206F ...)
\p{Identifier_Type: Exclusion} (17_080: U+03E2..03EF,
U+0800..082D, U+0830..083E,
U+1680..169C, U+16A0..16EA, U+16EE..16F8
...)
\p{Identifier_Type: Inclusion} (19: [\'\-.:\xb7], U+0375, U+058A,
U+05F3..05F4, U+06FD..06FE, U+0F0B ...)
\p{Identifier_Type: Limited_Use} (5268: U+0700..070D,
U+070F..074A, U+074D..074F,
U+07C0..07FA, U+07FD..07FF, U+0840..085B
...)
\p{Identifier_Type: Not_Character} (969_409 plus all above-Unicode
code points: [^\t\n\cK\f\r\x20-\x7e\x85
\xa0-\xff], U+0378..0379, U+0380..0383,
U+038B, U+038D, U+03A2 ...)
\p{Identifier_Type: Not_NFKC} (4859: [\xa0\xa8\xaa\xaf\xb2-\xb5
\xb8-\xba\xbc-\xbe], U+0132..0133,
U+013F..0140, U+017F, U+01C4..01CC,
U+01F1..01F3 ...)
\p{Identifier_Type: Not_XID} (8198: [\t\n\cK\f\r\x20!\"#\$\%&
\(\)*+,\/;<=>?\@\[\\\]\^`\{\|\}~\x85
\xa1-\xa7\xa9\xab-\xac\xae\xb0-\xb1\xb6
\xbb\xbf\xd7\xf7], U+02C2..02C5,
U+02D2..02D7, U+02DE..02DF,
U+02E5..02EB, U+02ED ...)
\p{Identifier_Type: Obsolete} (1627: U+018D, U+01AA..01AB,
U+01B9..01BB, U+01BE..01BF,
U+01F6..01F7, U+021C..021D ...)
\p{Identifier_Type: Recommended} (107_938: [0-9A-Z_a-z\xc0-\xd6
\xd8-\xf6\xf8-\xff], U+0100..0131,
U+0134..013E, U+0141..0148,
U+014A..017E, U+018F ...)
\p{Identifier_Type: Technical} (1660: U+0180, U+018D,
U+01AA..01AB, U+01BA..01BB, U+01BE,
U+01C0..01C3 ...)
\p{Identifier_Type: Uncommon_Use} (393: U+0181..018C, U+018E,
U+0190..019F, U+01A2..01A9,
U+01AC..01AE, U+01B1..01B8 ...)
\p{Ideo} \p{Ideographic} (= \p{Ideographic=Y})
(101_661)
\p{Ideo: *} \p{Ideographic: *}
\p{Ideographic} \p{Ideographic=Y} (Short: \p{Ideo})
(101_661)
\p{Ideographic: N*} (Short: \p{Ideo=N}, \P{Ideo}) (1_012_451
plus all above-Unicode code points:
U+0000..3005, U+3008..3020,
U+302A..3037, U+303B..33FF,
U+4DC0..4DFF, U+A000..F8FF ...)
\p{Ideographic: Y*} (Short: \p{Ideo=Y}, \p{Ideo}) (101_661:
U+3006..3007, U+3021..3029,
U+3038..303A, U+3400..4DBF,
U+4E00..9FFF, U+F900..FA6D ...)
X \p{Ideographic_Description_Characters} \p{Block=
Ideographic_Description_Characters}
(Short: \p{InIDC}) (16)
X \p{Ideographic_Symbols} \p{Ideographic_Symbols_And_Punctuation} (=
\p{Block=
Ideographic_Symbols_And_Punctuation})
(32)
X \p{Ideographic_Symbols_And_Punctuation} \p{Block=
Ideographic_Symbols_And_Punctuation}
(Short: \p{InIdeographicSymbols}) (32)
\p{IDS} \p{ID_Start} (= \p{ID_Start=Y}) (131_997)
\p{IDS: *} \p{ID_Start: *}
\p{IDS_Binary_Operator} \p{IDS_Binary_Operator=Y} (Short:
\p{IDSB}) (10)
\p{IDS_Binary_Operator: N*} (Short: \p{IDSB=N}, \P{IDSB})
(1_114_102 plus all above-Unicode code
points: U+0000..2FEF, U+2FF2..2FF3,
U+2FFC..infinity)
\p{IDS_Binary_Operator: Y*} (Short: \p{IDSB=Y}, \p{IDSB}) (10:
U+2FF0..2FF1, U+2FF4..2FFB)
\p{IDS_Trinary_Operator} \p{IDS_Trinary_Operator=Y} (Short:
\p{IDST}) (2)
\p{IDS_Trinary_Operator: N*} (Short: \p{IDST=N}, \P{IDST})
(1_114_110 plus all above-Unicode code
points: U+0000..2FF1, U+2FF4..infinity)
\p{IDS_Trinary_Operator: Y*} (Short: \p{IDST=Y}, \p{IDST}) (2:
U+2FF2..2FF3)
\p{IDSB} \p{IDS_Binary_Operator} (=
\p{IDS_Binary_Operator=Y}) (10)
\p{IDSB: *} \p{IDS_Binary_Operator: *}
\p{IDST} \p{IDS_Trinary_Operator} (=
\p{IDS_Trinary_Operator=Y}) (2)
\p{IDST: *} \p{IDS_Trinary_Operator: *}
\p{Imperial_Aramaic} \p{Script_Extensions=Imperial_Aramaic}
(Short: \p{Armi}; NOT \p{Block=
Imperial_Aramaic}) (31)
\p{In: *} \p{Present_In: *} (Perl extension)
X \p{In_*} \p{Block: *}
X \p{Indic_Number_Forms} \p{Common_Indic_Number_Forms} (= \p{Block=
Common_Indic_Number_Forms}) (16)
\p{Indic_Positional_Category: Bottom} (Short: \p{InPC=Bottom})
(352: U+093C, U+0941..0944, U+094D,
U+0952, U+0956..0957, U+0962..0963 ...)
\p{Indic_Positional_Category: Bottom_And_Left} (Short: \p{InPC=
BottomAndLeft}) (1: U+A9BF)
\p{Indic_Positional_Category: Bottom_And_Right} (Short: \p{InPC=
BottomAndRight}) (4: U+1B3B, U+A9BE,
U+A9C0, U+11942)
\p{Indic_Positional_Category: Left} (Short: \p{InPC=Left}) (64:
U+093F, U+094E, U+09BF, U+09C7..09C8,
U+0A3F, U+0ABF ...)
\p{Indic_Positional_Category: Left_And_Right} (Short: \p{InPC=
LeftAndRight}) (22: U+09CB..09CC,
U+0B4B, U+0BCA..0BCC, U+0D4A..0D4C,
U+0DDC, U+0DDE ...)
\p{Indic_Positional_Category: NA} (Short: \p{InPC=NA}) (1_112_896
plus all above-Unicode code points:
U+0000..08FF, U+0904..0939, U+093D,
U+0950, U+0958..0961, U+0964..0980 ...)
\p{Indic_Positional_Category: Overstruck} (Short: \p{InPC=
Overstruck}) (10: U+1CD4, U+1CE2..1CE8,
U+10A01, U+10A06)
\p{Indic_Positional_Category: Right} (Short: \p{InPC=Right}) (290:
U+0903, U+093B, U+093E, U+0940,
U+0949..094C, U+094F ...)
\p{Indic_Positional_Category: Top} (Short: \p{InPC=Top}) (418:
U+0900..0902, U+093A, U+0945..0948,
U+0951, U+0953..0955, U+0981 ...)
\p{Indic_Positional_Category: Top_And_Bottom} (Short: \p{InPC=
TopAndBottom}) (10: U+0C48, U+0F73,
U+0F76..0F79, U+0F81, U+1B3C,
U+1112E..1112F)
\p{Indic_Positional_Category: Top_And_Bottom_And_Left} (Short:
\p{InPC=TopAndBottomAndLeft}) (2:
U+103C, U+1171E)
\p{Indic_Positional_Category: Top_And_Bottom_And_Right} (Short:
\p{InPC=TopAndBottomAndRight}) (1:
U+1B3D)
\p{Indic_Positional_Category: Top_And_Left} (Short: \p{InPC=
TopAndLeft}) (6: U+0B48, U+0DDA, U+17BE,
U+1C29, U+114BB, U+115B9)
\p{Indic_Positional_Category: Top_And_Left_And_Right} (Short:
\p{InPC=TopAndLeftAndRight}) (4: U+0B4C,
U+0DDD, U+17BF, U+115BB)
\p{Indic_Positional_Category: Top_And_Right} (Short: \p{InPC=
TopAndRight}) (13: U+0AC9, U+0B57,
U+0CC0, U+0CC7..0CC8, U+0CCA..0CCB,
U+1925..1926 ...)
\p{Indic_Positional_Category: Visual_Order_Left} (Short: \p{InPC=
VisualOrderLeft}) (19: U+0E40..0E44,
U+0EC0..0EC4, U+19B5..19B7, U+19BA,
U+AAB5..AAB6, U+AAB9 ...)
X \p{Indic_Siyaq_Numbers} \p{Block=Indic_Siyaq_Numbers} (80)
\p{Indic_Syllabic_Category: Avagraha} (Short: \p{InSC=Avagraha})
(17: U+093D, U+09BD, U+0ABD, U+0B3D,
U+0C3D, U+0CBD ...)
\p{Indic_Syllabic_Category: Bindu} (Short: \p{InSC=Bindu}) (91:
U+0900..0902, U+0981..0982, U+09FC,
U+0A01..0A02, U+0A70, U+0A81..0A82 ...)
\p{Indic_Syllabic_Category: Brahmi_Joining_Number} (Short:
\p{InSC=BrahmiJoiningNumber}) (20:
U+11052..11065)
\p{Indic_Syllabic_Category: Cantillation_Mark} (Short: \p{InSC=
CantillationMark}) (59: U+0951..0952,
U+0A51, U+0AFA..0AFC, U+1CD0..1CD2,
U+1CD4..1CE1, U+1CF4 ...)
\p{Indic_Syllabic_Category: Consonant} (Short: \p{InSC=Consonant})
(2206: U+0915..0939, U+0958..095F,
U+0978..097F, U+0995..09A8,
U+09AA..09B0, U+09B2 ...)
\p{Indic_Syllabic_Category: Consonant_Dead} (Short: \p{InSC=
ConsonantDead}) (14: U+09CE, U+0C5D,
U+0CDD, U+0D54..0D56, U+0D7A..0D7F,
U+1CF2..1CF3)
\p{Indic_Syllabic_Category: Consonant_Final} (Short: \p{InSC=
ConsonantFinal}) (70: U+1930..1931,
U+1933..1939, U+19C1..19C7,
U+1A58..1A59, U+1B03, U+1B81 ...)
\p{Indic_Syllabic_Category: Consonant_Head_Letter} (Short:
\p{InSC=ConsonantHeadLetter}) (5:
U+0F88..0F8C)
\p{Indic_Syllabic_Category: Consonant_Initial_Postfixed} (Short:
\p{InSC=ConsonantInitialPostfixed}) (1:
U+1A5A)
\p{Indic_Syllabic_Category: Consonant_Killer} (Short: \p{InSC=
ConsonantKiller}) (2: U+0E4C, U+17CD)
\p{Indic_Syllabic_Category: Consonant_Medial} (Short: \p{InSC=
ConsonantMedial}) (31: U+0A75,
U+0EBC..0EBD, U+103B..103E,
U+105E..1060, U+1082, U+1A55..1A56 ...)
\p{Indic_Syllabic_Category: Consonant_Placeholder} (Short:
\p{InSC=ConsonantPlaceholder}) (22: [\-
\xa0\xd7], U+0980, U+0A72..0A73, U+104B,
U+104E, U+1900 ...)
\p{Indic_Syllabic_Category: Consonant_Preceding_Repha} (Short:
\p{InSC=ConsonantPrecedingRepha}) (3:
U+0D4E, U+11941, U+11D46)
\p{Indic_Syllabic_Category: Consonant_Prefixed} (Short: \p{InSC=
ConsonantPrefixed}) (10: U+111C2..111C3,
U+1193F, U+11A3A, U+11A84..11A89)
\p{Indic_Syllabic_Category: Consonant_Subjoined} (Short: \p{InSC=
ConsonantSubjoined}) (94: U+0F8D..0F97,
U+0F99..0FBC, U+1929..192B, U+1A57,
U+1A5B..1A5E, U+1BA1..1BA3 ...)
\p{Indic_Syllabic_Category: Consonant_Succeeding_Repha} (Short:
\p{InSC=ConsonantSucceedingRepha}) (1:
U+17CC)
\p{Indic_Syllabic_Category: Consonant_With_Stacker} (Short:
\p{InSC=ConsonantWithStacker}) (8:
U+0CF1..0CF2, U+1CF5..1CF6,
U+11003..11004, U+11460..11461)
\p{Indic_Syllabic_Category: Gemination_Mark} (Short: \p{InSC=
GeminationMark}) (3: U+0A71, U+11237,
U+11A98)
\p{Indic_Syllabic_Category: Invisible_Stacker} (Short: \p{InSC=
InvisibleStacker}) (12: U+1039, U+17D2,
U+1A60, U+1BAB, U+AAF6, U+10A3F ...)
\p{Indic_Syllabic_Category: Joiner} (Short: \p{InSC=Joiner}) (1:
U+200D)
\p{Indic_Syllabic_Category: Modifying_Letter} (Short: \p{InSC=
ModifyingLetter}) (1: U+0B83)
\p{Indic_Syllabic_Category: Non_Joiner} (Short: \p{InSC=
NonJoiner}) (1: U+200C)
\p{Indic_Syllabic_Category: Nukta} (Short: \p{InSC=Nukta}) (32:
U+093C, U+09BC, U+0A3C, U+0ABC,
U+0AFD..0AFF, U+0B3C ...)
\p{Indic_Syllabic_Category: Number} (Short: \p{InSC=Number}) (491:
[0-9], U+0966..096F, U+09E6..09EF,
U+0A66..0A6F, U+0AE6..0AEF, U+0B66..0B6F
...)
\p{Indic_Syllabic_Category: Number_Joiner} (Short: \p{InSC=
NumberJoiner}) (1: U+1107F)
\p{Indic_Syllabic_Category: Other} (Short: \p{InSC=Other})
(1_109_551 plus all above-Unicode code
points: [\x00-\x20!\"#\$\%&\'\(\)*+,.
\/:;<=>?\@A-Z\[\\\]\^_`a-z\{\|\}~\x7f-
\x9f\xa1-\xb1\xb4-\xd6\xd8-\xff],
U+0100..08FF, U+0950, U+0953..0954,
U+0964..0965, U+0970..0971 ...)
\p{Indic_Syllabic_Category: Pure_Killer} (Short: \p{InSC=
PureKiller}) (25: U+0D3B..0D3C, U+0E3A,
U+0E4E, U+0EBA, U+0F84, U+103A ...)
\p{Indic_Syllabic_Category: Register_Shifter} (Short: \p{InSC=
RegisterShifter}) (2: U+17C9..17CA)
\p{Indic_Syllabic_Category: Syllable_Modifier} (Short: \p{InSC=
SyllableModifier}) (25: [\xb2-\xb3],
U+09FE, U+0F35, U+0F37, U+0FC6, U+17CB
...)
\p{Indic_Syllabic_Category: Tone_Letter} (Short: \p{InSC=
ToneLetter}) (7: U+1970..1974, U+AAC0,
U+AAC2)
\p{Indic_Syllabic_Category: Tone_Mark} (Short: \p{InSC=ToneMark})
(42: U+0E48..0E4B, U+0EC8..0ECB, U+1037,
U+1063..1064, U+1069..106D, U+1087..108D
...)
\p{Indic_Syllabic_Category: Virama} (Short: \p{InSC=Virama}) (27:
U+094D, U+09CD, U+0A4D, U+0ACD, U+0B4D,
U+0BCD ...)
\p{Indic_Syllabic_Category: Visarga} (Short: \p{InSC=Visarga})
(35: U+0903, U+0983, U+0A03, U+0A83,
U+0B03, U+0C03 ...)
\p{Indic_Syllabic_Category: Vowel} (Short: \p{InSC=Vowel}) (30:
U+1963..196D, U+A85E..A861, U+A866,
U+A922..A92A, U+11150..11154)
\p{Indic_Syllabic_Category: Vowel_Dependent} (Short: \p{InSC=
VowelDependent}) (686: U+093A..093B,
U+093E..094C, U+094E..094F,
U+0955..0957, U+0962..0963, U+09BE..09C4
...)
\p{Indic_Syllabic_Category: Vowel_Independent} (Short: \p{InSC=
VowelIndependent}) (486: U+0904..0914,
U+0960..0961, U+0972..0977,
U+0985..098C, U+098F..0990, U+0993..0994
...)
\p{Inherited} \p{Script_Extensions=Inherited} (Short:
\p{Zinh}) (586)
\p{Initial_Punctuation} \p{General_Category=Initial_Punctuation}
(Short: \p{Pi}) (12)
\p{InPC: *} \p{Indic_Positional_Category: *}
\p{InSC: *} \p{Indic_Syllabic_Category: *}
\p{Inscriptional_Pahlavi} \p{Script_Extensions=
Inscriptional_Pahlavi} (Short: \p{Phli};
NOT \p{Block=Inscriptional_Pahlavi}) (27)
\p{Inscriptional_Parthian} \p{Script_Extensions=
Inscriptional_Parthian} (Short:
\p{Prti}; NOT \p{Block=
Inscriptional_Parthian}) (30)
X \p{IPA_Ext} \p{IPA_Extensions} (= \p{Block=
IPA_Extensions}) (96)
X \p{IPA_Extensions} \p{Block=IPA_Extensions} (Short:
\p{InIPAExt}) (96)
\p{Is_*} \p{*} (Any exceptions are individually
noted beginning with the word NOT.) If
an entry has flag(s) at its beginning,
like "D", the "Is_" form has the same
flag(s)
\p{Ital} \p{Old_Italic} (= \p{Script_Extensions=
Old_Italic}) (NOT \p{Block=Old_Italic})
(39)
X \p{Jamo} \p{Hangul_Jamo} (= \p{Block=Hangul_Jamo})
(256)
X \p{Jamo_Ext_A} \p{Hangul_Jamo_Extended_A} (= \p{Block=
Hangul_Jamo_Extended_A}) (32)
X \p{Jamo_Ext_B} \p{Hangul_Jamo_Extended_B} (= \p{Block=
Hangul_Jamo_Extended_B}) (80)
\p{Java} \p{Javanese} (= \p{Script_Extensions=
Javanese}) (NOT \p{Block=Javanese}) (91)
\p{Javanese} \p{Script_Extensions=Javanese} (Short:
\p{Java}; NOT \p{Block=Javanese}) (91)
\p{Jg: *} \p{Joining_Group: *}
\p{Join_C} \p{Join_Control} (= \p{Join_Control=Y}) (2)
\p{Join_C: *} \p{Join_Control: *}
\p{Join_Control} \p{Join_Control=Y} (Short: \p{JoinC}) (2)
\p{Join_Control: N*} (Short: \p{JoinC=N}, \P{JoinC}) (1_114_110
plus all above-Unicode code points:
U+0000..200B, U+200E..infinity)
\p{Join_Control: Y*} (Short: \p{JoinC=Y}, \p{JoinC}) (2:
U+200C..200D)
\p{Joining_Group: African_Feh} (Short: \p{Jg=AfricanFeh}) (1:
U+08BB)
\p{Joining_Group: African_Noon} (Short: \p{Jg=AfricanNoon}) (1:
U+08BD)
\p{Joining_Group: African_Qaf} (Short: \p{Jg=AfricanQaf}) (2:
U+08BC, U+08C4)
\p{Joining_Group: Ain} (Short: \p{Jg=Ain}) (9: U+0639..063A,
U+06A0, U+06FC, U+075D..075F, U+08B3,
U+08C3)
\p{Joining_Group: Alaph} (Short: \p{Jg=Alaph}) (1: U+0710)
\p{Joining_Group: Alef} (Short: \p{Jg=Alef}) (29: U+0622..0623,
U+0625, U+0627, U+0671..0673, U+0675,
U+0773..0774 ...)
\p{Joining_Group: Beh} (Short: \p{Jg=Beh}) (27: U+0628,
U+062A..062B, U+066E, U+0679..0680,
U+0750..0756, U+08A0..08A1 ...)
\p{Joining_Group: Beth} (Short: \p{Jg=Beth}) (2: U+0712, U+072D)
\p{Joining_Group: Burushaski_Yeh_Barree} (Short: \p{Jg=
BurushaskiYehBarree}) (2: U+077A..077B)
\p{Joining_Group: Dal} (Short: \p{Jg=Dal}) (15: U+062F..0630,
U+0688..0690, U+06EE, U+0759..075A,
U+08AE)
\p{Joining_Group: Dalath_Rish} (Short: \p{Jg=DalathRish}) (4:
U+0715..0716, U+072A, U+072F)
\p{Joining_Group: E} (Short: \p{Jg=E}) (1: U+0725)
\p{Joining_Group: Farsi_Yeh} (Short: \p{Jg=FarsiYeh}) (7:
U+063D..063F, U+06CC, U+06CE,
U+0775..0776)
\p{Joining_Group: Fe} (Short: \p{Jg=Fe}) (1: U+074F)
\p{Joining_Group: Feh} (Short: \p{Jg=Feh}) (10: U+0641,
U+06A1..06A6, U+0760..0761, U+08A4)
\p{Joining_Group: Final_Semkath} (Short: \p{Jg=FinalSemkath}) (1:
U+0724)
\p{Joining_Group: Gaf} (Short: \p{Jg=Gaf}) (17: U+063B..063C,
U+06A9, U+06AB, U+06AF..06B4,
U+0762..0764, U+088D ...)
\p{Joining_Group: Gamal} (Short: \p{Jg=Gamal}) (3: U+0713..0714,
U+072E)
\p{Joining_Group: Hah} (Short: \p{Jg=Hah}) (22: U+062C..062E,
U+0681..0687, U+06BF, U+0757..0758,
U+076E..076F, U+0772 ...)
\p{Joining_Group: Hamza_On_Heh_Goal} (Short: \p{Jg=
HamzaOnHehGoal}) (1: U+06C3)
\p{Joining_Group: Hanifi_Rohingya_Kinna_Ya} (Short: \p{Jg=
HanifiRohingyaKinnaYa}) (4: U+10D19,
U+10D1E, U+10D20, U+10D23)
\p{Joining_Group: Hanifi_Rohingya_Pa} (Short: \p{Jg=
HanifiRohingyaPa}) (3: U+10D02, U+10D09,
U+10D1C)
\p{Joining_Group: He} (Short: \p{Jg=He}) (1: U+0717)
\p{Joining_Group: Heh} (Short: \p{Jg=Heh}) (1: U+0647)
\p{Joining_Group: Heh_Goal} (Short: \p{Jg=HehGoal}) (2:
U+06C1..06C2)
\p{Joining_Group: Heth} (Short: \p{Jg=Heth}) (1: U+071A)
\p{Joining_Group: Kaf} (Short: \p{Jg=Kaf}) (6: U+0643,
U+06AC..06AE, U+077F, U+08B4)
\p{Joining_Group: Kaph} (Short: \p{Jg=Kaph}) (1: U+071F)
\p{Joining_Group: Khaph} (Short: \p{Jg=Khaph}) (1: U+074E)
\p{Joining_Group: Knotted_Heh} (Short: \p{Jg=KnottedHeh}) (2:
U+06BE, U+06FF)
\p{Joining_Group: Lam} (Short: \p{Jg=Lam}) (8: U+0644,
U+06B5..06B8, U+076A, U+08A6, U+08C7)
\p{Joining_Group: Lamadh} (Short: \p{Jg=Lamadh}) (1: U+0720)
\p{Joining_Group: Malayalam_Bha} (Short: \p{Jg=MalayalamBha}) (1:
U+0866)
\p{Joining_Group: Malayalam_Ja} (Short: \p{Jg=MalayalamJa}) (1:
U+0861)
\p{Joining_Group: Malayalam_Lla} (Short: \p{Jg=MalayalamLla}) (1:
U+0868)
\p{Joining_Group: Malayalam_Llla} (Short: \p{Jg=MalayalamLlla})
(1: U+0869)
\p{Joining_Group: Malayalam_Nga} (Short: \p{Jg=MalayalamNga}) (1:
U+0860)
\p{Joining_Group: Malayalam_Nna} (Short: \p{Jg=MalayalamNna}) (1:
U+0864)
\p{Joining_Group: Malayalam_Nnna} (Short: \p{Jg=MalayalamNnna})
(1: U+0865)
\p{Joining_Group: Malayalam_Nya} (Short: \p{Jg=MalayalamNya}) (1:
U+0862)
\p{Joining_Group: Malayalam_Ra} (Short: \p{Jg=MalayalamRa}) (1:
U+0867)
\p{Joining_Group: Malayalam_Ssa} (Short: \p{Jg=MalayalamSsa}) (1:
U+086A)
\p{Joining_Group: Malayalam_Tta} (Short: \p{Jg=MalayalamTta}) (1:
U+0863)
\p{Joining_Group: Manichaean_Aleph} (Short: \p{Jg=
ManichaeanAleph}) (1: U+10AC0)
\p{Joining_Group: Manichaean_Ayin} (Short: \p{Jg=ManichaeanAyin})
(2: U+10AD9..10ADA)
\p{Joining_Group: Manichaean_Beth} (Short: \p{Jg=ManichaeanBeth})
(2: U+10AC1..10AC2)
\p{Joining_Group: Manichaean_Daleth} (Short: \p{Jg=
ManichaeanDaleth}) (1: U+10AC5)
\p{Joining_Group: Manichaean_Dhamedh} (Short: \p{Jg=
ManichaeanDhamedh}) (1: U+10AD4)
\p{Joining_Group: Manichaean_Five} (Short: \p{Jg=ManichaeanFive})
(1: U+10AEC)
\p{Joining_Group: Manichaean_Gimel} (Short: \p{Jg=
ManichaeanGimel}) (2: U+10AC3..10AC4)
\p{Joining_Group: Manichaean_Heth} (Short: \p{Jg=ManichaeanHeth})
(1: U+10ACD)
\p{Joining_Group: Manichaean_Hundred} (Short: \p{Jg=
ManichaeanHundred}) (1: U+10AEF)
\p{Joining_Group: Manichaean_Kaph} (Short: \p{Jg=ManichaeanKaph})
(3: U+10AD0..10AD2)
\p{Joining_Group: Manichaean_Lamedh} (Short: \p{Jg=
ManichaeanLamedh}) (1: U+10AD3)
\p{Joining_Group: Manichaean_Mem} (Short: \p{Jg=ManichaeanMem})
(1: U+10AD6)
\p{Joining_Group: Manichaean_Nun} (Short: \p{Jg=ManichaeanNun})
(1: U+10AD7)
\p{Joining_Group: Manichaean_One} (Short: \p{Jg=ManichaeanOne})
(1: U+10AEB)
\p{Joining_Group: Manichaean_Pe} (Short: \p{Jg=ManichaeanPe}) (2:
U+10ADB..10ADC)
\p{Joining_Group: Manichaean_Qoph} (Short: \p{Jg=ManichaeanQoph})
(3: U+10ADE..10AE0)
\p{Joining_Group: Manichaean_Resh} (Short: \p{Jg=ManichaeanResh})
(1: U+10AE1)
\p{Joining_Group: Manichaean_Sadhe} (Short: \p{Jg=
ManichaeanSadhe}) (1: U+10ADD)
\p{Joining_Group: Manichaean_Samekh} (Short: \p{Jg=
ManichaeanSamekh}) (1: U+10AD8)
\p{Joining_Group: Manichaean_Taw} (Short: \p{Jg=ManichaeanTaw})
(1: U+10AE4)
\p{Joining_Group: Manichaean_Ten} (Short: \p{Jg=ManichaeanTen})
(1: U+10AED)
\p{Joining_Group: Manichaean_Teth} (Short: \p{Jg=ManichaeanTeth})
(1: U+10ACE)
\p{Joining_Group: Manichaean_Thamedh} (Short: \p{Jg=
ManichaeanThamedh}) (1: U+10AD5)
\p{Joining_Group: Manichaean_Twenty} (Short: \p{Jg=
ManichaeanTwenty}) (1: U+10AEE)
\p{Joining_Group: Manichaean_Waw} (Short: \p{Jg=ManichaeanWaw})
(1: U+10AC7)
\p{Joining_Group: Manichaean_Yodh} (Short: \p{Jg=ManichaeanYodh})
(1: U+10ACF)
\p{Joining_Group: Manichaean_Zayin} (Short: \p{Jg=
ManichaeanZayin}) (2: U+10AC9..10ACA)
\p{Joining_Group: Meem} (Short: \p{Jg=Meem}) (4: U+0645,
U+0765..0766, U+08A7)
\p{Joining_Group: Mim} (Short: \p{Jg=Mim}) (1: U+0721)
\p{Joining_Group: No_Joining_Group} (Short: \p{Jg=NoJoiningGroup})
(1_113_762 plus all above-Unicode code
points: U+0000..061F, U+0621, U+0640,
U+064B..066D, U+0670, U+0674 ...)
\p{Joining_Group: Noon} (Short: \p{Jg=Noon}) (9: U+0646,
U+06B9..06BC, U+0767..0769, U+0889)
\p{Joining_Group: Nun} (Short: \p{Jg=Nun}) (1: U+0722)
\p{Joining_Group: Nya} (Short: \p{Jg=Nya}) (1: U+06BD)
\p{Joining_Group: Pe} (Short: \p{Jg=Pe}) (1: U+0726)
\p{Joining_Group: Qaf} (Short: \p{Jg=Qaf}) (6: U+0642, U+066F,
U+06A7..06A8, U+08A5, U+08B5)
\p{Joining_Group: Qaph} (Short: \p{Jg=Qaph}) (1: U+0729)
\p{Joining_Group: Reh} (Short: \p{Jg=Reh}) (19: U+0631..0632,
U+0691..0699, U+06EF, U+075B,
U+076B..076C, U+0771 ...)
\p{Joining_Group: Reversed_Pe} (Short: \p{Jg=ReversedPe}) (1:
U+0727)
\p{Joining_Group: Rohingya_Yeh} (Short: \p{Jg=RohingyaYeh}) (1:
U+08AC)
\p{Joining_Group: Sad} (Short: \p{Jg=Sad}) (6: U+0635..0636,
U+069D..069E, U+06FB, U+08AF)
\p{Joining_Group: Sadhe} (Short: \p{Jg=Sadhe}) (1: U+0728)
\p{Joining_Group: Seen} (Short: \p{Jg=Seen}) (11: U+0633..0634,
U+069A..069C, U+06FA, U+075C, U+076D,
U+0770 ...)
\p{Joining_Group: Semkath} (Short: \p{Jg=Semkath}) (1: U+0723)
\p{Joining_Group: Shin} (Short: \p{Jg=Shin}) (1: U+072B)
\p{Joining_Group: Straight_Waw} (Short: \p{Jg=StraightWaw}) (1:
U+08B1)
\p{Joining_Group: Swash_Kaf} (Short: \p{Jg=SwashKaf}) (1: U+06AA)
\p{Joining_Group: Syriac_Waw} (Short: \p{Jg=SyriacWaw}) (1: U+0718)
\p{Joining_Group: Tah} (Short: \p{Jg=Tah}) (6: U+0637..0638,
U+069F, U+088B..088C, U+08A3)
\p{Joining_Group: Taw} (Short: \p{Jg=Taw}) (1: U+072C)
\p{Joining_Group: Teh_Marbuta} (Short: \p{Jg=TehMarbuta}) (3:
U+0629, U+06C0, U+06D5)
\p{Joining_Group: Teh_Marbuta_Goal} \p{Joining_Group=
Hamza_On_Heh_Goal} (1)
\p{Joining_Group: Teth} (Short: \p{Jg=Teth}) (2: U+071B..071C)
\p{Joining_Group: Thin_Yeh} (Short: \p{Jg=ThinYeh}) (1: U+0886)
\p{Joining_Group: Vertical_Tail} (Short: \p{Jg=VerticalTail}) (1:
U+088E)
\p{Joining_Group: Waw} (Short: \p{Jg=Waw}) (16: U+0624, U+0648,
U+0676..0677, U+06C4..06CB, U+06CF,
U+0778..0779 ...)
\p{Joining_Group: Yeh} (Short: \p{Jg=Yeh}) (11: U+0620, U+0626,
U+0649..064A, U+0678, U+06D0..06D1,
U+0777 ...)
\p{Joining_Group: Yeh_Barree} (Short: \p{Jg=YehBarree}) (2:
U+06D2..06D3)
\p{Joining_Group: Yeh_With_Tail} (Short: \p{Jg=YehWithTail}) (1:
U+06CD)
\p{Joining_Group: Yudh} (Short: \p{Jg=Yudh}) (1: U+071D)
\p{Joining_Group: Yudh_He} (Short: \p{Jg=YudhHe}) (1: U+071E)
\p{Joining_Group: Zain} (Short: \p{Jg=Zain}) (1: U+0719)
\p{Joining_Group: Zhain} (Short: \p{Jg=Zhain}) (1: U+074D)
\p{Joining_Type: C} \p{Joining_Type=Join_Causing} (7)
\p{Joining_Type: D} \p{Joining_Type=Dual_Joining} (610)
\p{Joining_Type: Dual_Joining} (Short: \p{Jt=D}) (610: U+0620,
U+0626, U+0628, U+062A..062E,
U+0633..063F, U+0641..0647 ...)
\p{Joining_Type: Join_Causing} (Short: \p{Jt=C}) (7: U+0640,
U+07FA, U+0883..0885, U+180A, U+200D)
\p{Joining_Type: L} \p{Joining_Type=Left_Joining} (5)
\p{Joining_Type: Left_Joining} (Short: \p{Jt=L}) (5: U+A872,
U+10ACD, U+10AD7, U+10D00, U+10FCB)
\p{Joining_Type: Non_Joining} (Short: \p{Jt=U}) (1_111_230 plus
all above-Unicode code points: [\x00-
\xac\xae-\xff], U+0100..02FF,
U+0370..0482, U+048A..0590, U+05BE,
U+05C0 ...)
\p{Joining_Type: R} \p{Joining_Type=Right_Joining} (152)
\p{Joining_Type: Right_Joining} (Short: \p{Jt=R}) (152:
U+0622..0625, U+0627, U+0629,
U+062F..0632, U+0648, U+0671..0673 ...)
\p{Joining_Type: T} \p{Joining_Type=Transparent} (2108)
\p{Joining_Type: Transparent} (Short: \p{Jt=T}) (2108: [\xad],
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2 ...)
\p{Joining_Type: U} \p{Joining_Type=Non_Joining} (1_111_230
plus all above-Unicode code points)
\p{Jt: *} \p{Joining_Type: *}
\p{Kaithi} \p{Script_Extensions=Kaithi} (Short:
\p{Kthi}; NOT \p{Block=Kaithi}) (88)
\p{Kali} \p{Kayah_Li} (= \p{Script_Extensions=
Kayah_Li}) (48)
\p{Kana} \p{Katakana} (= \p{Script_Extensions=
Katakana}) (NOT \p{Block=Katakana}) (372)
X \p{Kana_Ext_A} \p{Kana_Extended_A} (= \p{Block=
Kana_Extended_A}) (48)
X \p{Kana_Ext_B} \p{Kana_Extended_B} (= \p{Block=
Kana_Extended_B}) (16)
X \p{Kana_Extended_A} \p{Block=Kana_Extended_A} (Short:
\p{InKanaExtA}) (48)
X \p{Kana_Extended_B} \p{Block=Kana_Extended_B} (Short:
\p{InKanaExtB}) (16)
X \p{Kana_Sup} \p{Kana_Supplement} (= \p{Block=
Kana_Supplement}) (256)
X \p{Kana_Supplement} \p{Block=Kana_Supplement} (Short:
\p{InKanaSup}) (256)
X \p{Kanbun} \p{Block=Kanbun} (16)
X \p{Kangxi} \p{Kangxi_Radicals} (= \p{Block=
Kangxi_Radicals}) (224)
X \p{Kangxi_Radicals} \p{Block=Kangxi_Radicals} (Short:
\p{InKangxi}) (224)
\p{Kannada} \p{Script_Extensions=Kannada} (Short:
\p{Knda}; NOT \p{Block=Kannada}) (105)
\p{Katakana} \p{Script_Extensions=Katakana} (Short:
\p{Kana}; NOT \p{Block=Katakana}) (372)
X \p{Katakana_Ext} \p{Katakana_Phonetic_Extensions} (=
\p{Block=Katakana_Phonetic_Extensions})
(16)
X \p{Katakana_Phonetic_Extensions} \p{Block=
Katakana_Phonetic_Extensions} (Short:
\p{InKatakanaExt}) (16)
\p{Kayah_Li} \p{Script_Extensions=Kayah_Li} (Short:
\p{Kali}) (48)
\p{Khar} \p{Kharoshthi} (= \p{Script_Extensions=
Kharoshthi}) (NOT \p{Block=Kharoshthi})
(68)
\p{Kharoshthi} \p{Script_Extensions=Kharoshthi} (Short:
\p{Khar}; NOT \p{Block=Kharoshthi}) (68)
\p{Khitan_Small_Script} \p{Script_Extensions=Khitan_Small_Script}
(Short: \p{Kits}; NOT \p{Block=
Khitan_Small_Script}) (471)
\p{Khmer} \p{Script_Extensions=Khmer} (Short:
\p{Khmr}; NOT \p{Block=Khmer}) (146)
X \p{Khmer_Symbols} \p{Block=Khmer_Symbols} (32)
\p{Khmr} \p{Khmer} (= \p{Script_Extensions=Khmer})
(NOT \p{Block=Khmer}) (146)
\p{Khoj} \p{Khojki} (= \p{Script_Extensions=
Khojki}) (NOT \p{Block=Khojki}) (82)
\p{Khojki} \p{Script_Extensions=Khojki} (Short:
\p{Khoj}; NOT \p{Block=Khojki}) (82)
\p{Khudawadi} \p{Script_Extensions=Khudawadi} (Short:
\p{Sind}; NOT \p{Block=Khudawadi}) (81)
\p{Kits} \p{Khitan_Small_Script} (=
\p{Script_Extensions=
Khitan_Small_Script}) (NOT \p{Block=
Khitan_Small_Script}) (471)
\p{Knda} \p{Kannada} (= \p{Script_Extensions=
Kannada}) (NOT \p{Block=Kannada}) (105)
\p{Kthi} \p{Kaithi} (= \p{Script_Extensions=
Kaithi}) (NOT \p{Block=Kaithi}) (88)
\p{L} \pL \p{Letter} (= \p{General_Category=Letter})
(131_756)
X \p{L&} \p{Cased_Letter} (= \p{General_Category=
Cased_Letter}) (4089)
X \p{L_} \p{Cased_Letter} (= \p{General_Category=
Cased_Letter}) Note the trailing '_'
matters in spite of loose matching
rules. (4089)
\p{Lana} \p{Tai_Tham} (= \p{Script_Extensions=
Tai_Tham}) (NOT \p{Block=Tai_Tham}) (127)
\p{Lao} \p{Script_Extensions=Lao} (NOT \p{Block=
Lao}) (82)
\p{Laoo} \p{Lao} (= \p{Script_Extensions=Lao}) (NOT
\p{Block=Lao}) (82)
\p{Latin} \p{Script_Extensions=Latin} (Short:
\p{Latn}) (1504)
X \p{Latin_1} \p{Latin_1_Supplement} (= \p{Block=
Latin_1_Supplement}) (128)
X \p{Latin_1_Sup} \p{Latin_1_Supplement} (= \p{Block=
Latin_1_Supplement}) (128)
X \p{Latin_1_Supplement} \p{Block=Latin_1_Supplement} (Short:
\p{InLatin1}) (128)
X \p{Latin_Ext_A} \p{Latin_Extended_A} (= \p{Block=
Latin_Extended_A}) (128)
X \p{Latin_Ext_Additional} \p{Latin_Extended_Additional} (=
\p{Block=Latin_Extended_Additional})
(256)
X \p{Latin_Ext_B} \p{Latin_Extended_B} (= \p{Block=
Latin_Extended_B}) (208)
X \p{Latin_Ext_C} \p{Latin_Extended_C} (= \p{Block=
Latin_Extended_C}) (32)
X \p{Latin_Ext_D} \p{Latin_Extended_D} (= \p{Block=
Latin_Extended_D}) (224)
X \p{Latin_Ext_E} \p{Latin_Extended_E} (= \p{Block=
Latin_Extended_E}) (64)
X \p{Latin_Ext_F} \p{Latin_Extended_F} (= \p{Block=
Latin_Extended_F}) (64)
X \p{Latin_Ext_G} \p{Latin_Extended_G} (= \p{Block=
Latin_Extended_G}) (256)
X \p{Latin_Extended_A} \p{Block=Latin_Extended_A} (Short:
\p{InLatinExtA}) (128)
X \p{Latin_Extended_Additional} \p{Block=Latin_Extended_Additional}
(Short: \p{InLatinExtAdditional}) (256)
X \p{Latin_Extended_B} \p{Block=Latin_Extended_B} (Short:
\p{InLatinExtB}) (208)
X \p{Latin_Extended_C} \p{Block=Latin_Extended_C} (Short:
\p{InLatinExtC}) (32)
X \p{Latin_Extended_D} \p{Block=Latin_Extended_D} (Short:
\p{InLatinExtD}) (224)
X \p{Latin_Extended_E} \p{Block=Latin_Extended_E} (Short:
\p{InLatinExtE}) (64)
X \p{Latin_Extended_F} \p{Block=Latin_Extended_F} (Short:
\p{InLatinExtF}) (64)
X \p{Latin_Extended_G} \p{Block=Latin_Extended_G} (Short:
\p{InLatinExtG}) (256)
\p{Latn} \p{Latin} (= \p{Script_Extensions=Latin})
(1504)
\p{Lb: *} \p{Line_Break: *}
\p{LC} \p{Cased_Letter} (= \p{General_Category=
Cased_Letter}) (4089)
\p{Lepc} \p{Lepcha} (= \p{Script_Extensions=
Lepcha}) (NOT \p{Block=Lepcha}) (74)
\p{Lepcha} \p{Script_Extensions=Lepcha} (Short:
\p{Lepc}; NOT \p{Block=Lepcha}) (74)
\p{Letter} \p{General_Category=Letter} (Short: \p{L})
(131_756)
\p{Letter_Number} \p{General_Category=Letter_Number} (Short:
\p{Nl}) (236)
X \p{Letterlike_Symbols} \p{Block=Letterlike_Symbols} (80)
\p{Limb} \p{Limbu} (= \p{Script_Extensions=Limbu})
(NOT \p{Block=Limbu}) (69)
\p{Limbu} \p{Script_Extensions=Limbu} (Short:
\p{Limb}; NOT \p{Block=Limbu}) (69)
\p{Lina} \p{Linear_A} (= \p{Script_Extensions=
Linear_A}) (NOT \p{Block=Linear_A}) (386)
\p{Linb} \p{Linear_B} (= \p{Script_Extensions=
Linear_B}) (268)
\p{Line_Break: AI} \p{Line_Break=Ambiguous} (707)
\p{Line_Break: AL} \p{Line_Break=Alphabetic} (22_043)
\p{Line_Break: Alphabetic} (Short: \p{Lb=AL}) (22_043: [#&*<=>\@A-
Z\^_`a-z~\xa6\xa9\xac\xae-\xaf\xb5\xc0-
\xd6\xd8-\xf6\xf8-\xff], U+0100..02C6,
U+02CE..02CF, U+02D1..02D7, U+02DC,
U+02DE ...)
\p{Line_Break: Ambiguous} (Short: \p{Lb=AI}) (707: [\xa7-\xa8\xaa
\xb2-\xb3\xb6-\xba\xbc-\xbe\xd7\xf7],
U+02C7, U+02C9..02CB, U+02CD, U+02D0,
U+02D8..02DB ...)
\p{Line_Break: B2} \p{Line_Break=Break_Both} (3)
\p{Line_Break: BA} \p{Line_Break=Break_After} (247)
\p{Line_Break: BB} \p{Line_Break=Break_Before} (45)
\p{Line_Break: BK} \p{Line_Break=Mandatory_Break} (4)
\p{Line_Break: Break_After} (Short: \p{Lb=BA}) (247: [\t\|\xad],
U+058A, U+05BE, U+0964..0965,
U+0E5A..0E5B, U+0F0B ...)
\p{Line_Break: Break_Before} (Short: \p{Lb=BB}) (45: [\xb4],
U+02C8, U+02CC, U+02DF, U+0C77, U+0C84
...)
\p{Line_Break: Break_Both} (Short: \p{Lb=B2}) (3: U+2014,
U+2E3A..2E3B)
\p{Line_Break: Break_Symbols} (Short: \p{Lb=SY}) (1: [\/])
\p{Line_Break: Carriage_Return} (Short: \p{Lb=CR}) (1: [\r])
\p{Line_Break: CB} \p{Line_Break=Contingent_Break} (1)
\p{Line_Break: CJ} \p{Line_Break=
Conditional_Japanese_Starter} (58)
\p{Line_Break: CL} \p{Line_Break=Close_Punctuation} (95)
\p{Line_Break: Close_Parenthesis} (Short: \p{Lb=CP}) (2: [\)\]])
\p{Line_Break: Close_Punctuation} (Short: \p{Lb=CL}) (95: [\}],
U+0F3B, U+0F3D, U+169C, U+2046, U+207E
...)
\p{Line_Break: CM} \p{Line_Break=Combining_Mark} (2399)
\p{Line_Break: Combining_Mark} (Short: \p{Lb=CM}) (2399: [^\t\n
\cK\f\r\x20-\x7e\x85\xa0-\xff],
U+0300..034E, U+0350..035B,
U+0363..036F, U+0483..0489, U+0591..05BD
...)
\p{Line_Break: Complex_Context} (Short: \p{Lb=SA}) (757:
U+0E01..0E3A, U+0E40..0E4E,
U+0E81..0E82, U+0E84, U+0E86..0E8A,
U+0E8C..0EA3 ...)
\p{Line_Break: Conditional_Japanese_Starter} (Short: \p{Lb=CJ})
(58: U+3041, U+3043, U+3045, U+3047,
U+3049, U+3063 ...)
\p{Line_Break: Contingent_Break} (Short: \p{Lb=CB}) (1: U+FFFC)
\p{Line_Break: CP} \p{Line_Break=Close_Parenthesis} (2)
\p{Line_Break: CR} \p{Line_Break=Carriage_Return} (1)
\p{Line_Break: E_Base} (Short: \p{Lb=EB}) (132: U+261D, U+26F9,
U+270A..270D, U+1F385, U+1F3C2..1F3C4,
U+1F3C7 ...)
\p{Line_Break: E_Modifier} (Short: \p{Lb=EM}) (5: U+1F3FB..1F3FF)
\p{Line_Break: EB} \p{Line_Break=E_Base} (132)
\p{Line_Break: EM} \p{Line_Break=E_Modifier} (5)
\p{Line_Break: EX} \p{Line_Break=Exclamation} (40)
\p{Line_Break: Exclamation} (Short: \p{Lb=EX}) (40: [!?], U+05C6,
U+061B, U+061D..061F, U+06D4, U+07F9 ...)
\p{Line_Break: GL} \p{Line_Break=Glue} (26)
\p{Line_Break: Glue} (Short: \p{Lb=GL}) (26: [\xa0], U+034F,
U+035C..0362, U+0F08, U+0F0C, U+0F12 ...)
\p{Line_Break: H2} (Short: \p{Lb=H2}) (399: U+AC00, U+AC1C,
U+AC38, U+AC54, U+AC70, U+AC8C ...)
\p{Line_Break: H3} (Short: \p{Lb=H3}) (10_773: U+AC01..AC1B,
U+AC1D..AC37, U+AC39..AC53,
U+AC55..AC6F, U+AC71..AC8B, U+AC8D..ACA7
...)
\p{Line_Break: Hebrew_Letter} (Short: \p{Lb=HL}) (75:
U+05D0..05EA, U+05EF..05F2, U+FB1D,
U+FB1F..FB28, U+FB2A..FB36, U+FB38..FB3C
...)
\p{Line_Break: HL} \p{Line_Break=Hebrew_Letter} (75)
\p{Line_Break: HY} \p{Line_Break=Hyphen} (1)
\p{Line_Break: Hyphen} (Short: \p{Lb=HY}) (1: [\-])
\p{Line_Break: ID} \p{Line_Break=Ideographic} (172_456)
\p{Line_Break: Ideographic} (Short: \p{Lb=ID}) (172_456:
U+231A..231B, U+23F0..23F3,
U+2600..2603, U+2614..2615, U+2618,
U+261A..261C ...)
\p{Line_Break: IN} \p{Line_Break=Inseparable} (6)
\p{Line_Break: Infix_Numeric} (Short: \p{Lb=IS}) (13: [,.:;],
U+037E, U+0589, U+060C..060D, U+07F8,
U+2044 ...)
\p{Line_Break: Inseparable} (Short: \p{Lb=IN}) (6: U+2024..2026,
U+22EF, U+FE19, U+10AF6)
\p{Line_Break: Inseperable} \p{Line_Break=Inseparable} (6)
\p{Line_Break: IS} \p{Line_Break=Infix_Numeric} (13)
\p{Line_Break: JL} (Short: \p{Lb=JL}) (125: U+1100..115F,
U+A960..A97C)
\p{Line_Break: JT} (Short: \p{Lb=JT}) (137: U+11A8..11FF,
U+D7CB..D7FB)
\p{Line_Break: JV} (Short: \p{Lb=JV}) (95: U+1160..11A7,
U+D7B0..D7C6)
\p{Line_Break: LF} \p{Line_Break=Line_Feed} (1)
\p{Line_Break: Line_Feed} (Short: \p{Lb=LF}) (1: [\n])
\p{Line_Break: Mandatory_Break} (Short: \p{Lb=BK}) (4: [\cK\f],
U+2028..2029)
\p{Line_Break: Next_Line} (Short: \p{Lb=NL}) (1: [\x85])
\p{Line_Break: NL} \p{Line_Break=Next_Line} (1)
\p{Line_Break: Nonstarter} (Short: \p{Lb=NS}) (33: U+17D6,
U+203C..203D, U+2047..2049, U+3005,
U+301C, U+303B..303C ...)
\p{Line_Break: NS} \p{Line_Break=Nonstarter} (33)
\p{Line_Break: NU} \p{Line_Break=Numeric} (652)
\p{Line_Break: Numeric} (Short: \p{Lb=NU}) (652: [0-9],
U+0660..0669, U+066B..066C,
U+06F0..06F9, U+07C0..07C9, U+0966..096F
...)
\p{Line_Break: OP} \p{Line_Break=Open_Punctuation} (92)
\p{Line_Break: Open_Punctuation} (Short: \p{Lb=OP}) (92: [\(\[\{
\xa1\xbf], U+0F3A, U+0F3C, U+169B,
U+201A, U+201E ...)
\p{Line_Break: PO} \p{Line_Break=Postfix_Numeric} (37)
\p{Line_Break: Postfix_Numeric} (Short: \p{Lb=PO}) (37: [\%\xa2
\xb0], U+0609..060B, U+066A,
U+09F2..09F3, U+09F9, U+0D79 ...)
\p{Line_Break: PR} \p{Line_Break=Prefix_Numeric} (67)
\p{Line_Break: Prefix_Numeric} (Short: \p{Lb=PR}) (67: [\$+\\\xa3-
\xa5\xb1], U+058F, U+07FE..07FF, U+09FB,
U+0AF1, U+0BF9 ...)
\p{Line_Break: QU} \p{Line_Break=Quotation} (39)
\p{Line_Break: Quotation} (Short: \p{Lb=QU}) (39: [\"\'\xab\xbb],
U+2018..2019, U+201B..201D, U+201F,
U+2039..203A, U+275B..2760 ...)
\p{Line_Break: Regional_Indicator} (Short: \p{Lb=RI}) (26:
U+1F1E6..1F1FF)
\p{Line_Break: RI} \p{Line_Break=Regional_Indicator} (26)
\p{Line_Break: SA} \p{Line_Break=Complex_Context} (757)
D \p{Line_Break: SG} \p{Line_Break=Surrogate} (2048)
\p{Line_Break: SP} \p{Line_Break=Space} (1)
\p{Line_Break: Space} (Short: \p{Lb=SP}) (1: [\x20])
D \p{Line_Break: Surrogate} Surrogates should never appear in well-
formed text, and therefore shouldn't be
the basis for line breaking (Short:
\p{Lb=SG}) (2048: U+D800..DFFF)
\p{Line_Break: SY} \p{Line_Break=Break_Symbols} (1)
\p{Line_Break: Unknown} (Short: \p{Lb=XX}) (900_465 plus all
above-Unicode code points: U+0378..0379,
U+0380..0383, U+038B, U+038D, U+03A2,
U+0530 ...)
\p{Line_Break: WJ} \p{Line_Break=Word_Joiner} (2)
\p{Line_Break: Word_Joiner} (Short: \p{Lb=WJ}) (2: U+2060, U+FEFF)
\p{Line_Break: XX} \p{Line_Break=Unknown} (900_465 plus all
above-Unicode code points)
\p{Line_Break: ZW} \p{Line_Break=ZWSpace} (1)
\p{Line_Break: ZWJ} (Short: \p{Lb=ZWJ}) (1: U+200D)
\p{Line_Break: ZWSpace} (Short: \p{Lb=ZW}) (1: U+200B)
\p{Line_Separator} \p{General_Category=Line_Separator}
(Short: \p{Zl}) (1)
\p{Linear_A} \p{Script_Extensions=Linear_A} (Short:
\p{Lina}; NOT \p{Block=Linear_A}) (386)
\p{Linear_B} \p{Script_Extensions=Linear_B} (Short:
\p{Linb}) (268)
X \p{Linear_B_Ideograms} \p{Block=Linear_B_Ideograms} (128)
X \p{Linear_B_Syllabary} \p{Block=Linear_B_Syllabary} (128)
\p{Lisu} \p{Script_Extensions=Lisu} (NOT \p{Block=
Lisu}) (49)
X \p{Lisu_Sup} \p{Lisu_Supplement} (= \p{Block=
Lisu_Supplement}) (16)
X \p{Lisu_Supplement} \p{Block=Lisu_Supplement} (Short:
\p{InLisuSup}) (16)
\p{Ll} \p{Lowercase_Letter} (=
\p{General_Category=Lowercase_Letter})
(/i= General_Category=Cased_Letter)
(2227)
\p{Lm} \p{Modifier_Letter} (=
\p{General_Category=Modifier_Letter})
(334)
\p{Lo} \p{Other_Letter} (= \p{General_Category=
Other_Letter}) (127_333)
\p{LOE} \p{Logical_Order_Exception} (=
\p{Logical_Order_Exception=Y}) (19)
\p{LOE: *} \p{Logical_Order_Exception: *}
\p{Logical_Order_Exception} \p{Logical_Order_Exception=Y} (Short:
\p{LOE}) (19)
\p{Logical_Order_Exception: N*} (Short: \p{LOE=N}, \P{LOE})
(1_114_093 plus all above-Unicode code
points: U+0000..0E3F, U+0E45..0EBF,
U+0EC5..19B4, U+19B8..19B9,
U+19BB..AAB4, U+AAB7..AAB8 ...)
\p{Logical_Order_Exception: Y*} (Short: \p{LOE=Y}, \p{LOE}) (19:
U+0E40..0E44, U+0EC0..0EC4,
U+19B5..19B7, U+19BA, U+AAB5..AAB6,
U+AAB9 ...)
X \p{Low_Surrogates} \p{Block=Low_Surrogates} (1024)
\p{Lower} \p{XPosixLower} (= \p{Lowercase=Y}) (/i=
Cased=Yes) (2471)
\p{Lower: *} \p{Lowercase: *}
\p{Lowercase} \p{XPosixLower} (= \p{Lowercase=Y}) (/i=
Cased=Yes) (2471)
\p{Lowercase: N*} (Short: \p{Lower=N}, \P{Lower}; /i= Cased=
No) (1_111_641 plus all above-Unicode
code points: [\x00-\x20!\"#\$\%&\'
\(\)*+,\-.\/0-9:;<=>?\@A-Z\[\\\]\^_`\{
\|\}~\x7f-\xa9\xab-\xb4\xb6-\xb9\xbb-
\xde\xf7], U+0100, U+0102, U+0104,
U+0106, U+0108 ...)
\p{Lowercase: Y*} (Short: \p{Lower=Y}, \p{Lower}; /i= Cased=
Yes) (2471: [a-z\xaa\xb5\xba\xdf-\xf6
\xf8-\xff], U+0101, U+0103, U+0105,
U+0107, U+0109 ...)
\p{Lowercase_Letter} \p{General_Category=Lowercase_Letter}
(Short: \p{Ll}; /i= General_Category=
Cased_Letter) (2227)
\p{Lt} \p{Titlecase_Letter} (=
\p{General_Category=Titlecase_Letter})
(/i= General_Category=Cased_Letter) (31)
\p{Lu} \p{Uppercase_Letter} (=
\p{General_Category=Uppercase_Letter})
(/i= General_Category=Cased_Letter)
(1831)
\p{Lyci} \p{Lycian} (= \p{Script_Extensions=
Lycian}) (NOT \p{Block=Lycian}) (29)
\p{Lycian} \p{Script_Extensions=Lycian} (Short:
\p{Lyci}; NOT \p{Block=Lycian}) (29)
\p{Lydi} \p{Lydian} (= \p{Script_Extensions=
Lydian}) (NOT \p{Block=Lydian}) (27)
\p{Lydian} \p{Script_Extensions=Lydian} (Short:
\p{Lydi}; NOT \p{Block=Lydian}) (27)
\p{M} \pM \p{Mark} (= \p{General_Category=Mark})
(2408)
\p{Mahajani} \p{Script_Extensions=Mahajani} (Short:
\p{Mahj}; NOT \p{Block=Mahajani}) (61)
\p{Mahj} \p{Mahajani} (= \p{Script_Extensions=
Mahajani}) (NOT \p{Block=Mahajani}) (61)
X \p{Mahjong} \p{Mahjong_Tiles} (= \p{Block=
Mahjong_Tiles}) (48)
X \p{Mahjong_Tiles} \p{Block=Mahjong_Tiles} (Short:
\p{InMahjong}) (48)
\p{Maka} \p{Makasar} (= \p{Script_Extensions=
Makasar}) (NOT \p{Block=Makasar}) (25)
\p{Makasar} \p{Script_Extensions=Makasar} (Short:
\p{Maka}; NOT \p{Block=Makasar}) (25)
\p{Malayalam} \p{Script_Extensions=Malayalam} (Short:
\p{Mlym}; NOT \p{Block=Malayalam}) (126)
\p{Mand} \p{Mandaic} (= \p{Script_Extensions=
Mandaic}) (NOT \p{Block=Mandaic}) (30)
\p{Mandaic} \p{Script_Extensions=Mandaic} (Short:
\p{Mand}; NOT \p{Block=Mandaic}) (30)
\p{Mani} \p{Manichaean} (= \p{Script_Extensions=
Manichaean}) (NOT \p{Block=Manichaean})
(52)
\p{Manichaean} \p{Script_Extensions=Manichaean} (Short:
\p{Mani}; NOT \p{Block=Manichaean}) (52)
\p{Marc} \p{Marchen} (= \p{Script_Extensions=
Marchen}) (NOT \p{Block=Marchen}) (68)
\p{Marchen} \p{Script_Extensions=Marchen} (Short:
\p{Marc}; NOT \p{Block=Marchen}) (68)
\p{Mark} \p{General_Category=Mark} (Short: \p{M})
(2408)
\p{Masaram_Gondi} \p{Script_Extensions=Masaram_Gondi}
(Short: \p{Gonm}; NOT \p{Block=
Masaram_Gondi}) (77)
\p{Math} \p{Math=Y} (2310)
\p{Math: N*} (Single: \P{Math}) (1_111_802 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*,\-.\/0-9:;?\@A-Z
\[\\\]_`a-z\{\}\x7f-\xab\xad-\xb0\xb2-
\xd6\xd8-\xf6\xf8-\xff], U+0100..03CF,
U+03D3..03D4, U+03D6..03EF,
U+03F2..03F3, U+03F7..0605 ...)
\p{Math: Y*} (Single: \p{Math}) (2310: [+<=>\^\|~\xac
\xb1\xd7\xf7], U+03D0..03D2, U+03D5,
U+03F0..03F1, U+03F4..03F6, U+0606..0608
...)
X \p{Math_Alphanum} \p{Mathematical_Alphanumeric_Symbols} (=
\p{Block=
Mathematical_Alphanumeric_Symbols})
(1024)
X \p{Math_Operators} \p{Mathematical_Operators} (= \p{Block=
Mathematical_Operators}) (256)
\p{Math_Symbol} \p{General_Category=Math_Symbol} (Short:
\p{Sm}) (948)
X \p{Mathematical_Alphanumeric_Symbols} \p{Block=
Mathematical_Alphanumeric_Symbols}
(Short: \p{InMathAlphanum}) (1024)
X \p{Mathematical_Operators} \p{Block=Mathematical_Operators}
(Short: \p{InMathOperators}) (256)
X \p{Mayan_Numerals} \p{Block=Mayan_Numerals} (32)
\p{Mc} \p{Spacing_Mark} (= \p{General_Category=
Spacing_Mark}) (445)
\p{Me} \p{Enclosing_Mark} (= \p{General_Category=
Enclosing_Mark}) (13)
\p{Medefaidrin} \p{Script_Extensions=Medefaidrin} (Short:
\p{Medf}; NOT \p{Block=Medefaidrin}) (91)
\p{Medf} \p{Medefaidrin} (= \p{Script_Extensions=
Medefaidrin}) (NOT \p{Block=
Medefaidrin}) (91)
\p{Meetei_Mayek} \p{Script_Extensions=Meetei_Mayek} (Short:
\p{Mtei}; NOT \p{Block=Meetei_Mayek})
(79)
X \p{Meetei_Mayek_Ext} \p{Meetei_Mayek_Extensions} (= \p{Block=
Meetei_Mayek_Extensions}) (32)
X \p{Meetei_Mayek_Extensions} \p{Block=Meetei_Mayek_Extensions}
(Short: \p{InMeeteiMayekExt}) (32)
\p{Mend} \p{Mende_Kikakui} (= \p{Script_Extensions=
Mende_Kikakui}) (NOT \p{Block=
Mende_Kikakui}) (213)
\p{Mende_Kikakui} \p{Script_Extensions=Mende_Kikakui}
(Short: \p{Mend}; NOT \p{Block=
Mende_Kikakui}) (213)
\p{Merc} \p{Meroitic_Cursive} (=
\p{Script_Extensions=Meroitic_Cursive})
(NOT \p{Block=Meroitic_Cursive}) (90)
\p{Mero} \p{Meroitic_Hieroglyphs} (=
\p{Script_Extensions=
Meroitic_Hieroglyphs}) (32)
\p{Meroitic_Cursive} \p{Script_Extensions=Meroitic_Cursive}
(Short: \p{Merc}; NOT \p{Block=
Meroitic_Cursive}) (90)
\p{Meroitic_Hieroglyphs} \p{Script_Extensions=
Meroitic_Hieroglyphs} (Short: \p{Mero})
(32)
\p{Miao} \p{Script_Extensions=Miao} (NOT \p{Block=
Miao}) (149)
X \p{Misc_Arrows} \p{Miscellaneous_Symbols_And_Arrows} (=
\p{Block=
Miscellaneous_Symbols_And_Arrows}) (256)
X \p{Misc_Math_Symbols_A} \p{Miscellaneous_Mathematical_Symbols_A}
(= \p{Block=
Miscellaneous_Mathematical_Symbols_A})
(48)
X \p{Misc_Math_Symbols_B} \p{Miscellaneous_Mathematical_Symbols_B}
(= \p{Block=
Miscellaneous_Mathematical_Symbols_B})
(128)
X \p{Misc_Pictographs} \p{Miscellaneous_Symbols_And_Pictographs}
(= \p{Block=
Miscellaneous_Symbols_And_Pictographs})
(768)
X \p{Misc_Symbols} \p{Miscellaneous_Symbols} (= \p{Block=
Miscellaneous_Symbols}) (256)
X \p{Misc_Technical} \p{Miscellaneous_Technical} (= \p{Block=
Miscellaneous_Technical}) (256)
X \p{Miscellaneous_Mathematical_Symbols_A} \p{Block=
Miscellaneous_Mathematical_Symbols_A}
(Short: \p{InMiscMathSymbolsA}) (48)
X \p{Miscellaneous_Mathematical_Symbols_B} \p{Block=
Miscellaneous_Mathematical_Symbols_B}
(Short: \p{InMiscMathSymbolsB}) (128)
X \p{Miscellaneous_Symbols} \p{Block=Miscellaneous_Symbols} (Short:
\p{InMiscSymbols}) (256)
X \p{Miscellaneous_Symbols_And_Arrows} \p{Block=
Miscellaneous_Symbols_And_Arrows}
(Short: \p{InMiscArrows}) (256)
X \p{Miscellaneous_Symbols_And_Pictographs} \p{Block=
Miscellaneous_Symbols_And_Pictographs}
(Short: \p{InMiscPictographs}) (768)
X \p{Miscellaneous_Technical} \p{Block=Miscellaneous_Technical}
(Short: \p{InMiscTechnical}) (256)
\p{Mlym} \p{Malayalam} (= \p{Script_Extensions=
Malayalam}) (NOT \p{Block=Malayalam})
(126)
\p{Mn} \p{Nonspacing_Mark} (=
\p{General_Category=Nonspacing_Mark})
(1950)
\p{Modi} \p{Script_Extensions=Modi} (NOT \p{Block=
Modi}) (89)
\p{Modifier_Letter} \p{General_Category=Modifier_Letter}
(Short: \p{Lm}) (334)
X \p{Modifier_Letters} \p{Spacing_Modifier_Letters} (= \p{Block=
Spacing_Modifier_Letters}) (80)
\p{Modifier_Symbol} \p{General_Category=Modifier_Symbol}
(Short: \p{Sk}) (125)
X \p{Modifier_Tone_Letters} \p{Block=Modifier_Tone_Letters} (32)
\p{Mong} \p{Mongolian} (= \p{Script_Extensions=
Mongolian}) (NOT \p{Block=Mongolian})
(172)
\p{Mongolian} \p{Script_Extensions=Mongolian} (Short:
\p{Mong}; NOT \p{Block=Mongolian}) (172)
X \p{Mongolian_Sup} \p{Mongolian_Supplement} (= \p{Block=
Mongolian_Supplement}) (32)
X \p{Mongolian_Supplement} \p{Block=Mongolian_Supplement} (Short:
\p{InMongolianSup}) (32)
\p{Mro} \p{Script_Extensions=Mro} (NOT \p{Block=
Mro}) (43)
\p{Mroo} \p{Mro} (= \p{Script_Extensions=Mro}) (NOT
\p{Block=Mro}) (43)
\p{Mtei} \p{Meetei_Mayek} (= \p{Script_Extensions=
Meetei_Mayek}) (NOT \p{Block=
Meetei_Mayek}) (79)
\p{Mult} \p{Multani} (= \p{Script_Extensions=
Multani}) (NOT \p{Block=Multani}) (48)
\p{Multani} \p{Script_Extensions=Multani} (Short:
\p{Mult}; NOT \p{Block=Multani}) (48)
X \p{Music} \p{Musical_Symbols} (= \p{Block=
Musical_Symbols}) (256)
X \p{Musical_Symbols} \p{Block=Musical_Symbols} (Short:
\p{InMusic}) (256)
\p{Myanmar} \p{Script_Extensions=Myanmar} (Short:
\p{Mymr}; NOT \p{Block=Myanmar}) (224)
X \p{Myanmar_Ext_A} \p{Myanmar_Extended_A} (= \p{Block=
Myanmar_Extended_A}) (32)
X \p{Myanmar_Ext_B} \p{Myanmar_Extended_B} (= \p{Block=
Myanmar_Extended_B}) (32)
X \p{Myanmar_Extended_A} \p{Block=Myanmar_Extended_A} (Short:
\p{InMyanmarExtA}) (32)
X \p{Myanmar_Extended_B} \p{Block=Myanmar_Extended_B} (Short:
\p{InMyanmarExtB}) (32)
\p{Mymr} \p{Myanmar} (= \p{Script_Extensions=
Myanmar}) (NOT \p{Block=Myanmar}) (224)
\p{N} \pN \p{Number} (= \p{General_Category=Number})
(1791)
\p{Na=*} \p{Name=*}
\p{Nabataean} \p{Script_Extensions=Nabataean} (Short:
\p{Nbat}; NOT \p{Block=Nabataean}) (40)
\p{Name=*} Combination of Name and Name_Alias
properties; has special loose matching
rules, for which see Unicode UAX #44
\p{Nand} \p{Nandinagari} (= \p{Script_Extensions=
Nandinagari}) (NOT \p{Block=
Nandinagari}) (86)
\p{Nandinagari} \p{Script_Extensions=Nandinagari} (Short:
\p{Nand}; NOT \p{Block=Nandinagari}) (86)
\p{Narb} \p{Old_North_Arabian} (=
\p{Script_Extensions=Old_North_Arabian})
(32)
X \p{NB} \p{No_Block} (= \p{Block=No_Block})
(825_600 plus all above-Unicode code
points)
\p{Nbat} \p{Nabataean} (= \p{Script_Extensions=
Nabataean}) (NOT \p{Block=Nabataean})
(40)
\p{NChar} \p{Noncharacter_Code_Point} (=
\p{Noncharacter_Code_Point=Y}) (66)
\p{NChar: *} \p{Noncharacter_Code_Point: *}
\p{Nd} \p{XPosixDigit} (= \p{General_Category=
Decimal_Number}) (660)
\p{New_Tai_Lue} \p{Script_Extensions=New_Tai_Lue} (Short:
\p{Talu}; NOT \p{Block=New_Tai_Lue}) (83)
\p{Newa} \p{Script_Extensions=Newa} (NOT \p{Block=
Newa}) (97)
\p{NFC_QC: *} \p{NFC_Quick_Check: *}
\p{NFC_Quick_Check: M} \p{NFC_Quick_Check=Maybe} (111)
\p{NFC_Quick_Check: Maybe} (Short: \p{NFCQC=M}) (111:
U+0300..0304, U+0306..030C, U+030F,
U+0311, U+0313..0314, U+031B ...)
\p{NFC_Quick_Check: N} \p{NFC_Quick_Check=No} (NOT
\P{NFC_Quick_Check} NOR \P{NFC_QC})
(1120)
\p{NFC_Quick_Check: No} (Short: \p{NFCQC=N}; NOT
\P{NFC_Quick_Check} NOR \P{NFC_QC})
(1120: U+0340..0341, U+0343..0344,
U+0374, U+037E, U+0387, U+0958..095F ...)
\p{NFC_Quick_Check: Y} \p{NFC_Quick_Check=Yes} (NOT
\p{NFC_Quick_Check} NOR \p{NFC_QC})
(1_112_881 plus all above-Unicode code
points)
\p{NFC_Quick_Check: Yes} (Short: \p{NFCQC=Y}; NOT
\p{NFC_Quick_Check} NOR \p{NFC_QC})
(1_112_881 plus all above-Unicode code
points: U+0000..02FF, U+0305,
U+030D..030E, U+0310, U+0312,
U+0315..031A ...)
\p{NFD_QC: *} \p{NFD_Quick_Check: *}
\p{NFD_Quick_Check: N} \p{NFD_Quick_Check=No} (NOT
\P{NFD_Quick_Check} NOR \P{NFD_QC})
(13_233)
\p{NFD_Quick_Check: No} (Short: \p{NFDQC=N}; NOT
\P{NFD_Quick_Check} NOR \P{NFD_QC})
(13_233: [\xc0-\xc5\xc7-\xcf\xd1-\xd6
\xd9-\xdd\xe0-\xe5\xe7-\xef\xf1-\xf6
\xf9-\xfd\xff], U+0100..010F,
U+0112..0125, U+0128..0130,
U+0134..0137, U+0139..013E ...)
\p{NFD_Quick_Check: Y} \p{NFD_Quick_Check=Yes} (NOT
\p{NFD_Quick_Check} NOR \p{NFD_QC})
(1_100_879 plus all above-Unicode code
points)
\p{NFD_Quick_Check: Yes} (Short: \p{NFDQC=Y}; NOT
\p{NFD_Quick_Check} NOR \p{NFD_QC})
(1_100_879 plus all above-Unicode code
points: [\x00-\xbf\xc6\xd0\xd7-\xd8\xde-
\xdf\xe6\xf0\xf7-\xf8\xfe],
U+0110..0111, U+0126..0127,
U+0131..0133, U+0138, U+013F..0142 ...)
\p{NFKC_QC: *} \p{NFKC_Quick_Check: *}
\p{NFKC_Quick_Check: M} \p{NFKC_Quick_Check=Maybe} (111)
\p{NFKC_Quick_Check: Maybe} (Short: \p{NFKCQC=M}) (111:
U+0300..0304, U+0306..030C, U+030F,
U+0311, U+0313..0314, U+031B ...)
\p{NFKC_Quick_Check: N} \p{NFKC_Quick_Check=No} (NOT
\P{NFKC_Quick_Check} NOR \P{NFKC_QC})
(4866)
\p{NFKC_Quick_Check: No} (Short: \p{NFKCQC=N}; NOT
\P{NFKC_Quick_Check} NOR \P{NFKC_QC})
(4866: [\xa0\xa8\xaa\xaf\xb2-\xb5\xb8-
\xba\xbc-\xbe], U+0132..0133,
U+013F..0140, U+0149, U+017F,
U+01C4..01CC ...)
\p{NFKC_Quick_Check: Y} \p{NFKC_Quick_Check=Yes} (NOT
\p{NFKC_Quick_Check} NOR \p{NFKC_QC})
(1_109_135 plus all above-Unicode code
points)
\p{NFKC_Quick_Check: Yes} (Short: \p{NFKCQC=Y}; NOT
\p{NFKC_Quick_Check} NOR \p{NFKC_QC})
(1_109_135 plus all above-Unicode code
points: [\x00-\x9f\xa1-\xa7\xa9\xab-
\xae\xb0-\xb1\xb6-\xb7\xbb\xbf-\xff],
U+0100..0131, U+0134..013E,
U+0141..0148, U+014A..017E, U+0180..01C3
...)
\p{NFKD_QC: *} \p{NFKD_Quick_Check: *}
\p{NFKD_Quick_Check: N} \p{NFKD_Quick_Check=No} (NOT
\P{NFKD_Quick_Check} NOR \P{NFKD_QC})
(16_967)
\p{NFKD_Quick_Check: No} (Short: \p{NFKDQC=N}; NOT
\P{NFKD_Quick_Check} NOR \P{NFKD_QC})
(16_967: [\xa0\xa8\xaa\xaf\xb2-\xb5\xb8-
\xba\xbc-\xbe\xc0-\xc5\xc7-\xcf\xd1-
\xd6\xd9-\xdd\xe0-\xe5\xe7-\xef\xf1-
\xf6\xf9-\xfd\xff], U+0100..010F,
U+0112..0125, U+0128..0130,
U+0132..0137, U+0139..0140 ...)
\p{NFKD_Quick_Check: Y} \p{NFKD_Quick_Check=Yes} (NOT
\p{NFKD_Quick_Check} NOR \p{NFKD_QC})
(1_097_145 plus all above-Unicode code
points)
\p{NFKD_Quick_Check: Yes} (Short: \p{NFKDQC=Y}; NOT
\p{NFKD_Quick_Check} NOR \p{NFKD_QC})
(1_097_145 plus all above-Unicode code
points: [\x00-\x9f\xa1-\xa7\xa9\xab-
\xae\xb0-\xb1\xb6-\xb7\xbb\xbf\xc6\xd0
\xd7-\xd8\xde-\xdf\xe6\xf0\xf7-\xf8
\xfe], U+0110..0111, U+0126..0127,
U+0131, U+0138, U+0141..0142 ...)
\p{Nko} \p{Script_Extensions=Nko} (NOT \p{Block=
NKo}) (67)
\p{Nkoo} \p{Nko} (= \p{Script_Extensions=Nko}) (NOT
\p{Block=NKo}) (67)
\p{Nl} \p{Letter_Number} (= \p{General_Category=
Letter_Number}) (236)
\p{No} \p{Other_Number} (= \p{General_Category=
Other_Number}) (895)
X \p{No_Block} \p{Block=No_Block} (Short: \p{InNB})
(825_600 plus all above-Unicode code
points)
\p{Noncharacter_Code_Point} \p{Noncharacter_Code_Point=Y} (Short:
\p{NChar}) (66)
\p{Noncharacter_Code_Point: N*} (Short: \p{NChar=N}, \P{NChar})
(1_114_046 plus all above-Unicode code
points: U+0000..FDCF, U+FDF0..FFFD,
U+10000..1FFFD, U+20000..2FFFD,
U+30000..3FFFD, U+40000..4FFFD ...)
\p{Noncharacter_Code_Point: Y*} (Short: \p{NChar=Y}, \p{NChar})
(66: U+FDD0..FDEF, U+FFFE..FFFF,
U+1FFFE..1FFFF, U+2FFFE..2FFFF,
U+3FFFE..3FFFF, U+4FFFE..4FFFF ...)
\p{Nonspacing_Mark} \p{General_Category=Nonspacing_Mark}
(Short: \p{Mn}) (1950)
\p{Nshu} \p{Nushu} (= \p{Script_Extensions=Nushu})
(NOT \p{Block=Nushu}) (397)
\p{Nt: *} \p{Numeric_Type: *}
\p{Number} \p{General_Category=Number} (Short: \p{N})
(1791)
X \p{Number_Forms} \p{Block=Number_Forms} (64)
\p{Numeric_Type: De} \p{Numeric_Type=Decimal} (660)
\p{Numeric_Type: Decimal} (Short: \p{Nt=De}) (660: [0-9],
U+0660..0669, U+06F0..06F9,
U+07C0..07C9, U+0966..096F, U+09E6..09EF
...)
\p{Numeric_Type: Di} \p{Numeric_Type=Digit} (128)
\p{Numeric_Type: Digit} (Short: \p{Nt=Di}) (128: [\xb2-\xb3\xb9],
U+1369..1371, U+19DA, U+2070,
U+2074..2079, U+2080..2089 ...)
\p{Numeric_Type: None} (Short: \p{Nt=None}) (1_112_240 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@A-Z\[\\\]
\^_`a-z\{\|\}~\x7f-\xb1\xb4-\xb8\xba-
\xbb\xbf-\xff], U+0100..065F,
U+066A..06EF, U+06FA..07BF,
U+07CA..0965, U+0970..09E5 ...)
\p{Numeric_Type: Nu} \p{Numeric_Type=Numeric} (1084)
\p{Numeric_Type: Numeric} (Short: \p{Nt=Nu}) (1084: [\xbc-\xbe],
U+09F4..09F9, U+0B72..0B77,
U+0BF0..0BF2, U+0C78..0C7E, U+0D58..0D5E
...)
T \p{Numeric_Value: -1/2} (Short: \p{Nv=-1/2}) (1: U+0F33)
T \p{Numeric_Value: 0} (Short: \p{Nv=0}) (84: [0], U+0660,
U+06F0, U+07C0, U+0966, U+09E6 ...)
T \p{Numeric_Value: 1/320} (Short: \p{Nv=1/320}) (2: U+11FC0,
U+11FD4)
T \p{Numeric_Value: 1/160} (Short: \p{Nv=1/160}) (2: U+0D58, U+11FC1)
T \p{Numeric_Value: 1/80} (Short: \p{Nv=1/80}) (1: U+11FC2)
T \p{Numeric_Value: 1/64} (Short: \p{Nv=1/64}) (1: U+11FC3)
T \p{Numeric_Value: 1/40} (Short: \p{Nv=1/40}) (2: U+0D59, U+11FC4)
T \p{Numeric_Value: 1/32} (Short: \p{Nv=1/32}) (1: U+11FC5)
T \p{Numeric_Value: 3/80} (Short: \p{Nv=3/80}) (2: U+0D5A, U+11FC6)
T \p{Numeric_Value: 3/64} (Short: \p{Nv=3/64}) (1: U+11FC7)
T \p{Numeric_Value: 1/20} (Short: \p{Nv=1/20}) (2: U+0D5B, U+11FC8)
T \p{Numeric_Value: 1/16} (Short: \p{Nv=1/16}) (6: U+09F4, U+0B75,
U+0D76, U+A833, U+11FC9..11FCA)
T \p{Numeric_Value: 1/12} (Short: \p{Nv=1/12}) (1: U+109F6)
T \p{Numeric_Value: 1/10} (Short: \p{Nv=1/10}) (3: U+0D5C, U+2152,
U+11FCB)
T \p{Numeric_Value: 1/9} (Short: \p{Nv=1/9}) (1: U+2151)
T \p{Numeric_Value: 1/8} (Short: \p{Nv=1/8}) (7: U+09F5, U+0B76,
U+0D77, U+215B, U+A834, U+11FCC ...)
T \p{Numeric_Value: 1/7} (Short: \p{Nv=1/7}) (1: U+2150)
T \p{Numeric_Value: 3/20} (Short: \p{Nv=3/20}) (2: U+0D5D, U+11FCD)
T \p{Numeric_Value: 1/6} (Short: \p{Nv=1/6}) (4: U+2159, U+109F7,
U+12461, U+1ED3D)
T \p{Numeric_Value: 3/16} (Short: \p{Nv=3/16}) (5: U+09F6, U+0B77,
U+0D78, U+A835, U+11FCE)
T \p{Numeric_Value: 1/5} (Short: \p{Nv=1/5}) (3: U+0D5E, U+2155,
U+11FCF)
T \p{Numeric_Value: 1/4} (Short: \p{Nv=1/4}) (14: [\xbc], U+09F7,
U+0B72, U+0D73, U+A830, U+10140 ...)
T \p{Numeric_Value: 1/3} (Short: \p{Nv=1/3}) (6: U+2153, U+109F9,
U+10E7D, U+1245A, U+1245D, U+12465)
T \p{Numeric_Value: 3/8} (Short: \p{Nv=3/8}) (1: U+215C)
T \p{Numeric_Value: 2/5} (Short: \p{Nv=2/5}) (1: U+2156)
T \p{Numeric_Value: 5/12} (Short: \p{Nv=5/12}) (1: U+109FA)
T \p{Numeric_Value: 1/2} (Short: \p{Nv=1/2}) (19: [\xbd], U+0B73,
U+0D74, U+0F2A, U+2CFD, U+A831 ...)
T \p{Numeric_Value: 7/12} (Short: \p{Nv=7/12}) (1: U+109FC)
T \p{Numeric_Value: 3/5} (Short: \p{Nv=3/5}) (1: U+2157)
T \p{Numeric_Value: 5/8} (Short: \p{Nv=5/8}) (1: U+215D)
T \p{Numeric_Value: 2/3} (Short: \p{Nv=2/3}) (7: U+2154, U+10177,
U+109FD, U+10E7E, U+1245B, U+1245E ...)
T \p{Numeric_Value: 3/4} (Short: \p{Nv=3/4}) (9: [\xbe], U+09F8,
U+0B74, U+0D75, U+A832, U+10178 ...)
T \p{Numeric_Value: 4/5} (Short: \p{Nv=4/5}) (1: U+2158)
T \p{Numeric_Value: 5/6} (Short: \p{Nv=5/6}) (3: U+215A, U+109FF,
U+1245C)
T \p{Numeric_Value: 7/8} (Short: \p{Nv=7/8}) (1: U+215E)
T \p{Numeric_Value: 11/12} (Short: \p{Nv=11/12}) (1: U+109BC)
T \p{Numeric_Value: 1} (Short: \p{Nv=1}) (141: [1\xb9], U+0661,
U+06F1, U+07C1, U+0967, U+09E7 ...)
T \p{Numeric_Value: 3/2} (Short: \p{Nv=3/2}) (1: U+0F2B)
T \p{Numeric_Value: 2} (Short: \p{Nv=2}) (140: [2\xb2], U+0662,
U+06F2, U+07C2, U+0968, U+09E8 ...)
T \p{Numeric_Value: 5/2} (Short: \p{Nv=5/2}) (1: U+0F2C)
T \p{Numeric_Value: 3} (Short: \p{Nv=3}) (141: [3\xb3], U+0663,
U+06F3, U+07C3, U+0969, U+09E9 ...)
T \p{Numeric_Value: 7/2} (Short: \p{Nv=7/2}) (1: U+0F2D)
T \p{Numeric_Value: 4} (Short: \p{Nv=4}) (132: [4], U+0664,
U+06F4, U+07C4, U+096A, U+09EA ...)
T \p{Numeric_Value: 9/2} (Short: \p{Nv=9/2}) (1: U+0F2E)
T \p{Numeric_Value: 5} (Short: \p{Nv=5}) (130: [5], U+0665,
U+06F5, U+07C5, U+096B, U+09EB ...)
T \p{Numeric_Value: 11/2} (Short: \p{Nv=11/2}) (1: U+0F2F)
T \p{Numeric_Value: 6} (Short: \p{Nv=6}) (114: [6], U+0666,
U+06F6, U+07C6, U+096C, U+09EC ...)
T \p{Numeric_Value: 13/2} (Short: \p{Nv=13/2}) (1: U+0F30)
T \p{Numeric_Value: 7} (Short: \p{Nv=7}) (113: [7], U+0667,
U+06F7, U+07C7, U+096D, U+09ED ...)
T \p{Numeric_Value: 15/2} (Short: \p{Nv=15/2}) (1: U+0F31)
T \p{Numeric_Value: 8} (Short: \p{Nv=8}) (109: [8], U+0668,
U+06F8, U+07C8, U+096E, U+09EE ...)
T \p{Numeric_Value: 17/2} (Short: \p{Nv=17/2}) (1: U+0F32)
T \p{Numeric_Value: 9} (Short: \p{Nv=9}) (113: [9], U+0669,
U+06F9, U+07C9, U+096F, U+09EF ...)
T \p{Numeric_Value: 10} (Short: \p{Nv=10}) (62: U+0BF0, U+0D70,
U+1372, U+2169, U+2179, U+2469 ...)
T \p{Numeric_Value: 11} (Short: \p{Nv=11}) (8: U+216A, U+217A,
U+246A, U+247E, U+2492, U+24EB ...)
T \p{Numeric_Value: 12} (Short: \p{Nv=12}) (8: U+216B, U+217B,
U+246B, U+247F, U+2493, U+24EC ...)
T \p{Numeric_Value: 13} (Short: \p{Nv=13}) (6: U+246C, U+2480,
U+2494, U+24ED, U+16E8D, U+1D2ED)
T \p{Numeric_Value: 14} (Short: \p{Nv=14}) (6: U+246D, U+2481,
U+2495, U+24EE, U+16E8E, U+1D2EE)
T \p{Numeric_Value: 15} (Short: \p{Nv=15}) (6: U+246E, U+2482,
U+2496, U+24EF, U+16E8F, U+1D2EF)
T \p{Numeric_Value: 16} (Short: \p{Nv=16}) (7: U+09F9, U+246F,
U+2483, U+2497, U+24F0, U+16E90 ...)
T \p{Numeric_Value: 17} (Short: \p{Nv=17}) (7: U+16EE, U+2470,
U+2484, U+2498, U+24F1, U+16E91 ...)
T \p{Numeric_Value: 18} (Short: \p{Nv=18}) (7: U+16EF, U+2471,
U+2485, U+2499, U+24F2, U+16E92 ...)
T \p{Numeric_Value: 19} (Short: \p{Nv=19}) (7: U+16F0, U+2472,
U+2486, U+249A, U+24F3, U+16E93 ...)
T \p{Numeric_Value: 20} (Short: \p{Nv=20}) (36: U+1373, U+2473,
U+2487, U+249B, U+24F4, U+3039 ...)
T \p{Numeric_Value: 21} (Short: \p{Nv=21}) (1: U+3251)
T \p{Numeric_Value: 22} (Short: \p{Nv=22}) (1: U+3252)
T \p{Numeric_Value: 23} (Short: \p{Nv=23}) (1: U+3253)
T \p{Numeric_Value: 24} (Short: \p{Nv=24}) (1: U+3254)
T \p{Numeric_Value: 25} (Short: \p{Nv=25}) (1: U+3255)
T \p{Numeric_Value: 26} (Short: \p{Nv=26}) (1: U+3256)
T \p{Numeric_Value: 27} (Short: \p{Nv=27}) (1: U+3257)
T \p{Numeric_Value: 28} (Short: \p{Nv=28}) (1: U+3258)
T \p{Numeric_Value: 29} (Short: \p{Nv=29}) (1: U+3259)
T \p{Numeric_Value: 30} (Short: \p{Nv=30}) (19: U+1374, U+303A,
U+324A, U+325A, U+5345, U+10112 ...)
T \p{Numeric_Value: 31} (Short: \p{Nv=31}) (1: U+325B)
T \p{Numeric_Value: 32} (Short: \p{Nv=32}) (1: U+325C)
T \p{Numeric_Value: 33} (Short: \p{Nv=33}) (1: U+325D)
T \p{Numeric_Value: 34} (Short: \p{Nv=34}) (1: U+325E)
T \p{Numeric_Value: 35} (Short: \p{Nv=35}) (1: U+325F)
T \p{Numeric_Value: 36} (Short: \p{Nv=36}) (1: U+32B1)
T \p{Numeric_Value: 37} (Short: \p{Nv=37}) (1: U+32B2)
T \p{Numeric_Value: 38} (Short: \p{Nv=38}) (1: U+32B3)
T \p{Numeric_Value: 39} (Short: \p{Nv=39}) (1: U+32B4)
T \p{Numeric_Value: 40} (Short: \p{Nv=40}) (18: U+1375, U+324B,
U+32B5, U+534C, U+10113, U+102ED ...)
T \p{Numeric_Value: 41} (Short: \p{Nv=41}) (1: U+32B6)
T \p{Numeric_Value: 42} (Short: \p{Nv=42}) (1: U+32B7)
T \p{Numeric_Value: 43} (Short: \p{Nv=43}) (1: U+32B8)
T \p{Numeric_Value: 44} (Short: \p{Nv=44}) (1: U+32B9)
T \p{Numeric_Value: 45} (Short: \p{Nv=45}) (1: U+32BA)
T \p{Numeric_Value: 46} (Short: \p{Nv=46}) (1: U+32BB)
T \p{Numeric_Value: 47} (Short: \p{Nv=47}) (1: U+32BC)
T \p{Numeric_Value: 48} (Short: \p{Nv=48}) (1: U+32BD)
T \p{Numeric_Value: 49} (Short: \p{Nv=49}) (1: U+32BE)
T \p{Numeric_Value: 50} (Short: \p{Nv=50}) (29: U+1376, U+216C,
U+217C, U+2186, U+324C, U+32BF ...)
T \p{Numeric_Value: 60} (Short: \p{Nv=60}) (13: U+1377, U+324D,
U+10115, U+102EF, U+109CE, U+10E6E ...)
T \p{Numeric_Value: 70} (Short: \p{Nv=70}) (13: U+1378, U+324E,
U+10116, U+102F0, U+109CF, U+10E6F ...)
T \p{Numeric_Value: 80} (Short: \p{Nv=80}) (12: U+1379, U+324F,
U+10117, U+102F1, U+10E70, U+11062 ...)
T \p{Numeric_Value: 90} (Short: \p{Nv=90}) (12: U+137A, U+10118,
U+102F2, U+10341, U+10E71, U+11063 ...)
T \p{Numeric_Value: 100} (Short: \p{Nv=100}) (35: U+0BF1, U+0D71,
U+137B, U+216D, U+217D, U+4F70 ...)
T \p{Numeric_Value: 200} (Short: \p{Nv=200}) (6: U+1011A, U+102F4,
U+109D3, U+10E73, U+1EC84, U+1ED14)
T \p{Numeric_Value: 300} (Short: \p{Nv=300}) (7: U+1011B, U+1016B,
U+102F5, U+109D4, U+10E74, U+1EC85 ...)
T \p{Numeric_Value: 400} (Short: \p{Nv=400}) (7: U+1011C, U+102F6,
U+109D5, U+10E75, U+1EC86, U+1ED16 ...)
T \p{Numeric_Value: 500} (Short: \p{Nv=500}) (16: U+216E, U+217E,
U+1011D, U+10145, U+1014C, U+10153 ...)
T \p{Numeric_Value: 600} (Short: \p{Nv=600}) (7: U+1011E, U+102F8,
U+109D7, U+10E77, U+1EC88, U+1ED18 ...)
T \p{Numeric_Value: 700} (Short: \p{Nv=700}) (6: U+1011F, U+102F9,
U+109D8, U+10E78, U+1EC89, U+1ED19)
T \p{Numeric_Value: 800} (Short: \p{Nv=800}) (6: U+10120, U+102FA,
U+109D9, U+10E79, U+1EC8A, U+1ED1A)
T \p{Numeric_Value: 900} (Short: \p{Nv=900}) (7: U+10121, U+102FB,
U+1034A, U+109DA, U+10E7A, U+1EC8B ...)
T \p{Numeric_Value: 1000} (Short: \p{Nv=1000}) (22: U+0BF2, U+0D72,
U+216F, U+217F..2180, U+4EDF, U+5343 ...)
T \p{Numeric_Value: 2000} (Short: \p{Nv=2000}) (5: U+10123, U+109DC,
U+1EC8D, U+1ED1D, U+1ED3A)
T \p{Numeric_Value: 3000} (Short: \p{Nv=3000}) (4: U+10124, U+109DD,
U+1EC8E, U+1ED1E)
T \p{Numeric_Value: 4000} (Short: \p{Nv=4000}) (4: U+10125, U+109DE,
U+1EC8F, U+1ED1F)
T \p{Numeric_Value: 5000} (Short: \p{Nv=5000}) (8: U+2181, U+10126,
U+10146, U+1014E, U+10172, U+109DF ...)
T \p{Numeric_Value: 6000} (Short: \p{Nv=6000}) (4: U+10127, U+109E0,
U+1EC91, U+1ED21)
T \p{Numeric_Value: 7000} (Short: \p{Nv=7000}) (4: U+10128, U+109E1,
U+1EC92, U+1ED22)
T \p{Numeric_Value: 8000} (Short: \p{Nv=8000}) (4: U+10129, U+109E2,
U+1EC93, U+1ED23)
T \p{Numeric_Value: 9000} (Short: \p{Nv=9000}) (4: U+1012A, U+109E3,
U+1EC94, U+1ED24)
T \p{Numeric_Value: 10000} (= 1.0e+04) (Short: \p{Nv=10000}) (13:
U+137C, U+2182, U+4E07, U+842C, U+1012B,
U+10155 ...)
T \p{Numeric_Value: 20000} (= 2.0e+04) (Short: \p{Nv=20000}) (4:
U+1012C, U+109E5, U+1EC96, U+1ED26)
T \p{Numeric_Value: 30000} (= 3.0e+04) (Short: \p{Nv=30000}) (4:
U+1012D, U+109E6, U+1EC97, U+1ED27)
T \p{Numeric_Value: 40000} (= 4.0e+04) (Short: \p{Nv=40000}) (4:
U+1012E, U+109E7, U+1EC98, U+1ED28)
T \p{Numeric_Value: 50000} (= 5.0e+04) (Short: \p{Nv=50000}) (7:
U+2187, U+1012F, U+10147, U+10156,
U+109E8, U+1EC99 ...)
T \p{Numeric_Value: 60000} (= 6.0e+04) (Short: \p{Nv=60000}) (4:
U+10130, U+109E9, U+1EC9A, U+1ED2A)
T \p{Numeric_Value: 70000} (= 7.0e+04) (Short: \p{Nv=70000}) (4:
U+10131, U+109EA, U+1EC9B, U+1ED2B)
T \p{Numeric_Value: 80000} (= 8.0e+04) (Short: \p{Nv=80000}) (4:
U+10132, U+109EB, U+1EC9C, U+1ED2C)
T \p{Numeric_Value: 90000} (= 9.0e+04) (Short: \p{Nv=90000}) (4:
U+10133, U+109EC, U+1EC9D, U+1ED2D)
T \p{Numeric_Value: 100000} (= 1.0e+05) (Short: \p{Nv=100000}) (5:
U+2188, U+109ED, U+1EC9E, U+1ECA0,
U+1ECB4)
T \p{Numeric_Value: 200000} (= 2.0e+05) (Short: \p{Nv=200000}) (2:
U+109EE, U+1EC9F)
T \p{Numeric_Value: 216000} (= 2.2e+05) (Short: \p{Nv=216000}) (1:
U+12432)
T \p{Numeric_Value: 300000} (= 3.0e+05) (Short: \p{Nv=300000}) (1:
U+109EF)
T \p{Numeric_Value: 400000} (= 4.0e+05) (Short: \p{Nv=400000}) (1:
U+109F0)
T \p{Numeric_Value: 432000} (= 4.3e+05) (Short: \p{Nv=432000}) (1:
U+12433)
T \p{Numeric_Value: 500000} (= 5.0e+05) (Short: \p{Nv=500000}) (1:
U+109F1)
T \p{Numeric_Value: 600000} (= 6.0e+05) (Short: \p{Nv=600000}) (1:
U+109F2)
T \p{Numeric_Value: 700000} (= 7.0e+05) (Short: \p{Nv=700000}) (1:
U+109F3)
T \p{Numeric_Value: 800000} (= 8.0e+05) (Short: \p{Nv=800000}) (1:
U+109F4)
T \p{Numeric_Value: 900000} (= 9.0e+05) (Short: \p{Nv=900000}) (1:
U+109F5)
T \p{Numeric_Value: 1000000} (= 1.0e+06) (Short: \p{Nv=1000000}) (1:
U+16B5E)
T \p{Numeric_Value: 10000000} (= 1.0e+07) (Short: \p{Nv=10000000})
(1: U+1ECA1)
T \p{Numeric_Value: 20000000} (= 2.0e+07) (Short: \p{Nv=20000000})
(1: U+1ECA2)
T \p{Numeric_Value: 100000000} (= 1.0e+08) (Short: \p{Nv=100000000})
(3: U+4EBF, U+5104, U+16B5F)
T \p{Numeric_Value: 10000000000} (= 1.0e+10) (Short: \p{Nv=
10000000000}) (1: U+16B60)
T \p{Numeric_Value: 1000000000000} (= 1.0e+12) (Short: \p{Nv=
1000000000000}) (2: U+5146, U+16B61)
\p{Numeric_Value: NaN} (Short: \p{Nv=NaN}) (1_112_240 plus all
above-Unicode code points: [\x00-\x20!
\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@A-Z\[\\\]
\^_`a-z\{\|\}~\x7f-\xb1\xb4-\xb8\xba-
\xbb\xbf-\xff], U+0100..065F,
U+066A..06EF, U+06FA..07BF,
U+07CA..0965, U+0970..09E5 ...)
\p{Nushu} \p{Script_Extensions=Nushu} (Short:
\p{Nshu}; NOT \p{Block=Nushu}) (397)
\p{Nv: *} \p{Numeric_Value: *}
\p{Nyiakeng_Puachue_Hmong} \p{Script_Extensions=
Nyiakeng_Puachue_Hmong} (Short:
\p{Hmnp}; NOT \p{Block=
Nyiakeng_Puachue_Hmong}) (71)
X \p{OCR} \p{Optical_Character_Recognition} (=
\p{Block=Optical_Character_Recognition})
(32)
\p{Ogam} \p{Ogham} (= \p{Script_Extensions=Ogham})
(NOT \p{Block=Ogham}) (29)
\p{Ogham} \p{Script_Extensions=Ogham} (Short:
\p{Ogam}; NOT \p{Block=Ogham}) (29)
\p{Ol_Chiki} \p{Script_Extensions=Ol_Chiki} (Short:
\p{Olck}) (48)
\p{Olck} \p{Ol_Chiki} (= \p{Script_Extensions=
Ol_Chiki}) (48)
\p{Old_Hungarian} \p{Script_Extensions=Old_Hungarian}
(Short: \p{Hung}; NOT \p{Block=
Old_Hungarian}) (108)
\p{Old_Italic} \p{Script_Extensions=Old_Italic} (Short:
\p{Ital}; NOT \p{Block=Old_Italic}) (39)
\p{Old_North_Arabian} \p{Script_Extensions=Old_North_Arabian}
(Short: \p{Narb}) (32)
\p{Old_Permic} \p{Script_Extensions=Old_Permic} (Short:
\p{Perm}; NOT \p{Block=Old_Permic}) (44)
\p{Old_Persian} \p{Script_Extensions=Old_Persian} (Short:
\p{Xpeo}; NOT \p{Block=Old_Persian}) (50)
\p{Old_Sogdian} \p{Script_Extensions=Old_Sogdian} (Short:
\p{Sogo}; NOT \p{Block=Old_Sogdian}) (40)
\p{Old_South_Arabian} \p{Script_Extensions=Old_South_Arabian}
(Short: \p{Sarb}) (32)
\p{Old_Turkic} \p{Script_Extensions=Old_Turkic} (Short:
\p{Orkh}; NOT \p{Block=Old_Turkic}) (73)
\p{Old_Uyghur} \p{Script_Extensions=Old_Uyghur} (Short:
\p{Ougr}; NOT \p{Block=Old_Uyghur}) (28)
\p{Open_Punctuation} \p{General_Category=Open_Punctuation}
(Short: \p{Ps}) (79)
X \p{Optical_Character_Recognition} \p{Block=
Optical_Character_Recognition} (Short:
\p{InOCR}) (32)
\p{Oriya} \p{Script_Extensions=Oriya} (Short:
\p{Orya}; NOT \p{Block=Oriya}) (97)
\p{Orkh} \p{Old_Turkic} (= \p{Script_Extensions=
Old_Turkic}) (NOT \p{Block=Old_Turkic})
(73)
X \p{Ornamental_Dingbats} \p{Block=Ornamental_Dingbats} (48)
\p{Orya} \p{Oriya} (= \p{Script_Extensions=Oriya})
(NOT \p{Block=Oriya}) (97)
\p{Osage} \p{Script_Extensions=Osage} (Short:
\p{Osge}; NOT \p{Block=Osage}) (72)
\p{Osge} \p{Osage} (= \p{Script_Extensions=Osage})
(NOT \p{Block=Osage}) (72)
\p{Osma} \p{Osmanya} (= \p{Script_Extensions=
Osmanya}) (NOT \p{Block=Osmanya}) (40)
\p{Osmanya} \p{Script_Extensions=Osmanya} (Short:
\p{Osma}; NOT \p{Block=Osmanya}) (40)
\p{Other} \p{General_Category=Other} (Short: \p{C})
(969_578 plus all above-Unicode code
points)
\p{Other_Letter} \p{General_Category=Other_Letter} (Short:
\p{Lo}) (127_333)
\p{Other_Number} \p{General_Category=Other_Number} (Short:
\p{No}) (895)
\p{Other_Punctuation} \p{General_Category=Other_Punctuation}
(Short: \p{Po}) (605)
\p{Other_Symbol} \p{General_Category=Other_Symbol} (Short:
\p{So}) (6605)
X \p{Ottoman_Siyaq_Numbers} \p{Block=Ottoman_Siyaq_Numbers} (80)
\p{Ougr} \p{Old_Uyghur} (= \p{Script_Extensions=
Old_Uyghur}) (NOT \p{Block=Old_Uyghur})
(28)
\p{P} \pP \p{Punct} (= \p{General_Category=
Punctuation}) (NOT
\p{General_Punctuation}) (819)
\p{Pahawh_Hmong} \p{Script_Extensions=Pahawh_Hmong} (Short:
\p{Hmng}; NOT \p{Block=Pahawh_Hmong})
(127)
\p{Palm} \p{Palmyrene} (= \p{Script_Extensions=
Palmyrene}) (32)
\p{Palmyrene} \p{Script_Extensions=Palmyrene} (Short:
\p{Palm}) (32)
\p{Paragraph_Separator} \p{General_Category=Paragraph_Separator}
(Short: \p{Zp}) (1)
\p{Pat_Syn} \p{Pattern_Syntax} (= \p{Pattern_Syntax=
Y}) (2760)
\p{Pat_Syn: *} \p{Pattern_Syntax: *}
\p{Pat_WS} \p{Pattern_White_Space} (=
\p{Pattern_White_Space=Y}) (11)
\p{Pat_WS: *} \p{Pattern_White_Space: *}
\p{Pattern_Syntax} \p{Pattern_Syntax=Y} (Short: \p{PatSyn})
(2760)
\p{Pattern_Syntax: N*} (Short: \p{PatSyn=N}, \P{PatSyn})
(1_111_352 plus all above-Unicode code
points: [\x00-\x200-9A-Z_a-z\x7f-\xa0
\xa8\xaa\xad\xaf\xb2-\xb5\xb7-\xba\xbc-
\xbe\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..200F, U+2028..202F,
U+203F..2040, U+2054, U+205F..218F ...)
\p{Pattern_Syntax: Y*} (Short: \p{PatSyn=Y}, \p{PatSyn}) (2760:
[!\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@\[\\\]
\^`\{\|\}~\xa1-\xa7\xa9\xab-\xac\xae
\xb0-\xb1\xb6\xbb\xbf\xd7\xf7],
U+2010..2027, U+2030..203E,
U+2041..2053, U+2055..205E, U+2190..245F
...)
\p{Pattern_White_Space} \p{Pattern_White_Space=Y} (Short:
\p{PatWS}) (11)
\p{Pattern_White_Space: N*} (Short: \p{PatWS=N}, \P{PatWS})
(1_114_101 plus all above-Unicode code
points: [^\t\n\cK\f\r\x20\x85],
U+0100..200D, U+2010..2027,
U+202A..infinity)
\p{Pattern_White_Space: Y*} (Short: \p{PatWS=Y}, \p{PatWS}) (11:
[\t\n\cK\f\r\x20\x85], U+200E..200F,
U+2028..2029)
\p{Pau_Cin_Hau} \p{Script_Extensions=Pau_Cin_Hau} (Short:
\p{Pauc}; NOT \p{Block=Pau_Cin_Hau}) (57)
\p{Pauc} \p{Pau_Cin_Hau} (= \p{Script_Extensions=
Pau_Cin_Hau}) (NOT \p{Block=
Pau_Cin_Hau}) (57)
\p{Pc} \p{Connector_Punctuation} (=
\p{General_Category=
Connector_Punctuation}) (10)
\p{PCM} \p{Prepended_Concatenation_Mark} (=
\p{Prepended_Concatenation_Mark=Y}) (13)
\p{PCM: *} \p{Prepended_Concatenation_Mark: *}
\p{Pd} \p{Dash_Punctuation} (=
\p{General_Category=Dash_Punctuation})
(26)
\p{Pe} \p{Close_Punctuation} (=
\p{General_Category=Close_Punctuation})
(77)
\p{PerlSpace} \p{PosixSpace} (6)
\p{PerlWord} \p{PosixWord} (63)
\p{Perm} \p{Old_Permic} (= \p{Script_Extensions=
Old_Permic}) (NOT \p{Block=Old_Permic})
(44)
\p{Pf} \p{Final_Punctuation} (=
\p{General_Category=Final_Punctuation})
(10)
\p{Phag} \p{Phags_Pa} (= \p{Script_Extensions=
Phags_Pa}) (NOT \p{Block=Phags_Pa}) (59)
\p{Phags_Pa} \p{Script_Extensions=Phags_Pa} (Short:
\p{Phag}; NOT \p{Block=Phags_Pa}) (59)
X \p{Phaistos} \p{Phaistos_Disc} (= \p{Block=
Phaistos_Disc}) (48)
X \p{Phaistos_Disc} \p{Block=Phaistos_Disc} (Short:
\p{InPhaistos}) (48)
\p{Phli} \p{Inscriptional_Pahlavi} (=
\p{Script_Extensions=
Inscriptional_Pahlavi}) (NOT \p{Block=
Inscriptional_Pahlavi}) (27)
\p{Phlp} \p{Psalter_Pahlavi} (=
\p{Script_Extensions=Psalter_Pahlavi})
(NOT \p{Block=Psalter_Pahlavi}) (30)
\p{Phnx} \p{Phoenician} (= \p{Script_Extensions=
Phoenician}) (NOT \p{Block=Phoenician})
(29)
\p{Phoenician} \p{Script_Extensions=Phoenician} (Short:
\p{Phnx}; NOT \p{Block=Phoenician}) (29)
X \p{Phonetic_Ext} \p{Phonetic_Extensions} (= \p{Block=
Phonetic_Extensions}) (128)
X \p{Phonetic_Ext_Sup} \p{Phonetic_Extensions_Supplement} (=
\p{Block=
Phonetic_Extensions_Supplement}) (64)
X \p{Phonetic_Extensions} \p{Block=Phonetic_Extensions} (Short:
\p{InPhoneticExt}) (128)
X \p{Phonetic_Extensions_Supplement} \p{Block=
Phonetic_Extensions_Supplement} (Short:
\p{InPhoneticExtSup}) (64)
\p{Pi} \p{Initial_Punctuation} (=
\p{General_Category=
Initial_Punctuation}) (12)
X \p{Playing_Cards} \p{Block=Playing_Cards} (96)
\p{Plrd} \p{Miao} (= \p{Script_Extensions=Miao})
(NOT \p{Block=Miao}) (149)
\p{Po} \p{Other_Punctuation} (=
\p{General_Category=Other_Punctuation})
(605)
\p{PosixAlnum} (62: [0-9A-Za-z])
\p{PosixAlpha} (52: [A-Za-z])
\p{PosixBlank} (2: [\t\x20])
\p{PosixCntrl} ASCII control characters (33: ACK, BEL,
BS, CAN, CR, DC1, DC2, DC3, DC4, DEL,
DLE, ENQ, EOM, EOT, ESC, ETB, ETX, FF,
FS, GS, HT, LF, NAK, NUL, RS, SI, SO,
SOH, STX, SUB, SYN, US, VT)
\p{PosixDigit} (10: [0-9])
\p{PosixGraph} (94: [!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=>?\@A-
Z\[\\\]\^_`a-z\{\|\}~])
\p{PosixLower} (/i= PosixAlpha) (26: [a-z])
\p{PosixPrint} (95: [\x20-\x7e])
\p{PosixPunct} (32: [!\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@
\[\\\]\^_`\{\|\}~])
\p{PosixSpace} (Short: \p{PerlSpace}) (6: [\t\n\cK\f\r
\x20])
\p{PosixUpper} (/i= PosixAlpha) (26: [A-Z])
\p{PosixWord} \w, restricted to ASCII (Short:
\p{PerlWord}) (63: [0-9A-Z_a-z])
\p{PosixXDigit} \p{ASCII_Hex_Digit=Y} (Short: \p{AHex})
(22)
\p{Prepended_Concatenation_Mark} \p{Prepended_Concatenation_Mark=
Y} (Short: \p{PCM}) (13)
\p{Prepended_Concatenation_Mark: N*} (Short: \p{PCM=N}, \P{PCM})
(1_114_099 plus all above-Unicode code
points: U+0000..05FF, U+0606..06DC,
U+06DE..070E, U+0710..088F,
U+0892..08E1, U+08E3..110BC ...)
\p{Prepended_Concatenation_Mark: Y*} (Short: \p{PCM=Y}, \p{PCM})
(13: U+0600..0605, U+06DD, U+070F,
U+0890..0891, U+08E2, U+110BD ...)
T \p{Present_In: 1.1} \p{Age=V1_1} (Short: \p{In=1.1}) (Perl
extension) (33_979)
\p{Present_In: V1_1} \p{Present_In=1.1} (= \p{Age=V1_1}) (Perl
extension) (33_979)
T \p{Present_In: 2.0} Code point's usage introduced in version
2.0 or earlier (Short: \p{In=2.0}) (Perl
extension) (178_500: U+0000..01F5,
U+01FA..0217, U+0250..02A8,
U+02B0..02DE, U+02E0..02E9, U+0300..0345
...)
\p{Present_In: V2_0} \p{Present_In=2.0} (Perl extension)
(178_500)
T \p{Present_In: 2.1} Code point's usage introduced in version
2.1 or earlier (Short: \p{In=2.1}) (Perl
extension) (178_502: U+0000..01F5,
U+01FA..0217, U+0250..02A8,
U+02B0..02DE, U+02E0..02E9, U+0300..0345
...)
\p{Present_In: V2_1} \p{Present_In=2.1} (Perl extension)
(178_502)
T \p{Present_In: 3.0} Code point's usage introduced in version
3.0 or earlier (Short: \p{In=3.0}) (Perl
extension) (188_809: U+0000..021F,
U+0222..0233, U+0250..02AD,
U+02B0..02EE, U+0300..034E, U+0360..0362
...)
\p{Present_In: V3_0} \p{Present_In=3.0} (Perl extension)
(188_809)
T \p{Present_In: 3.1} Code point's usage introduced in version
3.1 or earlier (Short: \p{In=3.1}) (Perl
extension) (233_787: U+0000..021F,
U+0222..0233, U+0250..02AD,
U+02B0..02EE, U+0300..034E, U+0360..0362
...)
\p{Present_In: V3_1} \p{Present_In=3.1} (Perl extension)
(233_787)
T \p{Present_In: 3.2} Code point's usage introduced in version
3.2 or earlier (Short: \p{In=3.2}) (Perl
extension) (234_803: U+0000..0220,
U+0222..0233, U+0250..02AD,
U+02B0..02EE, U+0300..034F, U+0360..036F
...)
\p{Present_In: V3_2} \p{Present_In=3.2} (Perl extension)
(234_803)
T \p{Present_In: 4.0} Code point's usage introduced in version
4.0 or earlier (Short: \p{In=4.0}) (Perl
extension) (236_029: U+0000..0236,
U+0250..0357, U+035D..036F,
U+0374..0375, U+037A, U+037E ...)
\p{Present_In: V4_0} \p{Present_In=4.0} (Perl extension)
(236_029)
T \p{Present_In: 4.1} Code point's usage introduced in version
4.1 or earlier (Short: \p{In=4.1}) (Perl
extension) (237_302: U+0000..0241,
U+0250..036F, U+0374..0375, U+037A,
U+037E, U+0384..038A ...)
\p{Present_In: V4_1} \p{Present_In=4.1} (Perl extension)
(237_302)
T \p{Present_In: 5.0} Code point's usage introduced in version
5.0 or earlier (Short: \p{In=5.0}) (Perl
extension) (238_671: U+0000..036F,
U+0374..0375, U+037A..037E,
U+0384..038A, U+038C, U+038E..03A1 ...)
\p{Present_In: V5_0} \p{Present_In=5.0} (Perl extension)
(238_671)
T \p{Present_In: 5.1} Code point's usage introduced in version
5.1 or earlier (Short: \p{In=5.1}) (Perl
extension) (240_295: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0523 ...)
\p{Present_In: V5_1} \p{Present_In=5.1} (Perl extension)
(240_295)
T \p{Present_In: 5.2} Code point's usage introduced in version
5.2 or earlier (Short: \p{In=5.2}) (Perl
extension) (246_943: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0525 ...)
\p{Present_In: V5_2} \p{Present_In=5.2} (Perl extension)
(246_943)
T \p{Present_In: 6.0} Code point's usage introduced in version
6.0 or earlier (Short: \p{In=6.0}) (Perl
extension) (249_031: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0527 ...)
\p{Present_In: V6_0} \p{Present_In=6.0} (Perl extension)
(249_031)
T \p{Present_In: 6.1} Code point's usage introduced in version
6.1 or earlier (Short: \p{In=6.1}) (Perl
extension) (249_763: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0527 ...)
\p{Present_In: V6_1} \p{Present_In=6.1} (Perl extension)
(249_763)
T \p{Present_In: 6.2} Code point's usage introduced in version
6.2 or earlier (Short: \p{In=6.2}) (Perl
extension) (249_764: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0527 ...)
\p{Present_In: V6_2} \p{Present_In=6.2} (Perl extension)
(249_764)
T \p{Present_In: 6.3} Code point's usage introduced in version
6.3 or earlier (Short: \p{In=6.3}) (Perl
extension) (249_769: U+0000..0377,
U+037A..037E, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..0527 ...)
\p{Present_In: V6_3} \p{Present_In=6.3} (Perl extension)
(249_769)
T \p{Present_In: 7.0} Code point's usage introduced in version
7.0 or earlier (Short: \p{In=7.0}) (Perl
extension) (252_603: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V7_0} \p{Present_In=7.0} (Perl extension)
(252_603)
T \p{Present_In: 8.0} Code point's usage introduced in version
8.0 or earlier (Short: \p{In=8.0}) (Perl
extension) (260_319: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V8_0} \p{Present_In=8.0} (Perl extension)
(260_319)
T \p{Present_In: 9.0} Code point's usage introduced in version
9.0 or earlier (Short: \p{In=9.0}) (Perl
extension) (267_819: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V9_0} \p{Present_In=9.0} (Perl extension)
(267_819)
T \p{Present_In: 10.0} Code point's usage introduced in version
10.0 or earlier (Short: \p{In=10.0})
(Perl extension) (276_337: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V10_0} \p{Present_In=10.0} (Perl extension)
(276_337)
T \p{Present_In: 11.0} Code point's usage introduced in version
11.0 or earlier (Short: \p{In=11.0})
(Perl extension) (277_021: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V11_0} \p{Present_In=11.0} (Perl extension)
(277_021)
T \p{Present_In: 12.0} Code point's usage introduced in version
12.0 or earlier (Short: \p{In=12.0})
(Perl extension) (277_575: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V12_0} \p{Present_In=12.0} (Perl extension)
(277_575)
T \p{Present_In: 12.1} Code point's usage introduced in version
12.1 or earlier (Short: \p{In=12.1})
(Perl extension) (277_576: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V12_1} \p{Present_In=12.1} (Perl extension)
(277_576)
T \p{Present_In: 13.0} Code point's usage introduced in version
13.0 or earlier (Short: \p{In=13.0})
(Perl extension) (283_506: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V13_0} \p{Present_In=13.0} (Perl extension)
(283_506)
T \p{Present_In: 14.0} Code point's usage introduced in version
14.0 or earlier (Short: \p{In=14.0})
(Perl extension) (284_344: U+0000..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1, U+03A3..052F ...)
\p{Present_In: V14_0} \p{Present_In=14.0} (Perl extension)
(284_344)
\p{Present_In: NA} \p{Present_In=Unassigned} (= \p{Age=
Unassigned}) (Perl extension) (829_768
plus all above-Unicode code points)
\p{Present_In: Unassigned} \p{Age=Unassigned} (Short: \p{In=NA})
(Perl extension) (829_768 plus all
above-Unicode code points)
\p{Print} \p{XPosixPrint} (282_163)
\p{Private_Use} \p{General_Category=Private_Use} (Short:
\p{Co}; NOT \p{Private_Use_Area})
(137_468)
X \p{Private_Use_Area} \p{Block=Private_Use_Area} (Short:
\p{InPUA}) (6400)
\p{Prti} \p{Inscriptional_Parthian} (=
\p{Script_Extensions=
Inscriptional_Parthian}) (NOT \p{Block=
Inscriptional_Parthian}) (30)
\p{Ps} \p{Open_Punctuation} (=
\p{General_Category=Open_Punctuation})
(79)
\p{Psalter_Pahlavi} \p{Script_Extensions=Psalter_Pahlavi}
(Short: \p{Phlp}; NOT \p{Block=
Psalter_Pahlavi}) (30)
X \p{PUA} \p{Private_Use_Area} (= \p{Block=
Private_Use_Area}) (6400)
\p{Punct} \p{General_Category=Punctuation} (Short:
\p{P}; NOT \p{General_Punctuation}) (819)
\p{Punctuation} \p{Punct} (= \p{General_Category=
Punctuation}) (NOT
\p{General_Punctuation}) (819)
\p{Qaac} \p{Coptic} (= \p{Script_Extensions=
Coptic}) (NOT \p{Block=Coptic}) (165)
\p{Qaai} \p{Inherited} (= \p{Script_Extensions=
Inherited}) (586)
\p{QMark} \p{Quotation_Mark} (= \p{Quotation_Mark=
Y}) (30)
\p{QMark: *} \p{Quotation_Mark: *}
\p{Quotation_Mark} \p{Quotation_Mark=Y} (Short: \p{QMark})
(30)
\p{Quotation_Mark: N*} (Short: \p{QMark=N}, \P{QMark}) (1_114_082
plus all above-Unicode code points:
[\x00-\x20!#\$\%&\(\)*+,\-.\/0-9:;<=>?
\@A-Z\[\\\]\^_`a-z\{\|\}~\x7f-\xaa\xac-
\xba\xbc-\xff], U+0100..2017,
U+2020..2038, U+203B..2E41,
U+2E43..300B, U+3010..301C ...)
\p{Quotation_Mark: Y*} (Short: \p{QMark=Y}, \p{QMark}) (30: [\"
\'\xab\xbb], U+2018..201F, U+2039..203A,
U+2E42, U+300C..300F, U+301D..301F ...)
\p{Radical} \p{Radical=Y} (329)
\p{Radical: N*} (Single: \P{Radical}) (1_113_783 plus all
above-Unicode code points: U+0000..2E7F,
U+2E9A, U+2EF4..2EFF, U+2FD6..infinity)
\p{Radical: Y*} (Single: \p{Radical}) (329: U+2E80..2E99,
U+2E9B..2EF3, U+2F00..2FD5)
\p{Regional_Indicator} \p{Regional_Indicator=Y} (Short: \p{RI})
(26)
\p{Regional_Indicator: N*} (Short: \p{RI=N}, \P{RI}) (1_114_086
plus all above-Unicode code points:
U+0000..1F1E5, U+1F200..infinity)
\p{Regional_Indicator: Y*} (Short: \p{RI=Y}, \p{RI}) (26:
U+1F1E6..1F1FF)
\p{Rejang} \p{Script_Extensions=Rejang} (Short:
\p{Rjng}; NOT \p{Block=Rejang}) (37)
\p{RI} \p{Regional_Indicator} (=
\p{Regional_Indicator=Y}) (26)
\p{RI: *} \p{Regional_Indicator: *}
\p{Rjng} \p{Rejang} (= \p{Script_Extensions=
Rejang}) (NOT \p{Block=Rejang}) (37)
\p{Rohg} \p{Hanifi_Rohingya} (=
\p{Script_Extensions=Hanifi_Rohingya})
(NOT \p{Block=Hanifi_Rohingya}) (55)
X \p{Rumi} \p{Rumi_Numeral_Symbols} (= \p{Block=
Rumi_Numeral_Symbols}) (32)
X \p{Rumi_Numeral_Symbols} \p{Block=Rumi_Numeral_Symbols} (Short:
\p{InRumi}) (32)
\p{Runic} \p{Script_Extensions=Runic} (Short:
\p{Runr}; NOT \p{Block=Runic}) (86)
\p{Runr} \p{Runic} (= \p{Script_Extensions=Runic})
(NOT \p{Block=Runic}) (86)
\p{S} \pS \p{Symbol} (= \p{General_Category=Symbol})
(7741)
\p{Samaritan} \p{Script_Extensions=Samaritan} (Short:
\p{Samr}; NOT \p{Block=Samaritan}) (61)
\p{Samr} \p{Samaritan} (= \p{Script_Extensions=
Samaritan}) (NOT \p{Block=Samaritan})
(61)
\p{Sarb} \p{Old_South_Arabian} (=
\p{Script_Extensions=Old_South_Arabian})
(32)
\p{Saur} \p{Saurashtra} (= \p{Script_Extensions=
Saurashtra}) (NOT \p{Block=Saurashtra})
(82)
\p{Saurashtra} \p{Script_Extensions=Saurashtra} (Short:
\p{Saur}; NOT \p{Block=Saurashtra}) (82)
\p{SB: *} \p{Sentence_Break: *}
\p{Sc} \p{Currency_Symbol} (=
\p{General_Category=Currency_Symbol})
(63)
\p{Sc: *} \p{Script: *}
\p{Script: Adlam} (Short: \p{Sc=Adlm}) (88: U+1E900..1E94B,
U+1E950..1E959, U+1E95E..1E95F)
\p{Script: Adlm} \p{Script=Adlam} (88)
\p{Script: Aghb} \p{Script=Caucasian_Albanian} (=
\p{Script_Extensions=
Caucasian_Albanian}) (53)
\p{Script: Ahom} \p{Script_Extensions=Ahom} (Short: \p{Sc=
Ahom}, \p{Ahom}) (65)
\p{Script: Anatolian_Hieroglyphs} \p{Script_Extensions=
Anatolian_Hieroglyphs} (Short: \p{Sc=
Hluw}, \p{Hluw}) (583)
\p{Script: Arab} \p{Script=Arabic} (1365)
\p{Script: Arabic} (Short: \p{Sc=Arab}) (1365: U+0600..0604,
U+0606..060B, U+060D..061A,
U+061C..061E, U+0620..063F, U+0641..064A
...)
\p{Script: Armenian} \p{Script_Extensions=Armenian} (Short:
\p{Sc=Armn}, \p{Armn}) (96)
\p{Script: Armi} \p{Script=Imperial_Aramaic} (=
\p{Script_Extensions=Imperial_Aramaic})
(31)
\p{Script: Armn} \p{Script=Armenian} (=
\p{Script_Extensions=Armenian}) (96)
\p{Script: Avestan} \p{Script_Extensions=Avestan} (Short:
\p{Sc=Avst}, \p{Avst}) (61)
\p{Script: Avst} \p{Script=Avestan} (=
\p{Script_Extensions=Avestan}) (61)
\p{Script: Bali} \p{Script=Balinese} (=
\p{Script_Extensions=Balinese}) (124)
\p{Script: Balinese} \p{Script_Extensions=Balinese} (Short:
\p{Sc=Bali}, \p{Bali}) (124)
\p{Script: Bamu} \p{Script=Bamum} (= \p{Script_Extensions=
Bamum}) (657)
\p{Script: Bamum} \p{Script_Extensions=Bamum} (Short: \p{Sc=
Bamu}, \p{Bamu}) (657)
\p{Script: Bass} \p{Script=Bassa_Vah} (=
\p{Script_Extensions=Bassa_Vah}) (36)
\p{Script: Bassa_Vah} \p{Script_Extensions=Bassa_Vah} (Short:
\p{Sc=Bass}, \p{Bass}) (36)
\p{Script: Batak} \p{Script_Extensions=Batak} (Short: \p{Sc=
Batk}, \p{Batk}) (56)
\p{Script: Batk} \p{Script=Batak} (= \p{Script_Extensions=
Batak}) (56)
\p{Script: Beng} \p{Script=Bengali} (96)
\p{Script: Bengali} (Short: \p{Sc=Beng}) (96: U+0980..0983,
U+0985..098C, U+098F..0990,
U+0993..09A8, U+09AA..09B0, U+09B2 ...)
\p{Script: Bhaiksuki} \p{Script_Extensions=Bhaiksuki} (Short:
\p{Sc=Bhks}, \p{Bhks}) (97)
\p{Script: Bhks} \p{Script=Bhaiksuki} (=
\p{Script_Extensions=Bhaiksuki}) (97)
\p{Script: Bopo} \p{Script=Bopomofo} (77)
\p{Script: Bopomofo} (Short: \p{Sc=Bopo}) (77: U+02EA..02EB,
U+3105..312F, U+31A0..31BF)
\p{Script: Brah} \p{Script=Brahmi} (= \p{Script_Extensions=
Brahmi}) (115)
\p{Script: Brahmi} \p{Script_Extensions=Brahmi} (Short:
\p{Sc=Brah}, \p{Brah}) (115)
\p{Script: Brai} \p{Script=Braille} (=
\p{Script_Extensions=Braille}) (256)
\p{Script: Braille} \p{Script_Extensions=Braille} (Short:
\p{Sc=Brai}, \p{Brai}) (256)
\p{Script: Bugi} \p{Script=Buginese} (30)
\p{Script: Buginese} (Short: \p{Sc=Bugi}) (30: U+1A00..1A1B,
U+1A1E..1A1F)
\p{Script: Buhd} \p{Script=Buhid} (20)
\p{Script: Buhid} (Short: \p{Sc=Buhd}) (20: U+1740..1753)
\p{Script: Cakm} \p{Script=Chakma} (71)
\p{Script: Canadian_Aboriginal} \p{Script_Extensions=
Canadian_Aboriginal} (Short: \p{Sc=
Cans}, \p{Cans}) (726)
\p{Script: Cans} \p{Script=Canadian_Aboriginal} (=
\p{Script_Extensions=
Canadian_Aboriginal}) (726)
\p{Script: Cari} \p{Script=Carian} (= \p{Script_Extensions=
Carian}) (49)
\p{Script: Carian} \p{Script_Extensions=Carian} (Short:
\p{Sc=Cari}, \p{Cari}) (49)
\p{Script: Caucasian_Albanian} \p{Script_Extensions=
Caucasian_Albanian} (Short: \p{Sc=Aghb},
\p{Aghb}) (53)
\p{Script: Chakma} (Short: \p{Sc=Cakm}) (71: U+11100..11134,
U+11136..11147)
\p{Script: Cham} \p{Script_Extensions=Cham} (Short: \p{Sc=
Cham}, \p{Cham}) (83)
\p{Script: Cher} \p{Script=Cherokee} (=
\p{Script_Extensions=Cherokee}) (172)
\p{Script: Cherokee} \p{Script_Extensions=Cherokee} (Short:
\p{Sc=Cher}, \p{Cher}) (172)
\p{Script: Chorasmian} \p{Script_Extensions=Chorasmian} (Short:
\p{Sc=Chrs}, \p{Chrs}) (28)
\p{Script: Chrs} \p{Script=Chorasmian} (=
\p{Script_Extensions=Chorasmian}) (28)
\p{Script: Common} (Short: \p{Sc=Zyyy}) (8252: [\x00-\x20!
\"#\$\%&\'\(\)*+,\-.\/0-9:;<=>?\@\[\\\]
\^_`\{\|\}~\x7f-\xa9\xab-\xb9\xbb-\xbf
\xd7\xf7], U+02B9..02DF, U+02E5..02E9,
U+02EC..02FF, U+0374, U+037E ...)
\p{Script: Copt} \p{Script=Coptic} (137)
\p{Script: Coptic} (Short: \p{Sc=Copt}) (137: U+03E2..03EF,
U+2C80..2CF3, U+2CF9..2CFF)
\p{Script: Cpmn} \p{Script=Cypro_Minoan} (99)
\p{Script: Cprt} \p{Script=Cypriot} (55)
\p{Script: Cuneiform} \p{Script_Extensions=Cuneiform} (Short:
\p{Sc=Xsux}, \p{Xsux}) (1234)
\p{Script: Cypriot} (Short: \p{Sc=Cprt}) (55: U+10800..10805,
U+10808, U+1080A..10835, U+10837..10838,
U+1083C, U+1083F)
\p{Script: Cypro_Minoan} (Short: \p{Sc=Cpmn}) (99: U+12F90..12FF2)
\p{Script: Cyrillic} (Short: \p{Sc=Cyrl}) (443: U+0400..0484,
U+0487..052F, U+1C80..1C88, U+1D2B,
U+1D78, U+2DE0..2DFF ...)
\p{Script: Cyrl} \p{Script=Cyrillic} (443)
\p{Script: Deseret} \p{Script_Extensions=Deseret} (Short:
\p{Sc=Dsrt}, \p{Dsrt}) (80)
\p{Script: Deva} \p{Script=Devanagari} (154)
\p{Script: Devanagari} (Short: \p{Sc=Deva}) (154: U+0900..0950,
U+0955..0963, U+0966..097F, U+A8E0..A8FF)
\p{Script: Diak} \p{Script=Dives_Akuru} (=
\p{Script_Extensions=Dives_Akuru}) (72)
\p{Script: Dives_Akuru} \p{Script_Extensions=Dives_Akuru} (Short:
\p{Sc=Diak}, \p{Diak}) (72)
\p{Script: Dogr} \p{Script=Dogra} (60)
\p{Script: Dogra} (Short: \p{Sc=Dogr}) (60: U+11800..1183B)
\p{Script: Dsrt} \p{Script=Deseret} (=
\p{Script_Extensions=Deseret}) (80)
\p{Script: Dupl} \p{Script=Duployan} (143)
\p{Script: Duployan} (Short: \p{Sc=Dupl}) (143: U+1BC00..1BC6A,
U+1BC70..1BC7C, U+1BC80..1BC88,
U+1BC90..1BC99, U+1BC9C..1BC9F)
\p{Script: Egyp} \p{Script=Egyptian_Hieroglyphs} (=
\p{Script_Extensions=
Egyptian_Hieroglyphs}) (1080)
\p{Script: Egyptian_Hieroglyphs} \p{Script_Extensions=
Egyptian_Hieroglyphs} (Short: \p{Sc=
Egyp}, \p{Egyp}) (1080)
\p{Script: Elba} \p{Script=Elbasan} (=
\p{Script_Extensions=Elbasan}) (40)
\p{Script: Elbasan} \p{Script_Extensions=Elbasan} (Short:
\p{Sc=Elba}, \p{Elba}) (40)
\p{Script: Elym} \p{Script=Elymaic} (=
\p{Script_Extensions=Elymaic}) (23)
\p{Script: Elymaic} \p{Script_Extensions=Elymaic} (Short:
\p{Sc=Elym}, \p{Elym}) (23)
\p{Script: Ethi} \p{Script=Ethiopic} (=
\p{Script_Extensions=Ethiopic}) (523)
\p{Script: Ethiopic} \p{Script_Extensions=Ethiopic} (Short:
\p{Sc=Ethi}, \p{Ethi}) (523)
\p{Script: Geor} \p{Script=Georgian} (173)
\p{Script: Georgian} (Short: \p{Sc=Geor}) (173: U+10A0..10C5,
U+10C7, U+10CD, U+10D0..10FA,
U+10FC..10FF, U+1C90..1CBA ...)
\p{Script: Glag} \p{Script=Glagolitic} (134)
\p{Script: Glagolitic} (Short: \p{Sc=Glag}) (134: U+2C00..2C5F,
U+1E000..1E006, U+1E008..1E018,
U+1E01B..1E021, U+1E023..1E024,
U+1E026..1E02A)
\p{Script: Gong} \p{Script=Gunjala_Gondi} (63)
\p{Script: Gonm} \p{Script=Masaram_Gondi} (75)
\p{Script: Goth} \p{Script=Gothic} (= \p{Script_Extensions=
Gothic}) (27)
\p{Script: Gothic} \p{Script_Extensions=Gothic} (Short:
\p{Sc=Goth}, \p{Goth}) (27)
\p{Script: Gran} \p{Script=Grantha} (85)
\p{Script: Grantha} (Short: \p{Sc=Gran}) (85: U+11300..11303,
U+11305..1130C, U+1130F..11310,
U+11313..11328, U+1132A..11330,
U+11332..11333 ...)
\p{Script: Greek} (Short: \p{Sc=Grek}) (518: U+0370..0373,
U+0375..0377, U+037A..037D, U+037F,
U+0384, U+0386 ...)
\p{Script: Grek} \p{Script=Greek} (518)
\p{Script: Gujarati} (Short: \p{Sc=Gujr}) (91: U+0A81..0A83,
U+0A85..0A8D, U+0A8F..0A91,
U+0A93..0AA8, U+0AAA..0AB0, U+0AB2..0AB3
...)
\p{Script: Gujr} \p{Script=Gujarati} (91)
\p{Script: Gunjala_Gondi} (Short: \p{Sc=Gong}) (63:
U+11D60..11D65, U+11D67..11D68,
U+11D6A..11D8E, U+11D90..11D91,
U+11D93..11D98, U+11DA0..11DA9)
\p{Script: Gurmukhi} (Short: \p{Sc=Guru}) (80: U+0A01..0A03,
U+0A05..0A0A, U+0A0F..0A10,
U+0A13..0A28, U+0A2A..0A30, U+0A32..0A33
...)
\p{Script: Guru} \p{Script=Gurmukhi} (80)
\p{Script: Han} (Short: \p{Sc=Han}) (94_215: U+2E80..2E99,
U+2E9B..2EF3, U+2F00..2FD5, U+3005,
U+3007, U+3021..3029 ...)
\p{Script: Hang} \p{Script=Hangul} (11_739)
\p{Script: Hangul} (Short: \p{Sc=Hang}) (11_739:
U+1100..11FF, U+302E..302F,
U+3131..318E, U+3200..321E,
U+3260..327E, U+A960..A97C ...)
\p{Script: Hani} \p{Script=Han} (94_215)
\p{Script: Hanifi_Rohingya} (Short: \p{Sc=Rohg}) (50:
U+10D00..10D27, U+10D30..10D39)
\p{Script: Hano} \p{Script=Hanunoo} (21)
\p{Script: Hanunoo} (Short: \p{Sc=Hano}) (21: U+1720..1734)
\p{Script: Hatr} \p{Script=Hatran} (= \p{Script_Extensions=
Hatran}) (26)
\p{Script: Hatran} \p{Script_Extensions=Hatran} (Short:
\p{Sc=Hatr}, \p{Hatr}) (26)
\p{Script: Hebr} \p{Script=Hebrew} (= \p{Script_Extensions=
Hebrew}) (134)
\p{Script: Hebrew} \p{Script_Extensions=Hebrew} (Short:
\p{Sc=Hebr}, \p{Hebr}) (134)
\p{Script: Hira} \p{Script=Hiragana} (380)
\p{Script: Hiragana} (Short: \p{Sc=Hira}) (380: U+3041..3096,
U+309D..309F, U+1B001..1B11F,
U+1B150..1B152, U+1F200)
\p{Script: Hluw} \p{Script=Anatolian_Hieroglyphs} (=
\p{Script_Extensions=
Anatolian_Hieroglyphs}) (583)
\p{Script: Hmng} \p{Script=Pahawh_Hmong} (=
\p{Script_Extensions=Pahawh_Hmong}) (127)
\p{Script: Hmnp} \p{Script=Nyiakeng_Puachue_Hmong} (=
\p{Script_Extensions=
Nyiakeng_Puachue_Hmong}) (71)
\p{Script: Hung} \p{Script=Old_Hungarian} (=
\p{Script_Extensions=Old_Hungarian})
(108)
\p{Script: Imperial_Aramaic} \p{Script_Extensions=
Imperial_Aramaic} (Short: \p{Sc=Armi},
\p{Armi}) (31)
\p{Script: Inherited} (Short: \p{Sc=Zinh}) (657: U+0300..036F,
U+0485..0486, U+064B..0655, U+0670,
U+0951..0954, U+1AB0..1ACE ...)
\p{Script: Inscriptional_Pahlavi} \p{Script_Extensions=
Inscriptional_Pahlavi} (Short: \p{Sc=
Phli}, \p{Phli}) (27)
\p{Script: Inscriptional_Parthian} \p{Script_Extensions=
Inscriptional_Parthian} (Short: \p{Sc=
Prti}, \p{Prti}) (30)
\p{Script: Ital} \p{Script=Old_Italic} (=
\p{Script_Extensions=Old_Italic}) (39)
\p{Script: Java} \p{Script=Javanese} (90)
\p{Script: Javanese} (Short: \p{Sc=Java}) (90: U+A980..A9CD,
U+A9D0..A9D9, U+A9DE..A9DF)
\p{Script: Kaithi} (Short: \p{Sc=Kthi}) (68: U+11080..110C2,
U+110CD)
\p{Script: Kali} \p{Script=Kayah_Li} (47)
\p{Script: Kana} \p{Script=Katakana} (320)
\p{Script: Kannada} (Short: \p{Sc=Knda}) (90: U+0C80..0C8C,
U+0C8E..0C90, U+0C92..0CA8,
U+0CAA..0CB3, U+0CB5..0CB9, U+0CBC..0CC4
...)
\p{Script: Katakana} (Short: \p{Sc=Kana}) (320: U+30A1..30FA,
U+30FD..30FF, U+31F0..31FF,
U+32D0..32FE, U+3300..3357, U+FF66..FF6F
...)
\p{Script: Kayah_Li} (Short: \p{Sc=Kali}) (47: U+A900..A92D,
U+A92F)
\p{Script: Khar} \p{Script=Kharoshthi} (=
\p{Script_Extensions=Kharoshthi}) (68)
\p{Script: Kharoshthi} \p{Script_Extensions=Kharoshthi} (Short:
\p{Sc=Khar}, \p{Khar}) (68)
\p{Script: Khitan_Small_Script} \p{Script_Extensions=
Khitan_Small_Script} (Short: \p{Sc=
Kits}, \p{Kits}) (471)
\p{Script: Khmer} \p{Script_Extensions=Khmer} (Short: \p{Sc=
Khmr}, \p{Khmr}) (146)
\p{Script: Khmr} \p{Script=Khmer} (= \p{Script_Extensions=
Khmer}) (146)
\p{Script: Khoj} \p{Script=Khojki} (62)
\p{Script: Khojki} (Short: \p{Sc=Khoj}) (62: U+11200..11211,
U+11213..1123E)
\p{Script: Khudawadi} (Short: \p{Sc=Sind}) (69: U+112B0..112EA,
U+112F0..112F9)
\p{Script: Kits} \p{Script=Khitan_Small_Script} (=
\p{Script_Extensions=
Khitan_Small_Script}) (471)
\p{Script: Knda} \p{Script=Kannada} (90)
\p{Script: Kthi} \p{Script=Kaithi} (68)
\p{Script: Lana} \p{Script=Tai_Tham} (=
\p{Script_Extensions=Tai_Tham}) (127)
\p{Script: Lao} \p{Script_Extensions=Lao} (Short: \p{Sc=
Lao}, \p{Lao}) (82)
\p{Script: Laoo} \p{Script=Lao} (= \p{Script_Extensions=
Lao}) (82)
\p{Script: Latin} (Short: \p{Sc=Latn}) (1475: [A-Za-z\xaa
\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02B8, U+02E0..02E4,
U+1D00..1D25, U+1D2C..1D5C, U+1D62..1D65
...)
\p{Script: Latn} \p{Script=Latin} (1475)
\p{Script: Lepc} \p{Script=Lepcha} (= \p{Script_Extensions=
Lepcha}) (74)
\p{Script: Lepcha} \p{Script_Extensions=Lepcha} (Short:
\p{Sc=Lepc}, \p{Lepc}) (74)
\p{Script: Limb} \p{Script=Limbu} (68)
\p{Script: Limbu} (Short: \p{Sc=Limb}) (68: U+1900..191E,
U+1920..192B, U+1930..193B, U+1940,
U+1944..194F)
\p{Script: Lina} \p{Script=Linear_A} (341)
\p{Script: Linb} \p{Script=Linear_B} (211)
\p{Script: Linear_A} (Short: \p{Sc=Lina}) (341: U+10600..10736,
U+10740..10755, U+10760..10767)
\p{Script: Linear_B} (Short: \p{Sc=Linb}) (211: U+10000..1000B,
U+1000D..10026, U+10028..1003A,
U+1003C..1003D, U+1003F..1004D,
U+10050..1005D ...)
\p{Script: Lisu} \p{Script_Extensions=Lisu} (Short: \p{Sc=
Lisu}, \p{Lisu}) (49)
\p{Script: Lyci} \p{Script=Lycian} (= \p{Script_Extensions=
Lycian}) (29)
\p{Script: Lycian} \p{Script_Extensions=Lycian} (Short:
\p{Sc=Lyci}, \p{Lyci}) (29)
\p{Script: Lydi} \p{Script=Lydian} (= \p{Script_Extensions=
Lydian}) (27)
\p{Script: Lydian} \p{Script_Extensions=Lydian} (Short:
\p{Sc=Lydi}, \p{Lydi}) (27)
\p{Script: Mahajani} (Short: \p{Sc=Mahj}) (39: U+11150..11176)
\p{Script: Mahj} \p{Script=Mahajani} (39)
\p{Script: Maka} \p{Script=Makasar} (=
\p{Script_Extensions=Makasar}) (25)
\p{Script: Makasar} \p{Script_Extensions=Makasar} (Short:
\p{Sc=Maka}, \p{Maka}) (25)
\p{Script: Malayalam} (Short: \p{Sc=Mlym}) (118: U+0D00..0D0C,
U+0D0E..0D10, U+0D12..0D44,
U+0D46..0D48, U+0D4A..0D4F, U+0D54..0D63
...)
\p{Script: Mand} \p{Script=Mandaic} (29)
\p{Script: Mandaic} (Short: \p{Sc=Mand}) (29: U+0840..085B,
U+085E)
\p{Script: Mani} \p{Script=Manichaean} (51)
\p{Script: Manichaean} (Short: \p{Sc=Mani}) (51: U+10AC0..10AE6,
U+10AEB..10AF6)
\p{Script: Marc} \p{Script=Marchen} (=
\p{Script_Extensions=Marchen}) (68)
\p{Script: Marchen} \p{Script_Extensions=Marchen} (Short:
\p{Sc=Marc}, \p{Marc}) (68)
\p{Script: Masaram_Gondi} (Short: \p{Sc=Gonm}) (75:
U+11D00..11D06, U+11D08..11D09,
U+11D0B..11D36, U+11D3A, U+11D3C..11D3D,
U+11D3F..11D47 ...)
\p{Script: Medefaidrin} \p{Script_Extensions=Medefaidrin} (Short:
\p{Sc=Medf}, \p{Medf}) (91)
\p{Script: Medf} \p{Script=Medefaidrin} (=
\p{Script_Extensions=Medefaidrin}) (91)
\p{Script: Meetei_Mayek} \p{Script_Extensions=Meetei_Mayek}
(Short: \p{Sc=Mtei}, \p{Mtei}) (79)
\p{Script: Mend} \p{Script=Mende_Kikakui} (=
\p{Script_Extensions=Mende_Kikakui})
(213)
\p{Script: Mende_Kikakui} \p{Script_Extensions=Mende_Kikakui}
(Short: \p{Sc=Mend}, \p{Mend}) (213)
\p{Script: Merc} \p{Script=Meroitic_Cursive} (=
\p{Script_Extensions=Meroitic_Cursive})
(90)
\p{Script: Mero} \p{Script=Meroitic_Hieroglyphs} (=
\p{Script_Extensions=
Meroitic_Hieroglyphs}) (32)
\p{Script: Meroitic_Cursive} \p{Script_Extensions=
Meroitic_Cursive} (Short: \p{Sc=Merc},
\p{Merc}) (90)
\p{Script: Meroitic_Hieroglyphs} \p{Script_Extensions=
Meroitic_Hieroglyphs} (Short: \p{Sc=
Mero}, \p{Mero}) (32)
\p{Script: Miao} \p{Script_Extensions=Miao} (Short: \p{Sc=
Miao}, \p{Miao}) (149)
\p{Script: Mlym} \p{Script=Malayalam} (118)
\p{Script: Modi} (Short: \p{Sc=Modi}) (79: U+11600..11644,
U+11650..11659)
\p{Script: Mong} \p{Script=Mongolian} (168)
\p{Script: Mongolian} (Short: \p{Sc=Mong}) (168: U+1800..1801,
U+1804, U+1806..1819, U+1820..1878,
U+1880..18AA, U+11660..1166C)
\p{Script: Mro} \p{Script_Extensions=Mro} (Short: \p{Sc=
Mro}, \p{Mro}) (43)
\p{Script: Mroo} \p{Script=Mro} (= \p{Script_Extensions=
Mro}) (43)
\p{Script: Mtei} \p{Script=Meetei_Mayek} (=
\p{Script_Extensions=Meetei_Mayek}) (79)
\p{Script: Mult} \p{Script=Multani} (38)
\p{Script: Multani} (Short: \p{Sc=Mult}) (38: U+11280..11286,
U+11288, U+1128A..1128D, U+1128F..1129D,
U+1129F..112A9)
\p{Script: Myanmar} (Short: \p{Sc=Mymr}) (223: U+1000..109F,
U+A9E0..A9FE, U+AA60..AA7F)
\p{Script: Mymr} \p{Script=Myanmar} (223)
\p{Script: Nabataean} \p{Script_Extensions=Nabataean} (Short:
\p{Sc=Nbat}, \p{Nbat}) (40)
\p{Script: Nand} \p{Script=Nandinagari} (65)
\p{Script: Nandinagari} (Short: \p{Sc=Nand}) (65: U+119A0..119A7,
U+119AA..119D7, U+119DA..119E4)
\p{Script: Narb} \p{Script=Old_North_Arabian} (=
\p{Script_Extensions=Old_North_Arabian})
(32)
\p{Script: Nbat} \p{Script=Nabataean} (=
\p{Script_Extensions=Nabataean}) (40)
\p{Script: New_Tai_Lue} \p{Script_Extensions=New_Tai_Lue} (Short:
\p{Sc=Talu}, \p{Talu}) (83)
\p{Script: Newa} \p{Script_Extensions=Newa} (Short: \p{Sc=
Newa}, \p{Newa}) (97)
\p{Script: Nko} (Short: \p{Sc=Nko}) (62: U+07C0..07FA,
U+07FD..07FF)
\p{Script: Nkoo} \p{Script=Nko} (62)
\p{Script: Nshu} \p{Script=Nushu} (= \p{Script_Extensions=
Nushu}) (397)
\p{Script: Nushu} \p{Script_Extensions=Nushu} (Short: \p{Sc=
Nshu}, \p{Nshu}) (397)
\p{Script: Nyiakeng_Puachue_Hmong} \p{Script_Extensions=
Nyiakeng_Puachue_Hmong} (Short: \p{Sc=
Hmnp}, \p{Hmnp}) (71)
\p{Script: Ogam} \p{Script=Ogham} (= \p{Script_Extensions=
Ogham}) (29)
\p{Script: Ogham} \p{Script_Extensions=Ogham} (Short: \p{Sc=
Ogam}, \p{Ogam}) (29)
\p{Script: Ol_Chiki} \p{Script_Extensions=Ol_Chiki} (Short:
\p{Sc=Olck}, \p{Olck}) (48)
\p{Script: Olck} \p{Script=Ol_Chiki} (=
\p{Script_Extensions=Ol_Chiki}) (48)
\p{Script: Old_Hungarian} \p{Script_Extensions=Old_Hungarian}
(Short: \p{Sc=Hung}, \p{Hung}) (108)
\p{Script: Old_Italic} \p{Script_Extensions=Old_Italic} (Short:
\p{Sc=Ital}, \p{Ital}) (39)
\p{Script: Old_North_Arabian} \p{Script_Extensions=
Old_North_Arabian} (Short: \p{Sc=Narb},
\p{Narb}) (32)
\p{Script: Old_Permic} (Short: \p{Sc=Perm}) (43: U+10350..1037A)
\p{Script: Old_Persian} \p{Script_Extensions=Old_Persian} (Short:
\p{Sc=Xpeo}, \p{Xpeo}) (50)
\p{Script: Old_Sogdian} \p{Script_Extensions=Old_Sogdian} (Short:
\p{Sc=Sogo}, \p{Sogo}) (40)
\p{Script: Old_South_Arabian} \p{Script_Extensions=
Old_South_Arabian} (Short: \p{Sc=Sarb},
\p{Sarb}) (32)
\p{Script: Old_Turkic} \p{Script_Extensions=Old_Turkic} (Short:
\p{Sc=Orkh}, \p{Orkh}) (73)
\p{Script: Old_Uyghur} (Short: \p{Sc=Ougr}) (26: U+10F70..10F89)
\p{Script: Oriya} (Short: \p{Sc=Orya}) (91: U+0B01..0B03,
U+0B05..0B0C, U+0B0F..0B10,
U+0B13..0B28, U+0B2A..0B30, U+0B32..0B33
...)
\p{Script: Orkh} \p{Script=Old_Turkic} (=
\p{Script_Extensions=Old_Turkic}) (73)
\p{Script: Orya} \p{Script=Oriya} (91)
\p{Script: Osage} \p{Script_Extensions=Osage} (Short: \p{Sc=
Osge}, \p{Osge}) (72)
\p{Script: Osge} \p{Script=Osage} (= \p{Script_Extensions=
Osage}) (72)
\p{Script: Osma} \p{Script=Osmanya} (=
\p{Script_Extensions=Osmanya}) (40)
\p{Script: Osmanya} \p{Script_Extensions=Osmanya} (Short:
\p{Sc=Osma}, \p{Osma}) (40)
\p{Script: Ougr} \p{Script=Old_Uyghur} (26)
\p{Script: Pahawh_Hmong} \p{Script_Extensions=Pahawh_Hmong}
(Short: \p{Sc=Hmng}, \p{Hmng}) (127)
\p{Script: Palm} \p{Script=Palmyrene} (=
\p{Script_Extensions=Palmyrene}) (32)
\p{Script: Palmyrene} \p{Script_Extensions=Palmyrene} (Short:
\p{Sc=Palm}, \p{Palm}) (32)
\p{Script: Pau_Cin_Hau} \p{Script_Extensions=Pau_Cin_Hau} (Short:
\p{Sc=Pauc}, \p{Pauc}) (57)
\p{Script: Pauc} \p{Script=Pau_Cin_Hau} (=
\p{Script_Extensions=Pau_Cin_Hau}) (57)
\p{Script: Perm} \p{Script=Old_Permic} (43)
\p{Script: Phag} \p{Script=Phags_Pa} (56)
\p{Script: Phags_Pa} (Short: \p{Sc=Phag}) (56: U+A840..A877)
\p{Script: Phli} \p{Script=Inscriptional_Pahlavi} (=
\p{Script_Extensions=
Inscriptional_Pahlavi}) (27)
\p{Script: Phlp} \p{Script=Psalter_Pahlavi} (29)
\p{Script: Phnx} \p{Script=Phoenician} (=
\p{Script_Extensions=Phoenician}) (29)
\p{Script: Phoenician} \p{Script_Extensions=Phoenician} (Short:
\p{Sc=Phnx}, \p{Phnx}) (29)
\p{Script: Plrd} \p{Script=Miao} (= \p{Script_Extensions=
Miao}) (149)
\p{Script: Prti} \p{Script=Inscriptional_Parthian} (=
\p{Script_Extensions=
Inscriptional_Parthian}) (30)
\p{Script: Psalter_Pahlavi} (Short: \p{Sc=Phlp}) (29:
U+10B80..10B91, U+10B99..10B9C,
U+10BA9..10BAF)
\p{Script: Qaac} \p{Script=Coptic} (137)
\p{Script: Qaai} \p{Script=Inherited} (657)
\p{Script: Rejang} \p{Script_Extensions=Rejang} (Short:
\p{Sc=Rjng}, \p{Rjng}) (37)
\p{Script: Rjng} \p{Script=Rejang} (= \p{Script_Extensions=
Rejang}) (37)
\p{Script: Rohg} \p{Script=Hanifi_Rohingya} (50)
\p{Script: Runic} \p{Script_Extensions=Runic} (Short: \p{Sc=
Runr}, \p{Runr}) (86)
\p{Script: Runr} \p{Script=Runic} (= \p{Script_Extensions=
Runic}) (86)
\p{Script: Samaritan} \p{Script_Extensions=Samaritan} (Short:
\p{Sc=Samr}, \p{Samr}) (61)
\p{Script: Samr} \p{Script=Samaritan} (=
\p{Script_Extensions=Samaritan}) (61)
\p{Script: Sarb} \p{Script=Old_South_Arabian} (=
\p{Script_Extensions=Old_South_Arabian})
(32)
\p{Script: Saur} \p{Script=Saurashtra} (=
\p{Script_Extensions=Saurashtra}) (82)
\p{Script: Saurashtra} \p{Script_Extensions=Saurashtra} (Short:
\p{Sc=Saur}, \p{Saur}) (82)
\p{Script: Sgnw} \p{Script=SignWriting} (=
\p{Script_Extensions=SignWriting}) (672)
\p{Script: Sharada} (Short: \p{Sc=Shrd}) (96: U+11180..111DF)
\p{Script: Shavian} \p{Script_Extensions=Shavian} (Short:
\p{Sc=Shaw}, \p{Shaw}) (48)
\p{Script: Shaw} \p{Script=Shavian} (=
\p{Script_Extensions=Shavian}) (48)
\p{Script: Shrd} \p{Script=Sharada} (96)
\p{Script: Sidd} \p{Script=Siddham} (=
\p{Script_Extensions=Siddham}) (92)
\p{Script: Siddham} \p{Script_Extensions=Siddham} (Short:
\p{Sc=Sidd}, \p{Sidd}) (92)
\p{Script: SignWriting} \p{Script_Extensions=SignWriting} (Short:
\p{Sc=Sgnw}, \p{Sgnw}) (672)
\p{Script: Sind} \p{Script=Khudawadi} (69)
\p{Script: Sinh} \p{Script=Sinhala} (111)
\p{Script: Sinhala} (Short: \p{Sc=Sinh}) (111: U+0D81..0D83,
U+0D85..0D96, U+0D9A..0DB1,
U+0DB3..0DBB, U+0DBD, U+0DC0..0DC6 ...)
\p{Script: Sogd} \p{Script=Sogdian} (42)
\p{Script: Sogdian} (Short: \p{Sc=Sogd}) (42: U+10F30..10F59)
\p{Script: Sogo} \p{Script=Old_Sogdian} (=
\p{Script_Extensions=Old_Sogdian}) (40)
\p{Script: Sora} \p{Script=Sora_Sompeng} (=
\p{Script_Extensions=Sora_Sompeng}) (35)
\p{Script: Sora_Sompeng} \p{Script_Extensions=Sora_Sompeng}
(Short: \p{Sc=Sora}, \p{Sora}) (35)
\p{Script: Soyo} \p{Script=Soyombo} (=
\p{Script_Extensions=Soyombo}) (83)
\p{Script: Soyombo} \p{Script_Extensions=Soyombo} (Short:
\p{Sc=Soyo}, \p{Soyo}) (83)
\p{Script: Sund} \p{Script=Sundanese} (=
\p{Script_Extensions=Sundanese}) (72)
\p{Script: Sundanese} \p{Script_Extensions=Sundanese} (Short:
\p{Sc=Sund}, \p{Sund}) (72)
\p{Script: Sylo} \p{Script=Syloti_Nagri} (45)
\p{Script: Syloti_Nagri} (Short: \p{Sc=Sylo}) (45: U+A800..A82C)
\p{Script: Syrc} \p{Script=Syriac} (88)
\p{Script: Syriac} (Short: \p{Sc=Syrc}) (88: U+0700..070D,
U+070F..074A, U+074D..074F, U+0860..086A)
\p{Script: Tagalog} (Short: \p{Sc=Tglg}) (23: U+1700..1715,
U+171F)
\p{Script: Tagb} \p{Script=Tagbanwa} (18)
\p{Script: Tagbanwa} (Short: \p{Sc=Tagb}) (18: U+1760..176C,
U+176E..1770, U+1772..1773)
\p{Script: Tai_Le} (Short: \p{Sc=Tale}) (35: U+1950..196D,
U+1970..1974)
\p{Script: Tai_Tham} \p{Script_Extensions=Tai_Tham} (Short:
\p{Sc=Lana}, \p{Lana}) (127)
\p{Script: Tai_Viet} \p{Script_Extensions=Tai_Viet} (Short:
\p{Sc=Tavt}, \p{Tavt}) (72)
\p{Script: Takr} \p{Script=Takri} (68)
\p{Script: Takri} (Short: \p{Sc=Takr}) (68: U+11680..116B9,
U+116C0..116C9)
\p{Script: Tale} \p{Script=Tai_Le} (35)
\p{Script: Talu} \p{Script=New_Tai_Lue} (=
\p{Script_Extensions=New_Tai_Lue}) (83)
\p{Script: Tamil} (Short: \p{Sc=Taml}) (123: U+0B82..0B83,
U+0B85..0B8A, U+0B8E..0B90,
U+0B92..0B95, U+0B99..0B9A, U+0B9C ...)
\p{Script: Taml} \p{Script=Tamil} (123)
\p{Script: Tang} \p{Script=Tangut} (= \p{Script_Extensions=
Tangut}) (6914)
\p{Script: Tangsa} \p{Script_Extensions=Tangsa} (Short:
\p{Sc=Tnsa}, \p{Tnsa}) (89)
\p{Script: Tangut} \p{Script_Extensions=Tangut} (Short:
\p{Sc=Tang}, \p{Tang}) (6914)
\p{Script: Tavt} \p{Script=Tai_Viet} (=
\p{Script_Extensions=Tai_Viet}) (72)
\p{Script: Telu} \p{Script=Telugu} (100)
\p{Script: Telugu} (Short: \p{Sc=Telu}) (100: U+0C00..0C0C,
U+0C0E..0C10, U+0C12..0C28,
U+0C2A..0C39, U+0C3C..0C44, U+0C46..0C48
...)
\p{Script: Tfng} \p{Script=Tifinagh} (=
\p{Script_Extensions=Tifinagh}) (59)
\p{Script: Tglg} \p{Script=Tagalog} (23)
\p{Script: Thaa} \p{Script=Thaana} (50)
\p{Script: Thaana} (Short: \p{Sc=Thaa}) (50: U+0780..07B1)
\p{Script: Thai} \p{Script_Extensions=Thai} (Short: \p{Sc=
Thai}, \p{Thai}) (86)
\p{Script: Tibetan} \p{Script_Extensions=Tibetan} (Short:
\p{Sc=Tibt}, \p{Tibt}) (207)
\p{Script: Tibt} \p{Script=Tibetan} (=
\p{Script_Extensions=Tibetan}) (207)
\p{Script: Tifinagh} \p{Script_Extensions=Tifinagh} (Short:
\p{Sc=Tfng}, \p{Tfng}) (59)
\p{Script: Tirh} \p{Script=Tirhuta} (82)
\p{Script: Tirhuta} (Short: \p{Sc=Tirh}) (82: U+11480..114C7,
U+114D0..114D9)
\p{Script: Tnsa} \p{Script=Tangsa} (= \p{Script_Extensions=
Tangsa}) (89)
\p{Script: Toto} \p{Script_Extensions=Toto} (Short: \p{Sc=
Toto}, \p{Toto}) (31)
\p{Script: Ugar} \p{Script=Ugaritic} (=
\p{Script_Extensions=Ugaritic}) (31)
\p{Script: Ugaritic} \p{Script_Extensions=Ugaritic} (Short:
\p{Sc=Ugar}, \p{Ugar}) (31)
\p{Script: Unknown} \p{Script_Extensions=Unknown} (Short:
\p{Sc=Zzzz}, \p{Zzzz}) (969_350 plus all
above-Unicode code points)
\p{Script: Vai} \p{Script_Extensions=Vai} (Short: \p{Sc=
Vai}, \p{Vai}) (300)
\p{Script: Vaii} \p{Script=Vai} (= \p{Script_Extensions=
Vai}) (300)
\p{Script: Vith} \p{Script=Vithkuqi} (=
\p{Script_Extensions=Vithkuqi}) (70)
\p{Script: Vithkuqi} \p{Script_Extensions=Vithkuqi} (Short:
\p{Sc=Vith}, \p{Vith}) (70)
\p{Script: Wancho} \p{Script_Extensions=Wancho} (Short:
\p{Sc=Wcho}, \p{Wcho}) (59)
\p{Script: Wara} \p{Script=Warang_Citi} (=
\p{Script_Extensions=Warang_Citi}) (84)
\p{Script: Warang_Citi} \p{Script_Extensions=Warang_Citi} (Short:
\p{Sc=Wara}, \p{Wara}) (84)
\p{Script: Wcho} \p{Script=Wancho} (= \p{Script_Extensions=
Wancho}) (59)
\p{Script: Xpeo} \p{Script=Old_Persian} (=
\p{Script_Extensions=Old_Persian}) (50)
\p{Script: Xsux} \p{Script=Cuneiform} (=
\p{Script_Extensions=Cuneiform}) (1234)
\p{Script: Yezi} \p{Script=Yezidi} (47)
\p{Script: Yezidi} (Short: \p{Sc=Yezi}) (47: U+10E80..10EA9,
U+10EAB..10EAD, U+10EB0..10EB1)
\p{Script: Yi} (Short: \p{Sc=Yi}) (1220: U+A000..A48C,
U+A490..A4C6)
\p{Script: Yiii} \p{Script=Yi} (1220)
\p{Script: Zanabazar_Square} \p{Script_Extensions=
Zanabazar_Square} (Short: \p{Sc=Zanb},
\p{Zanb}) (72)
\p{Script: Zanb} \p{Script=Zanabazar_Square} (=
\p{Script_Extensions=Zanabazar_Square})
(72)
\p{Script: Zinh} \p{Script=Inherited} (657)
\p{Script: Zyyy} \p{Script=Common} (8252)
\p{Script: Zzzz} \p{Script=Unknown} (=
\p{Script_Extensions=Unknown}) (969_350
plus all above-Unicode code points)
\p{Script_Extensions: Adlam} (Short: \p{Scx=Adlm}, \p{Adlm}) (90:
U+061F, U+0640, U+1E900..1E94B,
U+1E950..1E959, U+1E95E..1E95F)
\p{Script_Extensions: Adlm} \p{Script_Extensions=Adlam} (90)
\p{Script_Extensions: Aghb} \p{Script_Extensions=
Caucasian_Albanian} (53)
\p{Script_Extensions: Ahom} (Short: \p{Scx=Ahom}, \p{Ahom}) (65:
U+11700..1171A, U+1171D..1172B,
U+11730..11746)
\p{Script_Extensions: Anatolian_Hieroglyphs} (Short: \p{Scx=Hluw},
\p{Hluw}) (583: U+14400..14646)
\p{Script_Extensions: Arab} \p{Script_Extensions=Arabic} (1411)
\p{Script_Extensions: Arabic} (Short: \p{Scx=Arab}, \p{Arab})
(1411: U+0600..0604, U+0606..06DC,
U+06DE..06FF, U+0750..077F,
U+0870..088E, U+0890..0891 ...)
\p{Script_Extensions: Armenian} (Short: \p{Scx=Armn}, \p{Armn})
(96: U+0531..0556, U+0559..058A,
U+058D..058F, U+FB13..FB17)
\p{Script_Extensions: Armi} \p{Script_Extensions=Imperial_Aramaic}
(31)
\p{Script_Extensions: Armn} \p{Script_Extensions=Armenian} (96)
\p{Script_Extensions: Avestan} (Short: \p{Scx=Avst}, \p{Avst})
(61: U+10B00..10B35, U+10B39..10B3F)
\p{Script_Extensions: Avst} \p{Script_Extensions=Avestan} (61)
\p{Script_Extensions: Bali} \p{Script_Extensions=Balinese} (124)
\p{Script_Extensions: Balinese} (Short: \p{Scx=Bali}, \p{Bali})
(124: U+1B00..1B4C, U+1B50..1B7E)
\p{Script_Extensions: Bamu} \p{Script_Extensions=Bamum} (657)
\p{Script_Extensions: Bamum} (Short: \p{Scx=Bamu}, \p{Bamu}) (657:
U+A6A0..A6F7, U+16800..16A38)
\p{Script_Extensions: Bass} \p{Script_Extensions=Bassa_Vah} (36)
\p{Script_Extensions: Bassa_Vah} (Short: \p{Scx=Bass}, \p{Bass})
(36: U+16AD0..16AED, U+16AF0..16AF5)
\p{Script_Extensions: Batak} (Short: \p{Scx=Batk}, \p{Batk}) (56:
U+1BC0..1BF3, U+1BFC..1BFF)
\p{Script_Extensions: Batk} \p{Script_Extensions=Batak} (56)
\p{Script_Extensions: Beng} \p{Script_Extensions=Bengali} (113)
\p{Script_Extensions: Bengali} (Short: \p{Scx=Beng}, \p{Beng})
(113: U+0951..0952, U+0964..0965,
U+0980..0983, U+0985..098C,
U+098F..0990, U+0993..09A8 ...)
\p{Script_Extensions: Bhaiksuki} (Short: \p{Scx=Bhks}, \p{Bhks})
(97: U+11C00..11C08, U+11C0A..11C36,
U+11C38..11C45, U+11C50..11C6C)
\p{Script_Extensions: Bhks} \p{Script_Extensions=Bhaiksuki} (97)
\p{Script_Extensions: Bopo} \p{Script_Extensions=Bopomofo} (117)
\p{Script_Extensions: Bopomofo} (Short: \p{Scx=Bopo}, \p{Bopo})
(117: U+02EA..02EB, U+3001..3003,
U+3008..3011, U+3013..301F,
U+302A..302D, U+3030 ...)
\p{Script_Extensions: Brah} \p{Script_Extensions=Brahmi} (115)
\p{Script_Extensions: Brahmi} (Short: \p{Scx=Brah}, \p{Brah})
(115: U+11000..1104D, U+11052..11075,
U+1107F)
\p{Script_Extensions: Brai} \p{Script_Extensions=Braille} (256)
\p{Script_Extensions: Braille} (Short: \p{Scx=Brai}, \p{Brai})
(256: U+2800..28FF)
\p{Script_Extensions: Bugi} \p{Script_Extensions=Buginese} (31)
\p{Script_Extensions: Buginese} (Short: \p{Scx=Bugi}, \p{Bugi})
(31: U+1A00..1A1B, U+1A1E..1A1F, U+A9CF)
\p{Script_Extensions: Buhd} \p{Script_Extensions=Buhid} (22)
\p{Script_Extensions: Buhid} (Short: \p{Scx=Buhd}, \p{Buhd}) (22:
U+1735..1736, U+1740..1753)
\p{Script_Extensions: Cakm} \p{Script_Extensions=Chakma} (91)
\p{Script_Extensions: Canadian_Aboriginal} (Short: \p{Scx=Cans},
\p{Cans}) (726: U+1400..167F,
U+18B0..18F5, U+11AB0..11ABF)
\p{Script_Extensions: Cans} \p{Script_Extensions=
Canadian_Aboriginal} (726)
\p{Script_Extensions: Cari} \p{Script_Extensions=Carian} (49)
\p{Script_Extensions: Carian} (Short: \p{Scx=Cari}, \p{Cari}) (49:
U+102A0..102D0)
\p{Script_Extensions: Caucasian_Albanian} (Short: \p{Scx=Aghb},
\p{Aghb}) (53: U+10530..10563, U+1056F)
\p{Script_Extensions: Chakma} (Short: \p{Scx=Cakm}, \p{Cakm}) (91:
U+09E6..09EF, U+1040..1049,
U+11100..11134, U+11136..11147)
\p{Script_Extensions: Cham} (Short: \p{Scx=Cham}, \p{Cham}) (83:
U+AA00..AA36, U+AA40..AA4D,
U+AA50..AA59, U+AA5C..AA5F)
\p{Script_Extensions: Cher} \p{Script_Extensions=Cherokee} (172)
\p{Script_Extensions: Cherokee} (Short: \p{Scx=Cher}, \p{Cher})
(172: U+13A0..13F5, U+13F8..13FD,
U+AB70..ABBF)
\p{Script_Extensions: Chorasmian} (Short: \p{Scx=Chrs}, \p{Chrs})
(28: U+10FB0..10FCB)
\p{Script_Extensions: Chrs} \p{Script_Extensions=Chorasmian} (28)
\p{Script_Extensions: Common} (Short: \p{Scx=Zyyy}, \p{Zyyy})
(7824: [\x00-\x20!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@\[\\\]\^_`\{\|\}~\x7f-\xa9
\xab-\xb9\xbb-\xbf\xd7\xf7],
U+02B9..02DF, U+02E5..02E9,
U+02EC..02FF, U+0374, U+037E ...)
\p{Script_Extensions: Copt} \p{Script_Extensions=Coptic} (165)
\p{Script_Extensions: Coptic} (Short: \p{Scx=Copt}, \p{Copt})
(165: U+03E2..03EF, U+2C80..2CF3,
U+2CF9..2CFF, U+102E0..102FB)
\p{Script_Extensions: Cpmn} \p{Script_Extensions=Cypro_Minoan}
(101)
\p{Script_Extensions: Cprt} \p{Script_Extensions=Cypriot} (112)
\p{Script_Extensions: Cuneiform} (Short: \p{Scx=Xsux}, \p{Xsux})
(1234: U+12000..12399, U+12400..1246E,
U+12470..12474, U+12480..12543)
\p{Script_Extensions: Cypriot} (Short: \p{Scx=Cprt}, \p{Cprt})
(112: U+10100..10102, U+10107..10133,
U+10137..1013F, U+10800..10805, U+10808,
U+1080A..10835 ...)
\p{Script_Extensions: Cypro_Minoan} (Short: \p{Scx=Cpmn},
\p{Cpmn}) (101: U+10100..10101,
U+12F90..12FF2)
\p{Script_Extensions: Cyrillic} (Short: \p{Scx=Cyrl}, \p{Cyrl})
(447: U+0400..052F, U+1C80..1C88,
U+1D2B, U+1D78, U+1DF8, U+2DE0..2DFF ...)
\p{Script_Extensions: Cyrl} \p{Script_Extensions=Cyrillic} (447)
\p{Script_Extensions: Deseret} (Short: \p{Scx=Dsrt}, \p{Dsrt})
(80: U+10400..1044F)
\p{Script_Extensions: Deva} \p{Script_Extensions=Devanagari} (210)
\p{Script_Extensions: Devanagari} (Short: \p{Scx=Deva}, \p{Deva})
(210: U+0900..0952, U+0955..097F,
U+1CD0..1CF6, U+1CF8..1CF9, U+20F0,
U+A830..A839 ...)
\p{Script_Extensions: Diak} \p{Script_Extensions=Dives_Akuru} (72)
\p{Script_Extensions: Dives_Akuru} (Short: \p{Scx=Diak}, \p{Diak})
(72: U+11900..11906, U+11909,
U+1190C..11913, U+11915..11916,
U+11918..11935, U+11937..11938 ...)
\p{Script_Extensions: Dogr} \p{Script_Extensions=Dogra} (82)
\p{Script_Extensions: Dogra} (Short: \p{Scx=Dogr}, \p{Dogr}) (82:
U+0964..096F, U+A830..A839,
U+11800..1183B)
\p{Script_Extensions: Dsrt} \p{Script_Extensions=Deseret} (80)
\p{Script_Extensions: Dupl} \p{Script_Extensions=Duployan} (147)
\p{Script_Extensions: Duployan} (Short: \p{Scx=Dupl}, \p{Dupl})
(147: U+1BC00..1BC6A, U+1BC70..1BC7C,
U+1BC80..1BC88, U+1BC90..1BC99,
U+1BC9C..1BCA3)
\p{Script_Extensions: Egyp} \p{Script_Extensions=
Egyptian_Hieroglyphs} (1080)
\p{Script_Extensions: Egyptian_Hieroglyphs} (Short: \p{Scx=Egyp},
\p{Egyp}) (1080: U+13000..1342E,
U+13430..13438)
\p{Script_Extensions: Elba} \p{Script_Extensions=Elbasan} (40)
\p{Script_Extensions: Elbasan} (Short: \p{Scx=Elba}, \p{Elba})
(40: U+10500..10527)
\p{Script_Extensions: Elym} \p{Script_Extensions=Elymaic} (23)
\p{Script_Extensions: Elymaic} (Short: \p{Scx=Elym}, \p{Elym})
(23: U+10FE0..10FF6)
\p{Script_Extensions: Ethi} \p{Script_Extensions=Ethiopic} (523)
\p{Script_Extensions: Ethiopic} (Short: \p{Scx=Ethi}, \p{Ethi})
(523: U+1200..1248, U+124A..124D,
U+1250..1256, U+1258, U+125A..125D,
U+1260..1288 ...)
\p{Script_Extensions: Geor} \p{Script_Extensions=Georgian} (174)
\p{Script_Extensions: Georgian} (Short: \p{Scx=Geor}, \p{Geor})
(174: U+10A0..10C5, U+10C7, U+10CD,
U+10D0..10FF, U+1C90..1CBA, U+1CBD..1CBF
...)
\p{Script_Extensions: Glag} \p{Script_Extensions=Glagolitic} (138)
\p{Script_Extensions: Glagolitic} (Short: \p{Scx=Glag}, \p{Glag})
(138: U+0484, U+0487, U+2C00..2C5F,
U+2E43, U+A66F, U+1E000..1E006 ...)
\p{Script_Extensions: Gong} \p{Script_Extensions=Gunjala_Gondi}
(65)
\p{Script_Extensions: Gonm} \p{Script_Extensions=Masaram_Gondi}
(77)
\p{Script_Extensions: Goth} \p{Script_Extensions=Gothic} (27)
\p{Script_Extensions: Gothic} (Short: \p{Scx=Goth}, \p{Goth}) (27:
U+10330..1034A)
\p{Script_Extensions: Gran} \p{Script_Extensions=Grantha} (116)
\p{Script_Extensions: Grantha} (Short: \p{Scx=Gran}, \p{Gran})
(116: U+0951..0952, U+0964..0965,
U+0BE6..0BF3, U+1CD0, U+1CD2..1CD3,
U+1CF2..1CF4 ...)
\p{Script_Extensions: Greek} (Short: \p{Scx=Grek}, \p{Grek}) (522:
U+0342, U+0345, U+0370..0373,
U+0375..0377, U+037A..037D, U+037F ...)
\p{Script_Extensions: Grek} \p{Script_Extensions=Greek} (522)
\p{Script_Extensions: Gujarati} (Short: \p{Scx=Gujr}, \p{Gujr})
(105: U+0951..0952, U+0964..0965,
U+0A81..0A83, U+0A85..0A8D,
U+0A8F..0A91, U+0A93..0AA8 ...)
\p{Script_Extensions: Gujr} \p{Script_Extensions=Gujarati} (105)
\p{Script_Extensions: Gunjala_Gondi} (Short: \p{Scx=Gong},
\p{Gong}) (65: U+0964..0965,
U+11D60..11D65, U+11D67..11D68,
U+11D6A..11D8E, U+11D90..11D91,
U+11D93..11D98 ...)
\p{Script_Extensions: Gurmukhi} (Short: \p{Scx=Guru}, \p{Guru})
(94: U+0951..0952, U+0964..0965,
U+0A01..0A03, U+0A05..0A0A,
U+0A0F..0A10, U+0A13..0A28 ...)
\p{Script_Extensions: Guru} \p{Script_Extensions=Gurmukhi} (94)
\p{Script_Extensions: Han} (Short: \p{Scx=Han}, \p{Han}) (94_503:
U+2E80..2E99, U+2E9B..2EF3,
U+2F00..2FD5, U+3001..3003,
U+3005..3011, U+3013..301F ...)
\p{Script_Extensions: Hang} \p{Script_Extensions=Hangul} (11_775)
\p{Script_Extensions: Hangul} (Short: \p{Scx=Hang}, \p{Hang})
(11_775: U+1100..11FF, U+3001..3003,
U+3008..3011, U+3013..301F,
U+302E..3030, U+3037 ...)
\p{Script_Extensions: Hani} \p{Script_Extensions=Han} (94_503)
\p{Script_Extensions: Hanifi_Rohingya} (Short: \p{Scx=Rohg},
\p{Rohg}) (55: U+060C, U+061B, U+061F,
U+0640, U+06D4, U+10D00..10D27 ...)
\p{Script_Extensions: Hano} \p{Script_Extensions=Hanunoo} (23)
\p{Script_Extensions: Hanunoo} (Short: \p{Scx=Hano}, \p{Hano})
(23: U+1720..1736)
\p{Script_Extensions: Hatr} \p{Script_Extensions=Hatran} (26)
\p{Script_Extensions: Hatran} (Short: \p{Scx=Hatr}, \p{Hatr}) (26:
U+108E0..108F2, U+108F4..108F5,
U+108FB..108FF)
\p{Script_Extensions: Hebr} \p{Script_Extensions=Hebrew} (134)
\p{Script_Extensions: Hebrew} (Short: \p{Scx=Hebr}, \p{Hebr})
(134: U+0591..05C7, U+05D0..05EA,
U+05EF..05F4, U+FB1D..FB36,
U+FB38..FB3C, U+FB3E ...)
\p{Script_Extensions: Hira} \p{Script_Extensions=Hiragana} (432)
\p{Script_Extensions: Hiragana} (Short: \p{Scx=Hira}, \p{Hira})
(432: U+3001..3003, U+3008..3011,
U+3013..301F, U+3030..3035, U+3037,
U+303C..303D ...)
\p{Script_Extensions: Hluw} \p{Script_Extensions=
Anatolian_Hieroglyphs} (583)
\p{Script_Extensions: Hmng} \p{Script_Extensions=Pahawh_Hmong}
(127)
\p{Script_Extensions: Hmnp} \p{Script_Extensions=
Nyiakeng_Puachue_Hmong} (71)
\p{Script_Extensions: Hung} \p{Script_Extensions=Old_Hungarian}
(108)
\p{Script_Extensions: Imperial_Aramaic} (Short: \p{Scx=Armi},
\p{Armi}) (31: U+10840..10855,
U+10857..1085F)
\p{Script_Extensions: Inherited} (Short: \p{Scx=Zinh}, \p{Zinh})
(586: U+0300..0341, U+0343..0344,
U+0346..0362, U+0953..0954,
U+1AB0..1ACE, U+1DC2..1DF7 ...)
\p{Script_Extensions: Inscriptional_Pahlavi} (Short: \p{Scx=Phli},
\p{Phli}) (27: U+10B60..10B72,
U+10B78..10B7F)
\p{Script_Extensions: Inscriptional_Parthian} (Short: \p{Scx=
Prti}, \p{Prti}) (30: U+10B40..10B55,
U+10B58..10B5F)
\p{Script_Extensions: Ital} \p{Script_Extensions=Old_Italic} (39)
\p{Script_Extensions: Java} \p{Script_Extensions=Javanese} (91)
\p{Script_Extensions: Javanese} (Short: \p{Scx=Java}, \p{Java})
(91: U+A980..A9CD, U+A9CF..A9D9,
U+A9DE..A9DF)
\p{Script_Extensions: Kaithi} (Short: \p{Scx=Kthi}, \p{Kthi}) (88:
U+0966..096F, U+A830..A839,
U+11080..110C2, U+110CD)
\p{Script_Extensions: Kali} \p{Script_Extensions=Kayah_Li} (48)
\p{Script_Extensions: Kana} \p{Script_Extensions=Katakana} (372)
\p{Script_Extensions: Kannada} (Short: \p{Scx=Knda}, \p{Knda})
(105: U+0951..0952, U+0964..0965,
U+0C80..0C8C, U+0C8E..0C90,
U+0C92..0CA8, U+0CAA..0CB3 ...)
\p{Script_Extensions: Katakana} (Short: \p{Scx=Kana}, \p{Kana})
(372: U+3001..3003, U+3008..3011,
U+3013..301F, U+3030..3035, U+3037,
U+303C..303D ...)
\p{Script_Extensions: Kayah_Li} (Short: \p{Scx=Kali}, \p{Kali})
(48: U+A900..A92F)
\p{Script_Extensions: Khar} \p{Script_Extensions=Kharoshthi} (68)
\p{Script_Extensions: Kharoshthi} (Short: \p{Scx=Khar}, \p{Khar})
(68: U+10A00..10A03, U+10A05..10A06,
U+10A0C..10A13, U+10A15..10A17,
U+10A19..10A35, U+10A38..10A3A ...)
\p{Script_Extensions: Khitan_Small_Script} (Short: \p{Scx=Kits},
\p{Kits}) (471: U+16FE4, U+18B00..18CD5)
\p{Script_Extensions: Khmer} (Short: \p{Scx=Khmr}, \p{Khmr}) (146:
U+1780..17DD, U+17E0..17E9,
U+17F0..17F9, U+19E0..19FF)
\p{Script_Extensions: Khmr} \p{Script_Extensions=Khmer} (146)
\p{Script_Extensions: Khoj} \p{Script_Extensions=Khojki} (82)
\p{Script_Extensions: Khojki} (Short: \p{Scx=Khoj}, \p{Khoj}) (82:
U+0AE6..0AEF, U+A830..A839,
U+11200..11211, U+11213..1123E)
\p{Script_Extensions: Khudawadi} (Short: \p{Scx=Sind}, \p{Sind})
(81: U+0964..0965, U+A830..A839,
U+112B0..112EA, U+112F0..112F9)
\p{Script_Extensions: Kits} \p{Script_Extensions=
Khitan_Small_Script} (471)
\p{Script_Extensions: Knda} \p{Script_Extensions=Kannada} (105)
\p{Script_Extensions: Kthi} \p{Script_Extensions=Kaithi} (88)
\p{Script_Extensions: Lana} \p{Script_Extensions=Tai_Tham} (127)
\p{Script_Extensions: Lao} (Short: \p{Scx=Lao}, \p{Lao}) (82:
U+0E81..0E82, U+0E84, U+0E86..0E8A,
U+0E8C..0EA3, U+0EA5, U+0EA7..0EBD ...)
\p{Script_Extensions: Laoo} \p{Script_Extensions=Lao} (82)
\p{Script_Extensions: Latin} (Short: \p{Scx=Latn}, \p{Latn})
(1504: [A-Za-z\xaa\xba\xc0-\xd6\xd8-
\xf6\xf8-\xff], U+0100..02B8,
U+02E0..02E4, U+0363..036F,
U+0485..0486, U+0951..0952 ...)
\p{Script_Extensions: Latn} \p{Script_Extensions=Latin} (1504)
\p{Script_Extensions: Lepc} \p{Script_Extensions=Lepcha} (74)
\p{Script_Extensions: Lepcha} (Short: \p{Scx=Lepc}, \p{Lepc}) (74:
U+1C00..1C37, U+1C3B..1C49, U+1C4D..1C4F)
\p{Script_Extensions: Limb} \p{Script_Extensions=Limbu} (69)
\p{Script_Extensions: Limbu} (Short: \p{Scx=Limb}, \p{Limb}) (69:
U+0965, U+1900..191E, U+1920..192B,
U+1930..193B, U+1940, U+1944..194F)
\p{Script_Extensions: Lina} \p{Script_Extensions=Linear_A} (386)
\p{Script_Extensions: Linb} \p{Script_Extensions=Linear_B} (268)
\p{Script_Extensions: Linear_A} (Short: \p{Scx=Lina}, \p{Lina})
(386: U+10107..10133, U+10600..10736,
U+10740..10755, U+10760..10767)
\p{Script_Extensions: Linear_B} (Short: \p{Scx=Linb}, \p{Linb})
(268: U+10000..1000B, U+1000D..10026,
U+10028..1003A, U+1003C..1003D,
U+1003F..1004D, U+10050..1005D ...)
\p{Script_Extensions: Lisu} (Short: \p{Scx=Lisu}, \p{Lisu}) (49:
U+A4D0..A4FF, U+11FB0)
\p{Script_Extensions: Lyci} \p{Script_Extensions=Lycian} (29)
\p{Script_Extensions: Lycian} (Short: \p{Scx=Lyci}, \p{Lyci}) (29:
U+10280..1029C)
\p{Script_Extensions: Lydi} \p{Script_Extensions=Lydian} (27)
\p{Script_Extensions: Lydian} (Short: \p{Scx=Lydi}, \p{Lydi}) (27:
U+10920..10939, U+1093F)
\p{Script_Extensions: Mahajani} (Short: \p{Scx=Mahj}, \p{Mahj})
(61: U+0964..096F, U+A830..A839,
U+11150..11176)
\p{Script_Extensions: Mahj} \p{Script_Extensions=Mahajani} (61)
\p{Script_Extensions: Maka} \p{Script_Extensions=Makasar} (25)
\p{Script_Extensions: Makasar} (Short: \p{Scx=Maka}, \p{Maka})
(25: U+11EE0..11EF8)
\p{Script_Extensions: Malayalam} (Short: \p{Scx=Mlym}, \p{Mlym})
(126: U+0951..0952, U+0964..0965,
U+0D00..0D0C, U+0D0E..0D10,
U+0D12..0D44, U+0D46..0D48 ...)
\p{Script_Extensions: Mand} \p{Script_Extensions=Mandaic} (30)
\p{Script_Extensions: Mandaic} (Short: \p{Scx=Mand}, \p{Mand})
(30: U+0640, U+0840..085B, U+085E)
\p{Script_Extensions: Mani} \p{Script_Extensions=Manichaean} (52)
\p{Script_Extensions: Manichaean} (Short: \p{Scx=Mani}, \p{Mani})
(52: U+0640, U+10AC0..10AE6,
U+10AEB..10AF6)
\p{Script_Extensions: Marc} \p{Script_Extensions=Marchen} (68)
\p{Script_Extensions: Marchen} (Short: \p{Scx=Marc}, \p{Marc})
(68: U+11C70..11C8F, U+11C92..11CA7,
U+11CA9..11CB6)
\p{Script_Extensions: Masaram_Gondi} (Short: \p{Scx=Gonm},
\p{Gonm}) (77: U+0964..0965,
U+11D00..11D06, U+11D08..11D09,
U+11D0B..11D36, U+11D3A, U+11D3C..11D3D
...)
\p{Script_Extensions: Medefaidrin} (Short: \p{Scx=Medf}, \p{Medf})
(91: U+16E40..16E9A)
\p{Script_Extensions: Medf} \p{Script_Extensions=Medefaidrin} (91)
\p{Script_Extensions: Meetei_Mayek} (Short: \p{Scx=Mtei},
\p{Mtei}) (79: U+AAE0..AAF6,
U+ABC0..ABED, U+ABF0..ABF9)
\p{Script_Extensions: Mend} \p{Script_Extensions=Mende_Kikakui}
(213)
\p{Script_Extensions: Mende_Kikakui} (Short: \p{Scx=Mend},
\p{Mend}) (213: U+1E800..1E8C4,
U+1E8C7..1E8D6)
\p{Script_Extensions: Merc} \p{Script_Extensions=Meroitic_Cursive}
(90)
\p{Script_Extensions: Mero} \p{Script_Extensions=
Meroitic_Hieroglyphs} (32)
\p{Script_Extensions: Meroitic_Cursive} (Short: \p{Scx=Merc},
\p{Merc}) (90: U+109A0..109B7,
U+109BC..109CF, U+109D2..109FF)
\p{Script_Extensions: Meroitic_Hieroglyphs} (Short: \p{Scx=Mero},
\p{Mero}) (32: U+10980..1099F)
\p{Script_Extensions: Miao} (Short: \p{Scx=Miao}, \p{Miao}) (149:
U+16F00..16F4A, U+16F4F..16F87,
U+16F8F..16F9F)
\p{Script_Extensions: Mlym} \p{Script_Extensions=Malayalam} (126)
\p{Script_Extensions: Modi} (Short: \p{Scx=Modi}, \p{Modi}) (89:
U+A830..A839, U+11600..11644,
U+11650..11659)
\p{Script_Extensions: Mong} \p{Script_Extensions=Mongolian} (172)
\p{Script_Extensions: Mongolian} (Short: \p{Scx=Mong}, \p{Mong})
(172: U+1800..1819, U+1820..1878,
U+1880..18AA, U+202F, U+11660..1166C)
\p{Script_Extensions: Mro} (Short: \p{Scx=Mro}, \p{Mro}) (43:
U+16A40..16A5E, U+16A60..16A69,
U+16A6E..16A6F)
\p{Script_Extensions: Mroo} \p{Script_Extensions=Mro} (43)
\p{Script_Extensions: Mtei} \p{Script_Extensions=Meetei_Mayek} (79)
\p{Script_Extensions: Mult} \p{Script_Extensions=Multani} (48)
\p{Script_Extensions: Multani} (Short: \p{Scx=Mult}, \p{Mult})
(48: U+0A66..0A6F, U+11280..11286,
U+11288, U+1128A..1128D, U+1128F..1129D,
U+1129F..112A9)
\p{Script_Extensions: Myanmar} (Short: \p{Scx=Mymr}, \p{Mymr})
(224: U+1000..109F, U+A92E,
U+A9E0..A9FE, U+AA60..AA7F)
\p{Script_Extensions: Mymr} \p{Script_Extensions=Myanmar} (224)
\p{Script_Extensions: Nabataean} (Short: \p{Scx=Nbat}, \p{Nbat})
(40: U+10880..1089E, U+108A7..108AF)
\p{Script_Extensions: Nand} \p{Script_Extensions=Nandinagari} (86)
\p{Script_Extensions: Nandinagari} (Short: \p{Scx=Nand}, \p{Nand})
(86: U+0964..0965, U+0CE6..0CEF, U+1CE9,
U+1CF2, U+1CFA, U+A830..A835 ...)
\p{Script_Extensions: Narb} \p{Script_Extensions=
Old_North_Arabian} (32)
\p{Script_Extensions: Nbat} \p{Script_Extensions=Nabataean} (40)
\p{Script_Extensions: New_Tai_Lue} (Short: \p{Scx=Talu}, \p{Talu})
(83: U+1980..19AB, U+19B0..19C9,
U+19D0..19DA, U+19DE..19DF)
\p{Script_Extensions: Newa} (Short: \p{Scx=Newa}, \p{Newa}) (97:
U+11400..1145B, U+1145D..11461)
\p{Script_Extensions: Nko} (Short: \p{Scx=Nko}, \p{Nko}) (67:
U+060C, U+061B, U+061F, U+07C0..07FA,
U+07FD..07FF, U+FD3E..FD3F)
\p{Script_Extensions: Nkoo} \p{Script_Extensions=Nko} (67)
\p{Script_Extensions: Nshu} \p{Script_Extensions=Nushu} (397)
\p{Script_Extensions: Nushu} (Short: \p{Scx=Nshu}, \p{Nshu}) (397:
U+16FE1, U+1B170..1B2FB)
\p{Script_Extensions: Nyiakeng_Puachue_Hmong} (Short: \p{Scx=
Hmnp}, \p{Hmnp}) (71: U+1E100..1E12C,
U+1E130..1E13D, U+1E140..1E149,
U+1E14E..1E14F)
\p{Script_Extensions: Ogam} \p{Script_Extensions=Ogham} (29)
\p{Script_Extensions: Ogham} (Short: \p{Scx=Ogam}, \p{Ogam}) (29:
U+1680..169C)
\p{Script_Extensions: Ol_Chiki} (Short: \p{Scx=Olck}, \p{Olck})
(48: U+1C50..1C7F)
\p{Script_Extensions: Olck} \p{Script_Extensions=Ol_Chiki} (48)
\p{Script_Extensions: Old_Hungarian} (Short: \p{Scx=Hung},
\p{Hung}) (108: U+10C80..10CB2,
U+10CC0..10CF2, U+10CFA..10CFF)
\p{Script_Extensions: Old_Italic} (Short: \p{Scx=Ital}, \p{Ital})
(39: U+10300..10323, U+1032D..1032F)
\p{Script_Extensions: Old_North_Arabian} (Short: \p{Scx=Narb},
\p{Narb}) (32: U+10A80..10A9F)
\p{Script_Extensions: Old_Permic} (Short: \p{Scx=Perm}, \p{Perm})
(44: U+0483, U+10350..1037A)
\p{Script_Extensions: Old_Persian} (Short: \p{Scx=Xpeo}, \p{Xpeo})
(50: U+103A0..103C3, U+103C8..103D5)
\p{Script_Extensions: Old_Sogdian} (Short: \p{Scx=Sogo}, \p{Sogo})
(40: U+10F00..10F27)
\p{Script_Extensions: Old_South_Arabian} (Short: \p{Scx=Sarb},
\p{Sarb}) (32: U+10A60..10A7F)
\p{Script_Extensions: Old_Turkic} (Short: \p{Scx=Orkh}, \p{Orkh})
(73: U+10C00..10C48)
\p{Script_Extensions: Old_Uyghur} (Short: \p{Scx=Ougr}, \p{Ougr})
(28: U+0640, U+10AF2, U+10F70..10F89)
\p{Script_Extensions: Oriya} (Short: \p{Scx=Orya}, \p{Orya}) (97:
U+0951..0952, U+0964..0965,
U+0B01..0B03, U+0B05..0B0C,
U+0B0F..0B10, U+0B13..0B28 ...)
\p{Script_Extensions: Orkh} \p{Script_Extensions=Old_Turkic} (73)
\p{Script_Extensions: Orya} \p{Script_Extensions=Oriya} (97)
\p{Script_Extensions: Osage} (Short: \p{Scx=Osge}, \p{Osge}) (72:
U+104B0..104D3, U+104D8..104FB)
\p{Script_Extensions: Osge} \p{Script_Extensions=Osage} (72)
\p{Script_Extensions: Osma} \p{Script_Extensions=Osmanya} (40)
\p{Script_Extensions: Osmanya} (Short: \p{Scx=Osma}, \p{Osma})
(40: U+10480..1049D, U+104A0..104A9)
\p{Script_Extensions: Ougr} \p{Script_Extensions=Old_Uyghur} (28)
\p{Script_Extensions: Pahawh_Hmong} (Short: \p{Scx=Hmng},
\p{Hmng}) (127: U+16B00..16B45,
U+16B50..16B59, U+16B5B..16B61,
U+16B63..16B77, U+16B7D..16B8F)
\p{Script_Extensions: Palm} \p{Script_Extensions=Palmyrene} (32)
\p{Script_Extensions: Palmyrene} (Short: \p{Scx=Palm}, \p{Palm})
(32: U+10860..1087F)
\p{Script_Extensions: Pau_Cin_Hau} (Short: \p{Scx=Pauc}, \p{Pauc})
(57: U+11AC0..11AF8)
\p{Script_Extensions: Pauc} \p{Script_Extensions=Pau_Cin_Hau} (57)
\p{Script_Extensions: Perm} \p{Script_Extensions=Old_Permic} (44)
\p{Script_Extensions: Phag} \p{Script_Extensions=Phags_Pa} (59)
\p{Script_Extensions: Phags_Pa} (Short: \p{Scx=Phag}, \p{Phag})
(59: U+1802..1803, U+1805, U+A840..A877)
\p{Script_Extensions: Phli} \p{Script_Extensions=
Inscriptional_Pahlavi} (27)
\p{Script_Extensions: Phlp} \p{Script_Extensions=Psalter_Pahlavi}
(30)
\p{Script_Extensions: Phnx} \p{Script_Extensions=Phoenician} (29)
\p{Script_Extensions: Phoenician} (Short: \p{Scx=Phnx}, \p{Phnx})
(29: U+10900..1091B, U+1091F)
\p{Script_Extensions: Plrd} \p{Script_Extensions=Miao} (149)
\p{Script_Extensions: Prti} \p{Script_Extensions=
Inscriptional_Parthian} (30)
\p{Script_Extensions: Psalter_Pahlavi} (Short: \p{Scx=Phlp},
\p{Phlp}) (30: U+0640, U+10B80..10B91,
U+10B99..10B9C, U+10BA9..10BAF)
\p{Script_Extensions: Qaac} \p{Script_Extensions=Coptic} (165)
\p{Script_Extensions: Qaai} \p{Script_Extensions=Inherited} (586)
\p{Script_Extensions: Rejang} (Short: \p{Scx=Rjng}, \p{Rjng}) (37:
U+A930..A953, U+A95F)
\p{Script_Extensions: Rjng} \p{Script_Extensions=Rejang} (37)
\p{Script_Extensions: Rohg} \p{Script_Extensions=Hanifi_Rohingya}
(55)
\p{Script_Extensions: Runic} (Short: \p{Scx=Runr}, \p{Runr}) (86:
U+16A0..16EA, U+16EE..16F8)
\p{Script_Extensions: Runr} \p{Script_Extensions=Runic} (86)
\p{Script_Extensions: Samaritan} (Short: \p{Scx=Samr}, \p{Samr})
(61: U+0800..082D, U+0830..083E)
\p{Script_Extensions: Samr} \p{Script_Extensions=Samaritan} (61)
\p{Script_Extensions: Sarb} \p{Script_Extensions=
Old_South_Arabian} (32)
\p{Script_Extensions: Saur} \p{Script_Extensions=Saurashtra} (82)
\p{Script_Extensions: Saurashtra} (Short: \p{Scx=Saur}, \p{Saur})
(82: U+A880..A8C5, U+A8CE..A8D9)
\p{Script_Extensions: Sgnw} \p{Script_Extensions=SignWriting} (672)
\p{Script_Extensions: Sharada} (Short: \p{Scx=Shrd}, \p{Shrd})
(102: U+0951, U+1CD7, U+1CD9,
U+1CDC..1CDD, U+1CE0, U+11180..111DF)
\p{Script_Extensions: Shavian} (Short: \p{Scx=Shaw}, \p{Shaw})
(48: U+10450..1047F)
\p{Script_Extensions: Shaw} \p{Script_Extensions=Shavian} (48)
\p{Script_Extensions: Shrd} \p{Script_Extensions=Sharada} (102)
\p{Script_Extensions: Sidd} \p{Script_Extensions=Siddham} (92)
\p{Script_Extensions: Siddham} (Short: \p{Scx=Sidd}, \p{Sidd})
(92: U+11580..115B5, U+115B8..115DD)
\p{Script_Extensions: SignWriting} (Short: \p{Scx=Sgnw}, \p{Sgnw})
(672: U+1D800..1DA8B, U+1DA9B..1DA9F,
U+1DAA1..1DAAF)
\p{Script_Extensions: Sind} \p{Script_Extensions=Khudawadi} (81)
\p{Script_Extensions: Sinh} \p{Script_Extensions=Sinhala} (113)
\p{Script_Extensions: Sinhala} (Short: \p{Scx=Sinh}, \p{Sinh})
(113: U+0964..0965, U+0D81..0D83,
U+0D85..0D96, U+0D9A..0DB1,
U+0DB3..0DBB, U+0DBD ...)
\p{Script_Extensions: Sogd} \p{Script_Extensions=Sogdian} (43)
\p{Script_Extensions: Sogdian} (Short: \p{Scx=Sogd}, \p{Sogd})
(43: U+0640, U+10F30..10F59)
\p{Script_Extensions: Sogo} \p{Script_Extensions=Old_Sogdian} (40)
\p{Script_Extensions: Sora} \p{Script_Extensions=Sora_Sompeng} (35)
\p{Script_Extensions: Sora_Sompeng} (Short: \p{Scx=Sora},
\p{Sora}) (35: U+110D0..110E8,
U+110F0..110F9)
\p{Script_Extensions: Soyo} \p{Script_Extensions=Soyombo} (83)
\p{Script_Extensions: Soyombo} (Short: \p{Scx=Soyo}, \p{Soyo})
(83: U+11A50..11AA2)
\p{Script_Extensions: Sund} \p{Script_Extensions=Sundanese} (72)
\p{Script_Extensions: Sundanese} (Short: \p{Scx=Sund}, \p{Sund})
(72: U+1B80..1BBF, U+1CC0..1CC7)
\p{Script_Extensions: Sylo} \p{Script_Extensions=Syloti_Nagri} (57)
\p{Script_Extensions: Syloti_Nagri} (Short: \p{Scx=Sylo},
\p{Sylo}) (57: U+0964..0965,
U+09E6..09EF, U+A800..A82C)
\p{Script_Extensions: Syrc} \p{Script_Extensions=Syriac} (107)
\p{Script_Extensions: Syriac} (Short: \p{Scx=Syrc}, \p{Syrc})
(107: U+060C, U+061B..061C, U+061F,
U+0640, U+064B..0655, U+0670 ...)
\p{Script_Extensions: Tagalog} (Short: \p{Scx=Tglg}, \p{Tglg})
(25: U+1700..1715, U+171F, U+1735..1736)
\p{Script_Extensions: Tagb} \p{Script_Extensions=Tagbanwa} (20)
\p{Script_Extensions: Tagbanwa} (Short: \p{Scx=Tagb}, \p{Tagb})
(20: U+1735..1736, U+1760..176C,
U+176E..1770, U+1772..1773)
\p{Script_Extensions: Tai_Le} (Short: \p{Scx=Tale}, \p{Tale}) (45:
U+1040..1049, U+1950..196D, U+1970..1974)
\p{Script_Extensions: Tai_Tham} (Short: \p{Scx=Lana}, \p{Lana})
(127: U+1A20..1A5E, U+1A60..1A7C,
U+1A7F..1A89, U+1A90..1A99, U+1AA0..1AAD)
\p{Script_Extensions: Tai_Viet} (Short: \p{Scx=Tavt}, \p{Tavt})
(72: U+AA80..AAC2, U+AADB..AADF)
\p{Script_Extensions: Takr} \p{Script_Extensions=Takri} (80)
\p{Script_Extensions: Takri} (Short: \p{Scx=Takr}, \p{Takr}) (80:
U+0964..0965, U+A830..A839,
U+11680..116B9, U+116C0..116C9)
\p{Script_Extensions: Tale} \p{Script_Extensions=Tai_Le} (45)
\p{Script_Extensions: Talu} \p{Script_Extensions=New_Tai_Lue} (83)
\p{Script_Extensions: Tamil} (Short: \p{Scx=Taml}, \p{Taml}) (133:
U+0951..0952, U+0964..0965,
U+0B82..0B83, U+0B85..0B8A,
U+0B8E..0B90, U+0B92..0B95 ...)
\p{Script_Extensions: Taml} \p{Script_Extensions=Tamil} (133)
\p{Script_Extensions: Tang} \p{Script_Extensions=Tangut} (6914)
\p{Script_Extensions: Tangsa} (Short: \p{Scx=Tnsa}, \p{Tnsa}) (89:
U+16A70..16ABE, U+16AC0..16AC9)
\p{Script_Extensions: Tangut} (Short: \p{Scx=Tang}, \p{Tang})
(6914: U+16FE0, U+17000..187F7,
U+18800..18AFF, U+18D00..18D08)
\p{Script_Extensions: Tavt} \p{Script_Extensions=Tai_Viet} (72)
\p{Script_Extensions: Telu} \p{Script_Extensions=Telugu} (106)
\p{Script_Extensions: Telugu} (Short: \p{Scx=Telu}, \p{Telu})
(106: U+0951..0952, U+0964..0965,
U+0C00..0C0C, U+0C0E..0C10,
U+0C12..0C28, U+0C2A..0C39 ...)
\p{Script_Extensions: Tfng} \p{Script_Extensions=Tifinagh} (59)
\p{Script_Extensions: Tglg} \p{Script_Extensions=Tagalog} (25)
\p{Script_Extensions: Thaa} \p{Script_Extensions=Thaana} (66)
\p{Script_Extensions: Thaana} (Short: \p{Scx=Thaa}, \p{Thaa}) (66:
U+060C, U+061B..061C, U+061F,
U+0660..0669, U+0780..07B1, U+FDF2 ...)
\p{Script_Extensions: Thai} (Short: \p{Scx=Thai}, \p{Thai}) (86:
U+0E01..0E3A, U+0E40..0E5B)
\p{Script_Extensions: Tibetan} (Short: \p{Scx=Tibt}, \p{Tibt})
(207: U+0F00..0F47, U+0F49..0F6C,
U+0F71..0F97, U+0F99..0FBC,
U+0FBE..0FCC, U+0FCE..0FD4 ...)
\p{Script_Extensions: Tibt} \p{Script_Extensions=Tibetan} (207)
\p{Script_Extensions: Tifinagh} (Short: \p{Scx=Tfng}, \p{Tfng})
(59: U+2D30..2D67, U+2D6F..2D70, U+2D7F)
\p{Script_Extensions: Tirh} \p{Script_Extensions=Tirhuta} (97)
\p{Script_Extensions: Tirhuta} (Short: \p{Scx=Tirh}, \p{Tirh})
(97: U+0951..0952, U+0964..0965, U+1CF2,
U+A830..A839, U+11480..114C7,
U+114D0..114D9)
\p{Script_Extensions: Tnsa} \p{Script_Extensions=Tangsa} (89)
\p{Script_Extensions: Toto} (Short: \p{Scx=Toto}, \p{Toto}) (31:
U+1E290..1E2AE)
\p{Script_Extensions: Ugar} \p{Script_Extensions=Ugaritic} (31)
\p{Script_Extensions: Ugaritic} (Short: \p{Scx=Ugar}, \p{Ugar})
(31: U+10380..1039D, U+1039F)
\p{Script_Extensions: Unknown} (Short: \p{Scx=Zzzz}, \p{Zzzz})
(969_350 plus all above-Unicode code
points: U+0378..0379, U+0380..0383,
U+038B, U+038D, U+03A2, U+0530 ...)
\p{Script_Extensions: Vai} (Short: \p{Scx=Vai}, \p{Vai}) (300:
U+A500..A62B)
\p{Script_Extensions: Vaii} \p{Script_Extensions=Vai} (300)
\p{Script_Extensions: Vith} \p{Script_Extensions=Vithkuqi} (70)
\p{Script_Extensions: Vithkuqi} (Short: \p{Scx=Vith}, \p{Vith})
(70: U+10570..1057A, U+1057C..1058A,
U+1058C..10592, U+10594..10595,
U+10597..105A1, U+105A3..105B1 ...)
\p{Script_Extensions: Wancho} (Short: \p{Scx=Wcho}, \p{Wcho}) (59:
U+1E2C0..1E2F9, U+1E2FF)
\p{Script_Extensions: Wara} \p{Script_Extensions=Warang_Citi} (84)
\p{Script_Extensions: Warang_Citi} (Short: \p{Scx=Wara}, \p{Wara})
(84: U+118A0..118F2, U+118FF)
\p{Script_Extensions: Wcho} \p{Script_Extensions=Wancho} (59)
\p{Script_Extensions: Xpeo} \p{Script_Extensions=Old_Persian} (50)
\p{Script_Extensions: Xsux} \p{Script_Extensions=Cuneiform} (1234)
\p{Script_Extensions: Yezi} \p{Script_Extensions=Yezidi} (60)
\p{Script_Extensions: Yezidi} (Short: \p{Scx=Yezi}, \p{Yezi}) (60:
U+060C, U+061B, U+061F, U+0660..0669,
U+10E80..10EA9, U+10EAB..10EAD ...)
\p{Script_Extensions: Yi} (Short: \p{Scx=Yi}, \p{Yi}) (1246:
U+3001..3002, U+3008..3011,
U+3014..301B, U+30FB, U+A000..A48C,
U+A490..A4C6 ...)
\p{Script_Extensions: Yiii} \p{Script_Extensions=Yi} (1246)
\p{Script_Extensions: Zanabazar_Square} (Short: \p{Scx=Zanb},
\p{Zanb}) (72: U+11A00..11A47)
\p{Script_Extensions: Zanb} \p{Script_Extensions=Zanabazar_Square}
(72)
\p{Script_Extensions: Zinh} \p{Script_Extensions=Inherited} (586)
\p{Script_Extensions: Zyyy} \p{Script_Extensions=Common} (7824)
\p{Script_Extensions: Zzzz} \p{Script_Extensions=Unknown} (969_350
plus all above-Unicode code points)
\p{Scx: *} \p{Script_Extensions: *}
\p{SD} \p{Soft_Dotted} (= \p{Soft_Dotted=Y}) (47)
\p{SD: *} \p{Soft_Dotted: *}
\p{Sentence_Break: AT} \p{Sentence_Break=ATerm} (4)
\p{Sentence_Break: ATerm} (Short: \p{SB=AT}) (4: [.], U+2024,
U+FE52, U+FF0E)
\p{Sentence_Break: CL} \p{Sentence_Break=Close} (195)
\p{Sentence_Break: Close} (Short: \p{SB=CL}) (195: [\"\'\(\)\[\]
\{\}\xab\xbb], U+0F3A..0F3D,
U+169B..169C, U+2018..201F,
U+2039..203A, U+2045..2046 ...)
\p{Sentence_Break: CR} (Short: \p{SB=CR}) (1: [\r])
\p{Sentence_Break: EX} \p{Sentence_Break=Extend} (2508)
\p{Sentence_Break: Extend} (Short: \p{SB=EX}) (2508: U+0300..036F,
U+0483..0489, U+0591..05BD, U+05BF,
U+05C1..05C2, U+05C4..05C5 ...)
\p{Sentence_Break: FO} \p{Sentence_Break=Format} (65)
\p{Sentence_Break: Format} (Short: \p{SB=FO}) (65: [\xad],
U+0600..0605, U+061C, U+06DD, U+070F,
U+0890..0891 ...)
\p{Sentence_Break: LE} \p{Sentence_Break=OLetter} (127_761)
\p{Sentence_Break: LF} (Short: \p{SB=LF}) (1: [\n])
\p{Sentence_Break: LO} \p{Sentence_Break=Lower} (2424)
\p{Sentence_Break: Lower} (Short: \p{SB=LO}) (2424: [a-z\xaa\xb5
\xba\xdf-\xf6\xf8-\xff], U+0101, U+0103,
U+0105, U+0107, U+0109 ...)
\p{Sentence_Break: NU} \p{Sentence_Break=Numeric} (662)
\p{Sentence_Break: Numeric} (Short: \p{SB=NU}) (662: [0-9],
U+0660..0669, U+066B..066C,
U+06F0..06F9, U+07C0..07C9, U+0966..096F
...)
\p{Sentence_Break: OLetter} (Short: \p{SB=LE}) (127_761: U+01BB,
U+01C0..01C3, U+0294, U+02B9..02BF,
U+02C6..02D1, U+02EC ...)
\p{Sentence_Break: Other} (Short: \p{SB=XX}) (978_357 plus all
above-Unicode code points: [^\t\n\cK\f
\r\x20!\"\'\(\),\-.0-9:?A-Z\[\]a-z\{\}
\x85\xa0\xaa-\xab\xad\xb5\xba-\xbb\xc0-
\xd6\xd8-\xf6\xf8-\xff], U+02C2..02C5,
U+02D2..02DF, U+02E5..02EB, U+02ED,
U+02EF..02FF ...)
\p{Sentence_Break: SC} \p{Sentence_Break=SContinue} (26)
\p{Sentence_Break: SContinue} (Short: \p{SB=SC}) (26: [,\-:],
U+055D, U+060C..060D, U+07F8, U+1802,
U+1808 ...)
\p{Sentence_Break: SE} \p{Sentence_Break=Sep} (3)
\p{Sentence_Break: Sep} (Short: \p{SB=SE}) (3: [\x85],
U+2028..2029)
\p{Sentence_Break: Sp} (Short: \p{SB=Sp}) (20: [\t\cK\f\x20\xa0],
U+1680, U+2000..200A, U+202F, U+205F,
U+3000)
\p{Sentence_Break: ST} \p{Sentence_Break=STerm} (149)
\p{Sentence_Break: STerm} (Short: \p{SB=ST}) (149: [!?], U+0589,
U+061D..061F, U+06D4, U+0700..0702,
U+07F9 ...)
\p{Sentence_Break: UP} \p{Sentence_Break=Upper} (1936)
\p{Sentence_Break: Upper} (Short: \p{SB=UP}) (1936: [A-Z\xc0-\xd6
\xd8-\xde], U+0100, U+0102, U+0104,
U+0106, U+0108 ...)
\p{Sentence_Break: XX} \p{Sentence_Break=Other} (978_357 plus all
above-Unicode code points)
\p{Sentence_Terminal} \p{Sentence_Terminal=Y} (Short: \p{STerm})
(152)
\p{Sentence_Terminal: N*} (Short: \p{STerm=N}, \P{STerm})
(1_113_960 plus all above-Unicode code
points: [\x00-\x20\"#\$\%&\'\(\)*+,\-
\/0-9:;<=>\@A-Z\[\\\]\^_`a-z\{\|\}~\x7f-
\xff], U+0100..0588, U+058A..061C,
U+0620..06D3, U+06D5..06FF, U+0703..07F8
...)
\p{Sentence_Terminal: Y*} (Short: \p{STerm=Y}, \p{STerm}) (152:
[!.?], U+0589, U+061D..061F, U+06D4,
U+0700..0702, U+07F9 ...)
\p{Separator} \p{General_Category=Separator} (Short:
\p{Z}) (19)
\p{Sgnw} \p{SignWriting} (= \p{Script_Extensions=
SignWriting}) (672)
\p{Sharada} \p{Script_Extensions=Sharada} (Short:
\p{Shrd}; NOT \p{Block=Sharada}) (102)
\p{Shavian} \p{Script_Extensions=Shavian} (Short:
\p{Shaw}) (48)
\p{Shaw} \p{Shavian} (= \p{Script_Extensions=
Shavian}) (48)
X \p{Shorthand_Format_Controls} \p{Block=Shorthand_Format_Controls}
(16)
\p{Shrd} \p{Sharada} (= \p{Script_Extensions=
Sharada}) (NOT \p{Block=Sharada}) (102)
\p{Sidd} \p{Siddham} (= \p{Script_Extensions=
Siddham}) (NOT \p{Block=Siddham}) (92)
\p{Siddham} \p{Script_Extensions=Siddham} (Short:
\p{Sidd}; NOT \p{Block=Siddham}) (92)
\p{SignWriting} \p{Script_Extensions=SignWriting} (Short:
\p{Sgnw}) (672)
\p{Sind} \p{Khudawadi} (= \p{Script_Extensions=
Khudawadi}) (NOT \p{Block=Khudawadi})
(81)
\p{Sinh} \p{Sinhala} (= \p{Script_Extensions=
Sinhala}) (NOT \p{Block=Sinhala}) (113)
\p{Sinhala} \p{Script_Extensions=Sinhala} (Short:
\p{Sinh}; NOT \p{Block=Sinhala}) (113)
X \p{Sinhala_Archaic_Numbers} \p{Block=Sinhala_Archaic_Numbers} (32)
\p{Sk} \p{Modifier_Symbol} (=
\p{General_Category=Modifier_Symbol})
(125)
\p{Sm} \p{Math_Symbol} (= \p{General_Category=
Math_Symbol}) (948)
X \p{Small_Form_Variants} \p{Block=Small_Form_Variants} (Short:
\p{InSmallForms}) (32)
X \p{Small_Forms} \p{Small_Form_Variants} (= \p{Block=
Small_Form_Variants}) (32)
X \p{Small_Kana_Ext} \p{Small_Kana_Extension} (= \p{Block=
Small_Kana_Extension}) (64)
X \p{Small_Kana_Extension} \p{Block=Small_Kana_Extension} (Short:
\p{InSmallKanaExt}) (64)
\p{So} \p{Other_Symbol} (= \p{General_Category=
Other_Symbol}) (6605)
\p{Soft_Dotted} \p{Soft_Dotted=Y} (Short: \p{SD}) (47)
\p{Soft_Dotted: N*} (Short: \p{SD=N}, \P{SD}) (1_114_065 plus
all above-Unicode code points: [\x00-
\x20!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=>?\@A-
Z\[\\\]\^_`a-hk-z\{\|\}~\x7f-\xff],
U+0100..012E, U+0130..0248,
U+024A..0267, U+0269..029C, U+029E..02B1
...)
\p{Soft_Dotted: Y*} (Short: \p{SD=Y}, \p{SD}) (47: [i-j],
U+012F, U+0249, U+0268, U+029D, U+02B2
...)
\p{Sogd} \p{Sogdian} (= \p{Script_Extensions=
Sogdian}) (NOT \p{Block=Sogdian}) (43)
\p{Sogdian} \p{Script_Extensions=Sogdian} (Short:
\p{Sogd}; NOT \p{Block=Sogdian}) (43)
\p{Sogo} \p{Old_Sogdian} (= \p{Script_Extensions=
Old_Sogdian}) (NOT \p{Block=
Old_Sogdian}) (40)
\p{Sora} \p{Sora_Sompeng} (= \p{Script_Extensions=
Sora_Sompeng}) (NOT \p{Block=
Sora_Sompeng}) (35)
\p{Sora_Sompeng} \p{Script_Extensions=Sora_Sompeng} (Short:
\p{Sora}; NOT \p{Block=Sora_Sompeng})
(35)
\p{Soyo} \p{Soyombo} (= \p{Script_Extensions=
Soyombo}) (NOT \p{Block=Soyombo}) (83)
\p{Soyombo} \p{Script_Extensions=Soyombo} (Short:
\p{Soyo}; NOT \p{Block=Soyombo}) (83)
\p{Space} \p{White_Space} (= \p{White_Space=Y}) (25)
\p{Space: *} \p{White_Space: *}
\p{Space_Separator} \p{General_Category=Space_Separator}
(Short: \p{Zs}) (17)
\p{SpacePerl} \p{XPosixSpace} (25)
\p{Spacing_Mark} \p{General_Category=Spacing_Mark} (Short:
\p{Mc}) (445)
X \p{Spacing_Modifier_Letters} \p{Block=Spacing_Modifier_Letters}
(Short: \p{InModifierLetters}) (80)
X \p{Specials} \p{Block=Specials} (16)
\p{STerm} \p{Sentence_Terminal} (=
\p{Sentence_Terminal=Y}) (152)
\p{STerm: *} \p{Sentence_Terminal: *}
\p{Sund} \p{Sundanese} (= \p{Script_Extensions=
Sundanese}) (NOT \p{Block=Sundanese})
(72)
\p{Sundanese} \p{Script_Extensions=Sundanese} (Short:
\p{Sund}; NOT \p{Block=Sundanese}) (72)
X \p{Sundanese_Sup} \p{Sundanese_Supplement} (= \p{Block=
Sundanese_Supplement}) (16)
X \p{Sundanese_Supplement} \p{Block=Sundanese_Supplement} (Short:
\p{InSundaneseSup}) (16)
X \p{Sup_Arrows_A} \p{Supplemental_Arrows_A} (= \p{Block=
Supplemental_Arrows_A}) (16)
X \p{Sup_Arrows_B} \p{Supplemental_Arrows_B} (= \p{Block=
Supplemental_Arrows_B}) (128)
X \p{Sup_Arrows_C} \p{Supplemental_Arrows_C} (= \p{Block=
Supplemental_Arrows_C}) (256)
X \p{Sup_Math_Operators} \p{Supplemental_Mathematical_Operators} (=
\p{Block=
Supplemental_Mathematical_Operators})
(256)
X \p{Sup_PUA_A} \p{Supplementary_Private_Use_Area_A} (=
\p{Block=
Supplementary_Private_Use_Area_A})
(65_536)
X \p{Sup_PUA_B} \p{Supplementary_Private_Use_Area_B} (=
\p{Block=
Supplementary_Private_Use_Area_B})
(65_536)
X \p{Sup_Punctuation} \p{Supplemental_Punctuation} (= \p{Block=
Supplemental_Punctuation}) (128)
X \p{Sup_Symbols_And_Pictographs}
\p{Supplemental_Symbols_And_Pictographs}
(= \p{Block=
Supplemental_Symbols_And_Pictographs})
(256)
X \p{Super_And_Sub} \p{Superscripts_And_Subscripts} (=
\p{Block=Superscripts_And_Subscripts})
(48)
X \p{Superscripts_And_Subscripts} \p{Block=
Superscripts_And_Subscripts} (Short:
\p{InSuperAndSub}) (48)
X \p{Supplemental_Arrows_A} \p{Block=Supplemental_Arrows_A} (Short:
\p{InSupArrowsA}) (16)
X \p{Supplemental_Arrows_B} \p{Block=Supplemental_Arrows_B} (Short:
\p{InSupArrowsB}) (128)
X \p{Supplemental_Arrows_C} \p{Block=Supplemental_Arrows_C} (Short:
\p{InSupArrowsC}) (256)
X \p{Supplemental_Mathematical_Operators} \p{Block=
Supplemental_Mathematical_Operators}
(Short: \p{InSupMathOperators}) (256)
X \p{Supplemental_Punctuation} \p{Block=Supplemental_Punctuation}
(Short: \p{InSupPunctuation}) (128)
X \p{Supplemental_Symbols_And_Pictographs} \p{Block=
Supplemental_Symbols_And_Pictographs}
(Short: \p{InSupSymbolsAndPictographs})
(256)
X \p{Supplementary_Private_Use_Area_A} \p{Block=
Supplementary_Private_Use_Area_A}
(Short: \p{InSupPUAA}) (65_536)
X \p{Supplementary_Private_Use_Area_B} \p{Block=
Supplementary_Private_Use_Area_B}
(Short: \p{InSupPUAB}) (65_536)
\p{Surrogate} \p{General_Category=Surrogate} (Short:
\p{Cs}) (2048)
X \p{Sutton_SignWriting} \p{Block=Sutton_SignWriting} (688)
\p{Sylo} \p{Syloti_Nagri} (= \p{Script_Extensions=
Syloti_Nagri}) (NOT \p{Block=
Syloti_Nagri}) (57)
\p{Syloti_Nagri} \p{Script_Extensions=Syloti_Nagri} (Short:
\p{Sylo}; NOT \p{Block=Syloti_Nagri})
(57)
\p{Symbol} \p{General_Category=Symbol} (Short: \p{S})
(7741)
X \p{Symbols_And_Pictographs_Ext_A}
\p{Symbols_And_Pictographs_Extended_A}
(= \p{Block=
Symbols_And_Pictographs_Extended_A})
(144)
X \p{Symbols_And_Pictographs_Extended_A} \p{Block=
Symbols_And_Pictographs_Extended_A} (144)
X \p{Symbols_For_Legacy_Computing} \p{Block=
Symbols_For_Legacy_Computing} (256)
\p{Syrc} \p{Syriac} (= \p{Script_Extensions=
Syriac}) (NOT \p{Block=Syriac}) (107)
\p{Syriac} \p{Script_Extensions=Syriac} (Short:
\p{Syrc}; NOT \p{Block=Syriac}) (107)
X \p{Syriac_Sup} \p{Syriac_Supplement} (= \p{Block=
Syriac_Supplement}) (16)
X \p{Syriac_Supplement} \p{Block=Syriac_Supplement} (Short:
\p{InSyriacSup}) (16)
\p{Tagalog} \p{Script_Extensions=Tagalog} (Short:
\p{Tglg}; NOT \p{Block=Tagalog}) (25)
\p{Tagb} \p{Tagbanwa} (= \p{Script_Extensions=
Tagbanwa}) (NOT \p{Block=Tagbanwa}) (20)
\p{Tagbanwa} \p{Script_Extensions=Tagbanwa} (Short:
\p{Tagb}; NOT \p{Block=Tagbanwa}) (20)
X \p{Tags} \p{Block=Tags} (128)
\p{Tai_Le} \p{Script_Extensions=Tai_Le} (Short:
\p{Tale}; NOT \p{Block=Tai_Le}) (45)
\p{Tai_Tham} \p{Script_Extensions=Tai_Tham} (Short:
\p{Lana}; NOT \p{Block=Tai_Tham}) (127)
\p{Tai_Viet} \p{Script_Extensions=Tai_Viet} (Short:
\p{Tavt}; NOT \p{Block=Tai_Viet}) (72)
X \p{Tai_Xuan_Jing} \p{Tai_Xuan_Jing_Symbols} (= \p{Block=
Tai_Xuan_Jing_Symbols}) (96)
X \p{Tai_Xuan_Jing_Symbols} \p{Block=Tai_Xuan_Jing_Symbols} (Short:
\p{InTaiXuanJing}) (96)
\p{Takr} \p{Takri} (= \p{Script_Extensions=Takri})
(NOT \p{Block=Takri}) (80)
\p{Takri} \p{Script_Extensions=Takri} (Short:
\p{Takr}; NOT \p{Block=Takri}) (80)
\p{Tale} \p{Tai_Le} (= \p{Script_Extensions=
Tai_Le}) (NOT \p{Block=Tai_Le}) (45)
\p{Talu} \p{New_Tai_Lue} (= \p{Script_Extensions=
New_Tai_Lue}) (NOT \p{Block=
New_Tai_Lue}) (83)
\p{Tamil} \p{Script_Extensions=Tamil} (Short:
\p{Taml}; NOT \p{Block=Tamil}) (133)
X \p{Tamil_Sup} \p{Tamil_Supplement} (= \p{Block=
Tamil_Supplement}) (64)
X \p{Tamil_Supplement} \p{Block=Tamil_Supplement} (Short:
\p{InTamilSup}) (64)
\p{Taml} \p{Tamil} (= \p{Script_Extensions=Tamil})
(NOT \p{Block=Tamil}) (133)
\p{Tang} \p{Tangut} (= \p{Script_Extensions=
Tangut}) (NOT \p{Block=Tangut}) (6914)
\p{Tangsa} \p{Script_Extensions=Tangsa} (Short:
\p{Tnsa}; NOT \p{Block=Tangsa}) (89)
\p{Tangut} \p{Script_Extensions=Tangut} (Short:
\p{Tang}; NOT \p{Block=Tangut}) (6914)
X \p{Tangut_Components} \p{Block=Tangut_Components} (768)
X \p{Tangut_Sup} \p{Tangut_Supplement} (= \p{Block=
Tangut_Supplement}) (128)
X \p{Tangut_Supplement} \p{Block=Tangut_Supplement} (Short:
\p{InTangutSup}) (128)
\p{Tavt} \p{Tai_Viet} (= \p{Script_Extensions=
Tai_Viet}) (NOT \p{Block=Tai_Viet}) (72)
\p{Telu} \p{Telugu} (= \p{Script_Extensions=
Telugu}) (NOT \p{Block=Telugu}) (106)
\p{Telugu} \p{Script_Extensions=Telugu} (Short:
\p{Telu}; NOT \p{Block=Telugu}) (106)
\p{Term} \p{Terminal_Punctuation} (=
\p{Terminal_Punctuation=Y}) (276)
\p{Term: *} \p{Terminal_Punctuation: *}
\p{Terminal_Punctuation} \p{Terminal_Punctuation=Y} (Short:
\p{Term}) (276)
\p{Terminal_Punctuation: N*} (Short: \p{Term=N}, \P{Term})
(1_113_836 plus all above-Unicode code
points: [\x00-\x20\"#\$\%&\'\(\)*+\-\/0-
9<=>\@A-Z\[\\\]\^_`a-z\{\|\}~\x7f-\xff],
U+0100..037D, U+037F..0386,
U+0388..0588, U+058A..05C2, U+05C4..060B
...)
\p{Terminal_Punctuation: Y*} (Short: \p{Term=Y}, \p{Term}) (276:
[!,.:;?], U+037E, U+0387, U+0589,
U+05C3, U+060C ...)
\p{Tfng} \p{Tifinagh} (= \p{Script_Extensions=
Tifinagh}) (NOT \p{Block=Tifinagh}) (59)
\p{Tglg} \p{Tagalog} (= \p{Script_Extensions=
Tagalog}) (NOT \p{Block=Tagalog}) (25)
\p{Thaa} \p{Thaana} (= \p{Script_Extensions=
Thaana}) (NOT \p{Block=Thaana}) (66)
\p{Thaana} \p{Script_Extensions=Thaana} (Short:
\p{Thaa}; NOT \p{Block=Thaana}) (66)
\p{Thai} \p{Script_Extensions=Thai} (NOT \p{Block=
Thai}) (86)
\p{Tibetan} \p{Script_Extensions=Tibetan} (Short:
\p{Tibt}; NOT \p{Block=Tibetan}) (207)
\p{Tibt} \p{Tibetan} (= \p{Script_Extensions=
Tibetan}) (NOT \p{Block=Tibetan}) (207)
\p{Tifinagh} \p{Script_Extensions=Tifinagh} (Short:
\p{Tfng}; NOT \p{Block=Tifinagh}) (59)
\p{Tirh} \p{Tirhuta} (= \p{Script_Extensions=
Tirhuta}) (NOT \p{Block=Tirhuta}) (97)
\p{Tirhuta} \p{Script_Extensions=Tirhuta} (Short:
\p{Tirh}; NOT \p{Block=Tirhuta}) (97)
\p{Title} \p{Titlecase} (/i= Cased=Yes) (31)
\p{Titlecase} (= \p{Gc=Lt}) (Short: \p{Title}; /i=
Cased=Yes) (31: U+01C5, U+01C8, U+01CB,
U+01F2, U+1F88..1F8F, U+1F98..1F9F ...)
\p{Titlecase_Letter} \p{General_Category=Titlecase_Letter}
(Short: \p{Lt}; /i= General_Category=
Cased_Letter) (31)
\p{Tnsa} \p{Tangsa} (= \p{Script_Extensions=
Tangsa}) (NOT \p{Block=Tangsa}) (89)
\p{Toto} \p{Script_Extensions=Toto} (NOT \p{Block=
Toto}) (31)
X \p{Transport_And_Map} \p{Transport_And_Map_Symbols} (= \p{Block=
Transport_And_Map_Symbols}) (128)
X \p{Transport_And_Map_Symbols} \p{Block=Transport_And_Map_Symbols}
(Short: \p{InTransportAndMap}) (128)
X \p{UCAS} \p{Unified_Canadian_Aboriginal_Syllabics}
(= \p{Block=
Unified_Canadian_Aboriginal_Syllabics})
(640)
X \p{UCAS_Ext} \p{Unified_Canadian_Aboriginal_Syllabics_-
Extended} (= \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended}) (80)
X \p{UCAS_Ext_A} \p{Unified_Canadian_Aboriginal_Syllabics_-
Extended_A} (= \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended_A}) (16)
\p{Ugar} \p{Ugaritic} (= \p{Script_Extensions=
Ugaritic}) (NOT \p{Block=Ugaritic}) (31)
\p{Ugaritic} \p{Script_Extensions=Ugaritic} (Short:
\p{Ugar}; NOT \p{Block=Ugaritic}) (31)
\p{UIdeo} \p{Unified_Ideograph} (=
\p{Unified_Ideograph=Y}) (92_865)
\p{UIdeo: *} \p{Unified_Ideograph: *}
\p{Unassigned} \p{General_Category=Unassigned} (Short:
\p{Cn}) (829_834 plus all above-Unicode
code points)
\p{Unicode} \p{Any} (1_114_112)
X \p{Unified_Canadian_Aboriginal_Syllabics} \p{Block=
Unified_Canadian_Aboriginal_Syllabics}
(Short: \p{InUCAS}) (640)
X \p{Unified_Canadian_Aboriginal_Syllabics_Extended} \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended} (Short: \p{InUCASExt}) (80)
X \p{Unified_Canadian_Aboriginal_Syllabics_Extended_A} \p{Block=
Unified_Canadian_Aboriginal_Syllabics_-
Extended_A} (Short: \p{InUCASExtA}) (16)
\p{Unified_Ideograph} \p{Unified_Ideograph=Y} (Short: \p{UIdeo})
(92_865)
\p{Unified_Ideograph: N*} (Short: \p{UIdeo=N}, \P{UIdeo})
(1_021_247 plus all above-Unicode code
points: U+0000..33FF, U+4DC0..4DFF,
U+A000..FA0D, U+FA10, U+FA12,
U+FA15..FA1E ...)
\p{Unified_Ideograph: Y*} (Short: \p{UIdeo=Y}, \p{UIdeo}) (92_865:
U+3400..4DBF, U+4E00..9FFF,
U+FA0E..FA0F, U+FA11, U+FA13..FA14,
U+FA1F ...)
\p{Unknown} \p{Script_Extensions=Unknown} (Short:
\p{Zzzz}) (969_350 plus all above-
Unicode code points)
\p{Upper} \p{XPosixUpper} (= \p{Uppercase=Y}) (/i=
Cased=Yes) (1951)
\p{Upper: *} \p{Uppercase: *}
\p{Uppercase} \p{XPosixUpper} (= \p{Uppercase=Y}) (/i=
Cased=Yes) (1951)
\p{Uppercase: N*} (Short: \p{Upper=N}, \P{Upper}; /i= Cased=
No) (1_112_161 plus all above-Unicode
code points: [\x00-\x20!\"#\$\%&\'
\(\)*+,\-.\/0-9:;<=>?\@\[\\\]\^_`a-z\{
\|\}~\x7f-\xbf\xd7\xdf-\xff], U+0101,
U+0103, U+0105, U+0107, U+0109 ...)
\p{Uppercase: Y*} (Short: \p{Upper=Y}, \p{Upper}; /i= Cased=
Yes) (1951: [A-Z\xc0-\xd6\xd8-\xde],
U+0100, U+0102, U+0104, U+0106, U+0108
...)
\p{Uppercase_Letter} \p{General_Category=Uppercase_Letter}
(Short: \p{Lu}; /i= General_Category=
Cased_Letter) (1831)
\p{Vai} \p{Script_Extensions=Vai} (NOT \p{Block=
Vai}) (300)
\p{Vaii} \p{Vai} (= \p{Script_Extensions=Vai}) (NOT
\p{Block=Vai}) (300)
\p{Variation_Selector} \p{Variation_Selector=Y} (Short: \p{VS};
NOT \p{Variation_Selectors}) (260)
\p{Variation_Selector: N*} (Short: \p{VS=N}, \P{VS}) (1_113_852
plus all above-Unicode code points:
U+0000..180A, U+180E, U+1810..FDFF,
U+FE10..E00FF, U+E01F0..infinity)
\p{Variation_Selector: Y*} (Short: \p{VS=Y}, \p{VS}) (260:
U+180B..180D, U+180F, U+FE00..FE0F,
U+E0100..E01EF)
X \p{Variation_Selectors} \p{Block=Variation_Selectors} (Short:
\p{InVS}) (16)
X \p{Variation_Selectors_Supplement} \p{Block=
Variation_Selectors_Supplement} (Short:
\p{InVSSup}) (240)
X \p{Vedic_Ext} \p{Vedic_Extensions} (= \p{Block=
Vedic_Extensions}) (48)
X \p{Vedic_Extensions} \p{Block=Vedic_Extensions} (Short:
\p{InVedicExt}) (48)
X \p{Vertical_Forms} \p{Block=Vertical_Forms} (16)
\p{Vertical_Orientation: R} \p{Vertical_Orientation=Rotated}
(786_641 plus all above-Unicode code
points)
\p{Vertical_Orientation: Rotated} (Short: \p{Vo=R}) (786_641 plus
all above-Unicode code points: [\x00-
\xa6\xa8\xaa-\xad\xaf-\xb0\xb2-\xbb\xbf-
\xd6\xd8-\xf6\xf8-\xff], U+0100..02E9,
U+02EC..10FF, U+1200..1400,
U+1680..18AF, U+1900..2015 ...)
\p{Vertical_Orientation: Tr} \p{Vertical_Orientation=
Transformed_Rotated} (47)
\p{Vertical_Orientation: Transformed_Rotated} (Short: \p{Vo=Tr})
(47: U+2329..232A, U+3008..3011,
U+3014..301F, U+3030, U+30A0, U+30FC ...)
\p{Vertical_Orientation: Transformed_Upright} (Short: \p{Vo=Tu})
(148: U+3001..3002, U+3041, U+3043,
U+3045, U+3047, U+3049 ...)
\p{Vertical_Orientation: Tu} \p{Vertical_Orientation=
Transformed_Upright} (148)
\p{Vertical_Orientation: U} \p{Vertical_Orientation=Upright}
(327_276)
\p{Vertical_Orientation: Upright} (Short: \p{Vo=U}) (327_276:
[\xa7\xa9\xae\xb1\xbc-\xbe\xd7\xf7],
U+02EA..02EB, U+1100..11FF,
U+1401..167F, U+18B0..18FF, U+2016 ...)
\p{VertSpace} \v (7: [\n\cK\f\r\x85], U+2028..2029)
\p{Vith} \p{Vithkuqi} (= \p{Script_Extensions=
Vithkuqi}) (NOT \p{Block=Vithkuqi}) (70)
\p{Vithkuqi} \p{Script_Extensions=Vithkuqi} (Short:
\p{Vith}; NOT \p{Block=Vithkuqi}) (70)
\p{Vo: *} \p{Vertical_Orientation: *}
\p{VS} \p{Variation_Selector} (=
\p{Variation_Selector=Y}) (NOT
\p{Variation_Selectors}) (260)
\p{VS: *} \p{Variation_Selector: *}
X \p{VS_Sup} \p{Variation_Selectors_Supplement} (=
\p{Block=
Variation_Selectors_Supplement}) (240)
\p{Wancho} \p{Script_Extensions=Wancho} (Short:
\p{Wcho}; NOT \p{Block=Wancho}) (59)
\p{Wara} \p{Warang_Citi} (= \p{Script_Extensions=
Warang_Citi}) (NOT \p{Block=
Warang_Citi}) (84)
\p{Warang_Citi} \p{Script_Extensions=Warang_Citi} (Short:
\p{Wara}; NOT \p{Block=Warang_Citi}) (84)
\p{WB: *} \p{Word_Break: *}
\p{Wcho} \p{Wancho} (= \p{Script_Extensions=
Wancho}) (NOT \p{Block=Wancho}) (59)
\p{White_Space} \p{White_Space=Y} (Short: \p{Space}) (25)
\p{White_Space: N*} (Short: \p{Space=N}, \P{Space}) (1_114_087
plus all above-Unicode code points: [^
\t\n\cK\f\r\x20\x85\xa0], U+0100..167F,
U+1681..1FFF, U+200B..2027,
U+202A..202E, U+2030..205E ...)
\p{White_Space: Y*} (Short: \p{Space=Y}, \p{Space}) (25: [\t
\n\cK\f\r\x20\x85\xa0], U+1680,
U+2000..200A, U+2028..2029, U+202F,
U+205F ...)
\p{Word} \p{XPosixWord} (135_202)
\p{Word_Break: ALetter} (Short: \p{WB=LE}) (29_336: [A-Za-z\xaa
\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02D7, U+02DE..02FF,
U+0370..0374, U+0376..0377, U+037A..037D
...)
\p{Word_Break: CR} (Short: \p{WB=CR}) (1: [\r])
\p{Word_Break: Double_Quote} (Short: \p{WB=DQ}) (1: [\"])
\p{Word_Break: DQ} \p{Word_Break=Double_Quote} (1)
\p{Word_Break: E_Base} (Short: \p{WB=EB}) (0)
\p{Word_Break: E_Base_GAZ} (Short: \p{WB=EBG}) (0)
\p{Word_Break: E_Modifier} (Short: \p{WB=EM}) (0)
\p{Word_Break: EB} \p{Word_Break=E_Base} (0)
\p{Word_Break: EBG} \p{Word_Break=E_Base_GAZ} (0)
\p{Word_Break: EM} \p{Word_Break=E_Modifier} (0)
\p{Word_Break: EX} \p{Word_Break=ExtendNumLet} (11)
\p{Word_Break: Extend} (Short: \p{WB=Extend}) (2512:
U+0300..036F, U+0483..0489,
U+0591..05BD, U+05BF, U+05C1..05C2,
U+05C4..05C5 ...)
\p{Word_Break: ExtendNumLet} (Short: \p{WB=EX}) (11: [_], U+202F,
U+203F..2040, U+2054, U+FE33..FE34,
U+FE4D..FE4F ...)
\p{Word_Break: FO} \p{Word_Break=Format} (64)
\p{Word_Break: Format} (Short: \p{WB=FO}) (64: [\xad],
U+0600..0605, U+061C, U+06DD, U+070F,
U+0890..0891 ...)
\p{Word_Break: GAZ} \p{Word_Break=Glue_After_Zwj} (0)
\p{Word_Break: Glue_After_Zwj} (Short: \p{WB=GAZ}) (0)
\p{Word_Break: Hebrew_Letter} (Short: \p{WB=HL}) (75:
U+05D0..05EA, U+05EF..05F2, U+FB1D,
U+FB1F..FB28, U+FB2A..FB36, U+FB38..FB3C
...)
\p{Word_Break: HL} \p{Word_Break=Hebrew_Letter} (75)
\p{Word_Break: KA} \p{Word_Break=Katakana} (330)
\p{Word_Break: Katakana} (Short: \p{WB=KA}) (330: U+3031..3035,
U+309B..309C, U+30A0..30FA,
U+30FC..30FF, U+31F0..31FF, U+32D0..32FE
...)
\p{Word_Break: LE} \p{Word_Break=ALetter} (29_336)
\p{Word_Break: LF} (Short: \p{WB=LF}) (1: [\n])
\p{Word_Break: MB} \p{Word_Break=MidNumLet} (7)
\p{Word_Break: MidLetter} (Short: \p{WB=ML}) (9: [:\xb7], U+0387,
U+055F, U+05F4, U+2027, U+FE13 ...)
\p{Word_Break: MidNum} (Short: \p{WB=MN}) (15: [,;], U+037E,
U+0589, U+060C..060D, U+066C, U+07F8 ...)
\p{Word_Break: MidNumLet} (Short: \p{WB=MB}) (7: [.],
U+2018..2019, U+2024, U+FE52, U+FF07,
U+FF0E)
\p{Word_Break: ML} \p{Word_Break=MidLetter} (9)
\p{Word_Break: MN} \p{Word_Break=MidNum} (15)
\p{Word_Break: Newline} (Short: \p{WB=NL}) (5: [\cK\f\x85],
U+2028..2029)
\p{Word_Break: NL} \p{Word_Break=Newline} (5)
\p{Word_Break: NU} \p{Word_Break=Numeric} (661)
\p{Word_Break: Numeric} (Short: \p{WB=NU}) (661: [0-9],
U+0660..0669, U+066B, U+06F0..06F9,
U+07C0..07C9, U+0966..096F ...)
\p{Word_Break: Other} (Short: \p{WB=XX}) (1_081_042 plus all
above-Unicode code points: [^\n\cK\f\r
\x20\"\',.0-9:;A-Z_a-z\x85\xaa\xad\xb5
\xb7\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+02D8..02DD, U+0375, U+0378..0379,
U+0380..0385, U+038B ...)
\p{Word_Break: Regional_Indicator} (Short: \p{WB=RI}) (26:
U+1F1E6..1F1FF)
\p{Word_Break: RI} \p{Word_Break=Regional_Indicator} (26)
\p{Word_Break: Single_Quote} (Short: \p{WB=SQ}) (1: [\'])
\p{Word_Break: SQ} \p{Word_Break=Single_Quote} (1)
\p{Word_Break: WSegSpace} (Short: \p{WB=WSegSpace}) (14: [\x20],
U+1680, U+2000..2006, U+2008..200A,
U+205F, U+3000)
\p{Word_Break: XX} \p{Word_Break=Other} (1_081_042 plus all
above-Unicode code points)
\p{Word_Break: ZWJ} (Short: \p{WB=ZWJ}) (1: U+200D)
\p{WSpace} \p{White_Space} (= \p{White_Space=Y}) (25)
\p{WSpace: *} \p{White_Space: *}
\p{XDigit} \p{XPosixXDigit} (= \p{Hex_Digit=Y}) (44)
\p{XID_Continue} \p{XID_Continue=Y} (Short: \p{XIDC})
(135_053)
\p{XID_Continue: N*} (Short: \p{XIDC=N}, \P{XIDC}) (979_059
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/:;<=>?
\@\[\\\]\^`\{\|\}~\x7f-\xa9\xab-\xb4
\xb6\xb8-\xb9\xbb-\xbf\xd7\xf7],
U+02C2..02C5, U+02D2..02DF,
U+02E5..02EB, U+02ED, U+02EF..02FF ...)
\p{XID_Continue: Y*} (Short: \p{XIDC=Y}, \p{XIDC}) (135_053:
[0-9A-Z_a-z\xaa\xb5\xb7\xba\xc0-\xd6
\xd8-\xf6\xf8-\xff], U+0100..02C1,
U+02C6..02D1, U+02E0..02E4, U+02EC,
U+02EE ...)
\p{XID_Start} \p{XID_Start=Y} (Short: \p{XIDS}) (131_974)
\p{XID_Start: N*} (Short: \p{XIDS=N}, \P{XIDS}) (982_138
plus all above-Unicode code points:
[\x00-\x20!\"#\$\%&\'\(\)*+,\-.\/0-9:;<=
>?\@\[\\\]\^_`\{\|\}~\x7f-\xa9\xab-\xb4
\xb6-\xb9\xbb-\xbf\xd7\xf7],
U+02C2..02C5, U+02D2..02DF,
U+02E5..02EB, U+02ED, U+02EF..036F ...)
\p{XID_Start: Y*} (Short: \p{XIDS=Y}, \p{XIDS}) (131_974:
[A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6
\xf8-\xff], U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
\p{XIDC} \p{XID_Continue} (= \p{XID_Continue=Y})
(135_053)
\p{XIDC: *} \p{XID_Continue: *}
\p{XIDS} \p{XID_Start} (= \p{XID_Start=Y}) (131_974)
\p{XIDS: *} \p{XID_Start: *}
\p{Xpeo} \p{Old_Persian} (= \p{Script_Extensions=
Old_Persian}) (NOT \p{Block=
Old_Persian}) (50)
\p{XPerlSpace} \p{XPosixSpace} (25)
\p{XPosixAlnum} Alphabetic and (decimal) Numeric (Short:
\p{Alnum}) (134_056: [0-9A-Za-z\xaa\xb5
\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
\p{XPosixAlpha} \p{Alphabetic=Y} (Short: \p{Alpha})
(133_396)
\p{XPosixBlank} \h, Horizontal white space (Short:
\p{Blank}) (18: [\t\x20\xa0], U+1680,
U+2000..200A, U+202F, U+205F, U+3000)
\p{XPosixCntrl} \p{General_Category=Control} Control
characters (Short: \p{Cc}) (65)
\p{XPosixDigit} \p{General_Category=Decimal_Number} [0-9]
+ all other decimal digits (Short:
\p{Nd}) (660)
\p{XPosixGraph} Characters that are graphical (Short:
\p{Graph}) (282_146: [!\"#\$\%&\'
\(\)*+,\-.\/0-9:;<=>?\@A-Z\[\\\]\^_`a-z
\{\|\}~\xa1-\xff], U+0100..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1 ...)
\p{XPosixLower} \p{Lowercase=Y} (Short: \p{Lower}; /i=
Cased=Yes) (2471)
\p{XPosixPrint} Characters that are graphical plus space
characters (but no controls) (Short:
\p{Print}) (282_163: [\x20-\x7e\xa0-
\xff], U+0100..0377, U+037A..037F,
U+0384..038A, U+038C, U+038E..03A1 ...)
\p{XPosixPunct} \p{Punct} + ASCII-range \p{Symbol} (828:
[!\"#\$\%&\'\(\)*+,\-.\/:;<=>?\@\[\\\]
\^_`\{\|\}~\xa1\xa7\xab\xb6-\xb7\xbb
\xbf], U+037E, U+0387, U+055A..055F,
U+0589..058A, U+05BE ...)
\p{XPosixSpace} \s including beyond ASCII and vertical tab
(Short: \p{SpacePerl}) (25: [\t\n\cK\f
\r\x20\x85\xa0], U+1680, U+2000..200A,
U+2028..2029, U+202F, U+205F ...)
\p{XPosixUpper} \p{Uppercase=Y} (Short: \p{Upper}; /i=
Cased=Yes) (1951)
\p{XPosixWord} \w, including beyond ASCII; = \p{Alnum} +
\pM + \p{Pc} + \p{Join_Control} (Short:
\p{Word}) (135_202: [0-9A-Z_a-z\xaa\xb5
\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...)
\p{XPosixXDigit} \p{Hex_Digit=Y} (Short: \p{Hex}) (44)
\p{Xsux} \p{Cuneiform} (= \p{Script_Extensions=
Cuneiform}) (NOT \p{Block=Cuneiform})
(1234)
\p{Yezi} \p{Yezidi} (= \p{Script_Extensions=
Yezidi}) (NOT \p{Block=Yezidi}) (60)
\p{Yezidi} \p{Script_Extensions=Yezidi} (Short:
\p{Yezi}; NOT \p{Block=Yezidi}) (60)
\p{Yi} \p{Script_Extensions=Yi} (1246)
X \p{Yi_Radicals} \p{Block=Yi_Radicals} (64)
X \p{Yi_Syllables} \p{Block=Yi_Syllables} (1168)
\p{Yiii} \p{Yi} (= \p{Script_Extensions=Yi}) (1246)
X \p{Yijing} \p{Yijing_Hexagram_Symbols} (= \p{Block=
Yijing_Hexagram_Symbols}) (64)
X \p{Yijing_Hexagram_Symbols} \p{Block=Yijing_Hexagram_Symbols}
(Short: \p{InYijing}) (64)
\p{Z} \pZ \p{Separator} (= \p{General_Category=
Separator}) (19)
\p{Zanabazar_Square} \p{Script_Extensions=Zanabazar_Square}
(Short: \p{Zanb}; NOT \p{Block=
Zanabazar_Square}) (72)
\p{Zanb} \p{Zanabazar_Square} (=
\p{Script_Extensions=Zanabazar_Square})
(NOT \p{Block=Zanabazar_Square}) (72)
\p{Zinh} \p{Inherited} (= \p{Script_Extensions=
Inherited}) (586)
\p{Zl} \p{Line_Separator} (= \p{General_Category=
Line_Separator}) (1)
X \p{Znamenny_Music} \p{Znamenny_Musical_Notation} (= \p{Block=
Znamenny_Musical_Notation}) (208)
X \p{Znamenny_Musical_Notation} \p{Block=Znamenny_Musical_Notation}
(Short: \p{InZnamennyMusic}) (208)
\p{Zp} \p{Paragraph_Separator} (=
\p{General_Category=
Paragraph_Separator}) (1)
\p{Zs} \p{Space_Separator} (=
\p{General_Category=Space_Separator})
(17)
\p{Zyyy} \p{Common} (= \p{Script_Extensions=
Common}) (7824)
\p{Zzzz} \p{Unknown} (= \p{Script_Extensions=
Unknown}) (969_350 plus all above-
Unicode code points)
```
###
Legal `\p{}` and `\P{}` constructs that match no characters
Unicode has some property-value pairs that currently don't match anything. This happens generally either because they are obsolete, or they exist for symmetry with other forms, but no language has yet been encoded that uses them. In this version of Unicode, the following match zero code points:
\p{Canonical\_Combining\_Class=Attached\_Below\_Left}
\p{Canonical\_Combining\_Class=CCC133}
\p{Grapheme\_Cluster\_Break=E\_Base}
\p{Grapheme\_Cluster\_Break=E\_Base\_GAZ}
\p{Grapheme\_Cluster\_Break=E\_Modifier}
\p{Grapheme\_Cluster\_Break=Glue\_After\_Zwj}
\p{Word\_Break=E\_Base}
\p{Word\_Break=E\_Base\_GAZ}
\p{Word\_Break=E\_Modifier}
\p{Word\_Break=Glue\_After\_Zwj}
Properties accessible through Unicode::UCD
-------------------------------------------
The value of any Unicode (not including Perl extensions) character property mentioned above for any single code point is available through ["charprop()" in Unicode::UCD](Unicode::UCD#charprop%28%29). ["charprops\_all()" in Unicode::UCD](Unicode::UCD#charprops_all%28%29) returns the values of all the Unicode properties for a given code point.
Besides these, all the Unicode character properties mentioned above (except for those marked as for internal use by Perl) are also accessible by ["prop\_invlist()" in Unicode::UCD](Unicode::UCD#prop_invlist%28%29).
Due to their nature, not all Unicode character properties are suitable for regular expression matches, nor `prop_invlist()`. The remaining non-provisional, non-internal ones are accessible via ["prop\_invmap()" in Unicode::UCD](Unicode::UCD#prop_invmap%28%29) (except for those that this Perl installation hasn't included; see [below for which those are](#Unicode-character-properties-that-are-NOT-accepted-by-Perl)).
For compatibility with other parts of Perl, all the single forms given in the table in the [section above](#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D) are recognized. BUT, there are some ambiguities between some Perl extensions and the Unicode properties, all of which are silently resolved in favor of the official Unicode property. To avoid surprises, you should only use `prop_invmap()` for forms listed in the table below, which omits the non-recommended ones. The affected forms are the Perl single form equivalents of Unicode properties, such as `\p{sc}` being a single-form equivalent of `\p{gc=sc}`, which is treated by `prop_invmap()` as the `Script` property, whose short name is `sc`. The table indicates the current ambiguities in the INFO column, beginning with the word `"NOT"`.
The standard Unicode properties listed below are documented in <http://www.unicode.org/reports/tr44/>; Perl\_Decimal\_Digit is documented in ["prop\_invmap()" in Unicode::UCD](Unicode::UCD#prop_invmap%28%29). The other Perl extensions are in ["Other Properties" in perlunicode](perlunicode#Other-Properties);
The first column in the table is a name for the property; the second column is an alternative name, if any, plus possibly some annotations. The alternative name is the property's full name, unless that would simply repeat the first column, in which case the second column indicates the property's short name (if different). The annotations are given only in the entry for the full name. The annotations for binary properties include a list of the first few ranges that the property matches. To avoid any ambiguity, the SPACE character is represented as `\x20`.
If a property is obsolete, etc, the entry will be flagged with the same characters used in the table in the [section above](#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D), like **D** or **S**.
```
NAME INFO
Age
AHex ASCII_Hex_Digit
All (Perl extension). All code points,
including those above Unicode. Same as
qr/./s. U+0000..infinity
Alnum XPosixAlnum. (Perl extension)
Alpha Alphabetic
Alphabetic (Short: Alpha). [A-Za-z\xaa\xb5\xba\xc0-
\xd6\xd8-\xf6\xf8-\xff], U+0100..02C1,
U+02C6..02D1, U+02E0..02E4, U+02EC, U+02EE
...
Any (Perl extension). All Unicode code
points. U+0000..10FFFF
ASCII Block=Basic_Latin. (Perl extension).
[\x00-\x7f]
ASCII_Hex_Digit (Short: AHex). [0-9A-Fa-f]
Assigned (Perl extension). All assigned code
points. U+0000..0377, U+037A..037F,
U+0384..038A, U+038C, U+038E..03A1,
U+03A3..052F ...
Bc Bidi_Class
Bidi_C Bidi_Control
Bidi_Class (Short: bc)
Bidi_Control (Short: Bidi_C). U+061C, U+200E..200F,
U+202A..202E, U+2066..2069
Bidi_M Bidi_Mirrored
Bidi_Mirrored (Short: Bidi_M). [\(\)<>\[\]\{\}\xab
\xbb], U+0F3A..0F3D, U+169B..169C,
U+2039..203A, U+2045..2046, U+207D..207E
...
Bidi_Mirroring_Glyph (Short: bmg)
Bidi_Paired_Bracket (Short: bpb)
Bidi_Paired_Bracket_Type (Short: bpt)
Blank XPosixBlank. (Perl extension)
Blk Block
Block (Short: blk)
Bmg Bidi_Mirroring_Glyph
Bpb Bidi_Paired_Bracket
Bpt Bidi_Paired_Bracket_Type
Canonical_Combining_Class (Short: ccc)
Case_Folding (Short: cf)
Case_Ignorable (Short: CI). [\'.:\^`\xa8\xad\xaf\xb4
\xb7-\xb8], U+02B0..036F, U+0374..0375,
U+037A, U+0384..0385, U+0387 ...
Cased [A-Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-
\xff], U+0100..01BA, U+01BC..01BF,
U+01C4..0293, U+0295..02B8, U+02C0..02C1
...
Category General_Category
Ccc Canonical_Combining_Class
CE Composition_Exclusion
Cf Case_Folding; NOT 'cf' meaning
'General_Category=Format'
Changes_When_Casefolded (Short: CWCF). [A-Z\xb5\xc0-\xd6\xd8-
\xdf], U+0100, U+0102, U+0104, U+0106,
U+0108 ...
Changes_When_Casemapped (Short: CWCM). [A-Za-z\xb5\xc0-\xd6\xd8-
\xf6\xf8-\xff], U+0100..0137,
U+0139..018C, U+018E..019A, U+019C..01A9,
U+01AC..01B9 ...
Changes_When_Lowercased (Short: CWL). [A-Z\xc0-\xd6\xd8-\xde],
U+0100, U+0102, U+0104, U+0106, U+0108 ...
Changes_When_NFKC_Casefolded (Short: CWKCF). [A-Z\xa0\xa8\xaa
\xad\xaf\xb2-\xb5\xb8-\xba\xbc-\xbe\xc0-
\xd6\xd8-\xdf], U+0100, U+0102, U+0104,
U+0106, U+0108 ...
Changes_When_Titlecased (Short: CWT). [a-z\xb5\xdf-\xf6\xf8-
\xff], U+0101, U+0103, U+0105, U+0107,
U+0109 ...
Changes_When_Uppercased (Short: CWU). [a-z\xb5\xdf-\xf6\xf8-
\xff], U+0101, U+0103, U+0105, U+0107,
U+0109 ...
CI Case_Ignorable
Cntrl XPosixCntrl (=General_Category=Control).
(Perl extension)
Comp_Ex Full_Composition_Exclusion
Composition_Exclusion (Short: CE). U+0958..095F, U+09DC..09DD,
U+09DF, U+0A33, U+0A36, U+0A59..0A5B ...
CWCF Changes_When_Casefolded
CWCM Changes_When_Casemapped
CWKCF Changes_When_NFKC_Casefolded
CWL Changes_When_Lowercased
CWT Changes_When_Titlecased
CWU Changes_When_Uppercased
Dash [\-], U+058A, U+05BE, U+1400, U+1806,
U+2010..2015 ...
Decomposition_Mapping (Short: dm)
Decomposition_Type (Short: dt)
Default_Ignorable_Code_Point (Short: DI). [\xad], U+034F, U+061C,
U+115F..1160, U+17B4..17B5, U+180B..180F
...
Dep Deprecated
Deprecated (Short: Dep). U+0149, U+0673, U+0F77,
U+0F79, U+17A3..17A4, U+206A..206F ...
DI Default_Ignorable_Code_Point
Dia Diacritic
Diacritic (Short: Dia). [\^`\xa8\xaf\xb4\xb7-\xb8],
U+02B0..034E, U+0350..0357, U+035D..0362,
U+0374..0375, U+037A ...
Digit XPosixDigit (=General_Category=
Decimal_Number). (Perl extension)
Dm Decomposition_Mapping
Dt Decomposition_Type
Ea East_Asian_Width
East_Asian_Width (Short: ea)
EBase Emoji_Modifier_Base
EComp Emoji_Component
EMod Emoji_Modifier
Emoji [#*0-9\xa9\xae], U+203C, U+2049, U+2122,
U+2139, U+2194..2199 ...
Emoji_Component (Short: EComp). [#*0-9], U+200D, U+20E3,
U+FE0F, U+1F1E6..1F1FF, U+1F3FB..1F3FF ...
Emoji_Modifier (Short: EMod). U+1F3FB..1F3FF
Emoji_Modifier_Base (Short: EBase). U+261D, U+26F9,
U+270A..270D, U+1F385, U+1F3C2..1F3C4,
U+1F3C7 ...
Emoji_Presentation (Short: EPres). U+231A..231B,
U+23E9..23EC, U+23F0, U+23F3,
U+25FD..25FE, U+2614..2615 ...
EPres Emoji_Presentation
EqUIdeo Equivalent_Unified_Ideograph
Equivalent_Unified_Ideograph (Short: EqUIdeo)
Ext Extender
Extended_Pictographic (Short: ExtPict). [\xa9\xae], U+203C,
U+2049, U+2122, U+2139, U+2194..2199 ...
Extender (Short: Ext). [\xb7], U+02D0..02D1,
U+0640, U+07FA, U+0B55, U+0E46 ...
ExtPict Extended_Pictographic
Full_Composition_Exclusion (Short: Comp_Ex). U+0340..0341,
U+0343..0344, U+0374, U+037E, U+0387,
U+0958..095F ...
Gc General_Category
GCB Grapheme_Cluster_Break
General_Category (Short: gc)
Gr_Base Grapheme_Base
Gr_Ext Grapheme_Extend
Graph XPosixGraph. (Perl extension)
Grapheme_Base (Short: Gr_Base). [\x20-\x7e\xa0-\xac
\xae-\xff], U+0100..02FF, U+0370..0377,
U+037A..037F, U+0384..038A, U+038C ...
Grapheme_Cluster_Break (Short: GCB)
Grapheme_Extend (Short: Gr_Ext). U+0300..036F,
U+0483..0489, U+0591..05BD, U+05BF,
U+05C1..05C2, U+05C4..05C5 ...
Hangul_Syllable_Type (Short: hst)
Hex Hex_Digit
Hex_Digit (Short: Hex). [0-9A-Fa-f], U+FF10..FF19,
U+FF21..FF26, U+FF41..FF46
HorizSpace XPosixBlank. (Perl extension)
Hst Hangul_Syllable_Type
D Hyphen [\-\xad], U+058A, U+1806, U+2010..2011,
U+2E17, U+30FB ... Supplanted by
Line_Break property values; see
www.unicode.org/reports/tr14
ID_Continue (Short: IDC). [0-9A-Z_a-z\xaa\xb5\xb7
\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1, U+02E0..02E4,
U+02EC, U+02EE ...
ID_Start (Short: IDS). [A-Za-z\xaa\xb5\xba\xc0-
\xd6\xd8-\xf6\xf8-\xff], U+0100..02C1,
U+02C6..02D1, U+02E0..02E4, U+02EC, U+02EE
...
IDC ID_Continue
Identifier_Status
Identifier_Type
Ideo Ideographic
Ideographic (Short: Ideo). U+3006..3007,
U+3021..3029, U+3038..303A, U+3400..4DBF,
U+4E00..9FFF, U+F900..FA6D ...
IDS ID_Start
IDS_Binary_Operator (Short: IDSB). U+2FF0..2FF1, U+2FF4..2FFB
IDS_Trinary_Operator (Short: IDST). U+2FF2..2FF3
IDSB IDS_Binary_Operator
IDST IDS_Trinary_Operator
In Present_In. (Perl extension)
Indic_Positional_Category (Short: InPC)
Indic_Syllabic_Category (Short: InSC)
InPC Indic_Positional_Category
InSC Indic_Syllabic_Category
Isc ISO_Comment; NOT 'isc' meaning
'General_Category=Other'
ISO_Comment (Short: isc)
Jg Joining_Group
Join_C Join_Control
Join_Control (Short: Join_C). U+200C..200D
Joining_Group (Short: jg)
Joining_Type (Short: jt)
Jt Joining_Type
Lb Line_Break
Lc Lowercase_Mapping; NOT 'lc' meaning
'General_Category=Cased_Letter'
Line_Break (Short: lb)
LOE Logical_Order_Exception
Logical_Order_Exception (Short: LOE). U+0E40..0E44, U+0EC0..0EC4,
U+19B5..19B7, U+19BA, U+AAB5..AAB6, U+AAB9
...
Lower Lowercase
Lowercase (Short: Lower). [a-z\xaa\xb5\xba\xdf-
\xf6\xf8-\xff], U+0101, U+0103, U+0105,
U+0107, U+0109 ...
Lowercase_Mapping (Short: lc)
Math [+<=>\^\|~\xac\xb1\xd7\xf7], U+03D0..03D2,
U+03D5, U+03F0..03F1, U+03F4..03F6,
U+0606..0608 ...
Na Name
Na1 Unicode_1_Name
Name (Short: na)
Name_Alias
NChar Noncharacter_Code_Point
NFC_QC NFC_Quick_Check
NFC_Quick_Check (Short: NFC_QC)
NFD_QC NFD_Quick_Check
NFD_Quick_Check (Short: NFD_QC)
NFKC_Casefold (Short: NFKC_CF)
NFKC_CF NFKC_Casefold
NFKC_QC NFKC_Quick_Check
NFKC_Quick_Check (Short: NFKC_QC)
NFKD_QC NFKD_Quick_Check
NFKD_Quick_Check (Short: NFKD_QC)
Noncharacter_Code_Point (Short: NChar). U+FDD0..FDEF,
U+FFFE..FFFF, U+1FFFE..1FFFF,
U+2FFFE..2FFFF, U+3FFFE..3FFFF,
U+4FFFE..4FFFF ...
Nt Numeric_Type
Numeric_Type (Short: nt)
Numeric_Value (Short: nv)
Nv Numeric_Value
Pat_Syn Pattern_Syntax
Pat_WS Pattern_White_Space
Pattern_Syntax (Short: Pat_Syn). [!\"#\$\%&\'\(\)*+,\-.
\/:;<=>?\@\[\\\]\^`\{\|\}~\xa1-\xa7\xa9
\xab-\xac\xae\xb0-\xb1\xb6\xbb\xbf\xd7
\xf7], U+2010..2027, U+2030..203E,
U+2041..2053, U+2055..205E, U+2190..245F
...
Pattern_White_Space (Short: Pat_WS). [\t\n\cK\f\r\x20\x85],
U+200E..200F, U+2028..2029
PCM Prepended_Concatenation_Mark
Perl_Decimal_Digit (Perl extension)
PerlSpace PosixSpace. (Perl extension)
PerlWord PosixWord. (Perl extension)
PosixAlnum (Perl extension). [0-9A-Za-z]
PosixAlpha (Perl extension). [A-Za-z]
PosixBlank (Perl extension). [\t\x20]
PosixCntrl (Perl extension). ASCII control
characters. ACK, BEL, BS, CAN, CR, DC1,
DC2, DC3, DC4, DEL, DLE, ENQ, EOM, EOT,
ESC, ETB, ETX, FF, FS, GS, HT, LF, NAK,
NUL, RS, SI, SO, SOH, STX, SUB, SYN, US, VT
PosixDigit (Perl extension). [0-9]
PosixGraph (Perl extension). [!\"#\$\%&\'\(\)*+,\-.
\/0-9:;<=>?\@A-Z\[\\\]\^_`a-z\{\|\}~]
PosixLower (Perl extension). [a-z]
PosixPrint (Perl extension). [\x20-\x7e]
PosixPunct (Perl extension). [!\"#\$\%&\'\(\)*+,\-.
\/:;<=>?\@\[\\\]\^_`\{\|\}~]
PosixSpace (Perl extension). [\t\n\cK\f\r\x20]
PosixUpper (Perl extension). [A-Z]
PosixWord (Perl extension). \w, restricted to
ASCII. [0-9A-Z_a-z]
PosixXDigit ASCII_Hex_Digit. (Perl extension).
[0-9A-Fa-f]
Prepended_Concatenation_Mark (Short: PCM). U+0600..0605, U+06DD,
U+070F, U+0890..0891, U+08E2, U+110BD ...
Present_In (Short: In). (Perl extension)
Print XPosixPrint. (Perl extension)
Punct General_Category=Punctuation. (Perl
extension). [!\"#\%&\'\(\)*,\-.\/:;?\@
\[\\\]_\{\}\xa1\xa7\xab\xb6-\xb7\xbb\xbf],
U+037E, U+0387, U+055A..055F,
U+0589..058A, U+05BE ...
QMark Quotation_Mark
Quotation_Mark (Short: QMark). [\"\'\xab\xbb],
U+2018..201F, U+2039..203A, U+2E42,
U+300C..300F, U+301D..301F ...
Radical U+2E80..2E99, U+2E9B..2EF3, U+2F00..2FD5
Regional_Indicator (Short: RI). U+1F1E6..1F1FF
RI Regional_Indicator
SB Sentence_Break
Sc Script; NOT 'sc' meaning
'General_Category=Currency_Symbol'
Scf Simple_Case_Folding
Script (Short: sc)
Script_Extensions (Short: scx)
Scx Script_Extensions
SD Soft_Dotted
Sentence_Break (Short: SB)
Sentence_Terminal (Short: STerm). [!.?], U+0589,
U+061D..061F, U+06D4, U+0700..0702, U+07F9
...
Sfc Simple_Case_Folding
Simple_Case_Folding (Short: scf)
Simple_Lowercase_Mapping (Short: slc)
Simple_Titlecase_Mapping (Short: stc)
Simple_Uppercase_Mapping (Short: suc)
Slc Simple_Lowercase_Mapping
Soft_Dotted (Short: SD). [i-j], U+012F, U+0249,
U+0268, U+029D, U+02B2 ...
Space White_Space
SpacePerl XPosixSpace. (Perl extension)
Stc Simple_Titlecase_Mapping
STerm Sentence_Terminal
Suc Simple_Uppercase_Mapping
Tc Titlecase_Mapping
Term Terminal_Punctuation
Terminal_Punctuation (Short: Term). [!,.:;?], U+037E, U+0387,
U+0589, U+05C3, U+060C ...
Title Titlecase. (Perl extension)
Titlecase (Short: Title). (Perl extension). (=
\p{Gc=Lt}). U+01C5, U+01C8, U+01CB,
U+01F2, U+1F88..1F8F, U+1F98..1F9F ...
Titlecase_Mapping (Short: tc)
Uc Uppercase_Mapping
UIdeo Unified_Ideograph
Unicode Any. (Perl extension)
Unicode_1_Name (Short: na1)
Unified_Ideograph (Short: UIdeo). U+3400..4DBF,
U+4E00..9FFF, U+FA0E..FA0F, U+FA11,
U+FA13..FA14, U+FA1F ...
Upper Uppercase
Uppercase (Short: Upper). [A-Z\xc0-\xd6\xd8-\xde],
U+0100, U+0102, U+0104, U+0106, U+0108 ...
Uppercase_Mapping (Short: uc)
Variation_Selector (Short: VS). U+180B..180D, U+180F,
U+FE00..FE0F, U+E0100..E01EF
Vertical_Orientation (Short: vo)
VertSpace (Perl extension). \v. [\n\cK\f\r\x85],
U+2028..2029
Vo Vertical_Orientation
VS Variation_Selector
WB Word_Break
White_Space (Short: WSpace). [\t\n\cK\f\r\x20\x85
\xa0], U+1680, U+2000..200A, U+2028..2029,
U+202F, U+205F ...
Word XPosixWord. (Perl extension)
Word_Break (Short: WB)
WSpace White_Space
XDigit XPosixXDigit (=Hex_Digit). (Perl
extension)
XID_Continue (Short: XIDC). [0-9A-Z_a-z\xaa\xb5\xb7
\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1, U+02E0..02E4,
U+02EC, U+02EE ...
XID_Start (Short: XIDS). [A-Za-z\xaa\xb5\xba\xc0-
\xd6\xd8-\xf6\xf8-\xff], U+0100..02C1,
U+02C6..02D1, U+02E0..02E4, U+02EC, U+02EE
...
XIDC XID_Continue
XIDS XID_Start
XPerlSpace XPosixSpace. (Perl extension)
XPosixAlnum (Short: Alnum). (Perl extension).
Alphabetic and (decimal) Numeric. [0-9A-
Za-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-
\xff], U+0100..02C1, U+02C6..02D1,
U+02E0..02E4, U+02EC, U+02EE ...
XPosixAlpha Alphabetic. (Perl extension). [A-Za-z
\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1, U+02E0..02E4,
U+02EC, U+02EE ...
XPosixBlank (Short: Blank). (Perl extension). \h,
Horizontal white space. [\t\x20\xa0],
U+1680, U+2000..200A, U+202F, U+205F,
U+3000
XPosixCntrl General_Category=Control (Short: Cntrl).
(Perl extension). Control characters.
[\x00-\x1f\x7f-\x9f]
XPosixDigit General_Category=Decimal_Number (Short:
Digit). (Perl extension). [0-9] + all
other decimal digits. [0-9],
U+0660..0669, U+06F0..06F9, U+07C0..07C9,
U+0966..096F, U+09E6..09EF ...
XPosixGraph (Short: Graph). (Perl extension).
Characters that are graphical. [!\"#\$
\%&\'\(\)*+,\-.\/0-9:;<=>?\@A-Z\[\\\]
\^_`a-z\{\|\}~\xa1-\xff], U+0100..0377,
U+037A..037F, U+0384..038A, U+038C,
U+038E..03A1 ...
XPosixLower Lowercase. (Perl extension). [a-z\xaa
\xb5\xba\xdf-\xf6\xf8-\xff], U+0101,
U+0103, U+0105, U+0107, U+0109 ...
XPosixPrint (Short: Print). (Perl extension).
Characters that are graphical plus space
characters (but no controls). [\x20-\x7e
\xa0-\xff], U+0100..0377, U+037A..037F,
U+0384..038A, U+038C, U+038E..03A1 ...
XPosixPunct (Perl extension). \p{Punct} + ASCII-range
\p{Symbol}. [!\"#\$\%&\'\(\)*+,\-.\/:;<=
>?\@\[\\\]\^_`\{\|\}~\xa1\xa7\xab\xb6-
\xb7\xbb\xbf], U+037E, U+0387,
U+055A..055F, U+0589..058A, U+05BE ...
XPosixSpace (Perl extension). \s including beyond
ASCII and vertical tab. [\t\n\cK\f\r\x20
\x85\xa0], U+1680, U+2000..200A,
U+2028..2029, U+202F, U+205F ...
XPosixUpper Uppercase. (Perl extension). [A-Z\xc0-
\xd6\xd8-\xde], U+0100, U+0102, U+0104,
U+0106, U+0108 ...
XPosixWord (Short: Word). (Perl extension). \w,
including beyond ASCII; = \p{Alnum} + \pM
+ \p{Pc} + \p{Join_Control}. [0-9A-Z_a-z
\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\xff],
U+0100..02C1, U+02C6..02D1, U+02E0..02E4,
U+02EC, U+02EE ...
XPosixXDigit Hex_Digit (Short: XDigit). (Perl
extension). [0-9A-Fa-f], U+FF10..FF19,
U+FF21..FF26, U+FF41..FF46
```
Properties accessible through other means
------------------------------------------
Certain properties are accessible also via core function calls. These are:
```
Lowercase_Mapping lc() and lcfirst()
Titlecase_Mapping ucfirst()
Uppercase_Mapping uc()
```
Also, Case\_Folding is accessible through the `/i` modifier in regular expressions, the `\F` transliteration escape, and the `[fc](perlfunc#fc)` operator.
Besides being able to say `\p{Name=...}`, the Name and Name\_Aliases properties are accessible through the `\N{}` interpolation in double-quoted strings and regular expressions; and functions `charnames::viacode()`, `charnames::vianame()`, and `charnames::string_vianame()` (which require a `use charnames ();` to be specified.
Finally, most properties related to decomposition are accessible via <Unicode::Normalize>.
Unicode character properties that are NOT accepted by Perl
-----------------------------------------------------------
Perl will generate an error for a few character properties in Unicode when used in a regular expression. The non-Unihan ones are listed below, with the reasons they are not accepted, perhaps with work-arounds. The short names for the properties are listed enclosed in (parentheses). As described after the list, an installation can change the defaults and choose to accept any of these. The list is machine generated based on the choices made for the installation that generated this document.
*Expands\_On\_NFC* (XO\_NFC)
*Expands\_On\_NFD* (XO\_NFD)
*Expands\_On\_NFKC* (XO\_NFKC)
*Expands\_On\_NFKD* (XO\_NFKD) Deprecated by Unicode. These are characters that expand to more than one character in the specified normalization form, but whether they actually take up more bytes or not depends on the encoding being used. For example, a UTF-8 encoded character may expand to a different number of bytes than a UTF-32 encoded character.
*Grapheme\_Link* (Gr\_Link) Duplicates ccc=vr (Canonical\_Combining\_Class=Virama)
*Jamo\_Short\_Name* (JSN)
*Other\_Alphabetic* (OAlpha)
*Other\_Default\_Ignorable\_Code\_Point* (ODI)
*Other\_Grapheme\_Extend* (OGr\_Ext)
*Other\_ID\_Continue* (OIDC)
*Other\_ID\_Start* (OIDS)
*Other\_Lowercase* (OLower)
*Other\_Math* (OMath)
*Other\_Uppercase* (OUpper) Used by Unicode internally for generating other properties and not intended to be used stand-alone
*Script=Katakana\_Or\_Hiragana* (sc=Hrkt) Obsolete. All code points previously matched by this have been moved to "Script=Common". Consider instead using "Script\_Extensions=Katakana" or "Script\_Extensions=Hiragana" (or both)
*Script\_Extensions=Katakana\_Or\_Hiragana* (scx=Hrkt) All code points that would be matched by this are matched by either "Script\_Extensions=Katakana" or "Script\_Extensions=Hiragana"
An installation can choose to allow any of these to be matched by downloading the Unicode database from <http://www.unicode.org/Public/> to `$Config{privlib}`/*unicore/* in the Perl source tree, changing the controlling lists contained in the program `$Config{privlib}`/*unicore/mktables* and then re-compiling and installing. (`%Config` is available from the Config module).
Also, perl can be recompiled to operate on an earlier version of the Unicode standard. Further information is at `$Config{privlib}`/*unicore/README.perl*.
Other information in the Unicode data base
-------------------------------------------
The Unicode data base is delivered in two different formats. The XML version is valid for more modern Unicode releases. The other version is a collection of files. The two are intended to give equivalent information. Perl uses the older form; this allows you to recompile Perl to use early Unicode releases.
The only non-character property that Perl currently supports is Named Sequences, in which a sequence of code points is given a name and generally treated as a single entity. (Perl supports these via the `\N{...}` double-quotish construct, ["charnames::string\_vianame(name)" in charnames](charnames#charnames%3A%3Astring_vianame%28name%29), and ["namedseq()" in Unicode::UCD](Unicode::UCD#namedseq%28%29).
Below is a list of the files in the Unicode data base that Perl doesn't currently use, along with very brief descriptions of their purposes. Some of the names of the files have been shortened from those that Unicode uses, in order to allow them to be distinguishable from similarly named files on file systems for which only the first 8 characters of a name are significant.
*auxiliary/GraphemeBreakTest.html*
*auxiliary/LineBreakTest.html*
*auxiliary/SentenceBreakTest.html*
*auxiliary/WordBreakTest.html*
Documentation of validation Tests
*BidiCharacterTest.txt*
*BidiTest.txt*
*NormTest.txt*
Validation Tests
*CJKRadicals.txt*
Maps the kRSUnicode property values to corresponding code points
*emoji/ReadMe.txt*
*ReadMe.txt*
Documentation
*EmojiSources.txt*
Maps certain Unicode code points to their legacy Japanese cell-phone values
*extracted/DName.txt*
This file adds no new information not already present in other files
*Index.txt*
Alphabetical index of Unicode characters
*NamedSqProv.txt*
Named sequences proposed for inclusion in a later version of the Unicode Standard; if you need them now, you can append this file to *NamedSequences.txt* and recompile perl
*NamesList.html*
Describes the format and contents of *NamesList.txt*
*NamesList.txt*
Annotated list of characters
*NormalizationCorrections.txt*
Documentation of corrections already incorporated into the Unicode data base
*NushuSources.txt*
Specifies source material for Nushu characters
*StandardizedVariants.html*
Obsoleted as of Unicode 9.0, but previously provided a visual display of the standard variant sequences derived from *StandardizedVariants.txt*.
*StandardizedVariants.txt*
Certain glyph variations for character display are standardized. This lists the non-Unihan ones; the Unihan ones are also not used by Perl, and are in a separate Unicode data base <http://www.unicode.org/ivd>
*TangutSources.txt*
Specifies source mappings for Tangut ideographs and components. This data file also includes informative radical-stroke values that are used internally by Unicode
*USourceData.txt*
Documentation of status and cross reference of proposals for encoding by Unicode of Unihan characters
*USourceGlyphs.pdf*
Pictures of the characters in *USourceData.txt*
SEE ALSO
---------
<http://www.unicode.org/reports/tr44/>
<perlrecharclass>
<perlunicode>
| programming_docs |
perl cpan cpan
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Options](#Options)
+ [Examples](#Examples)
+ [Environment variables](#Environment-variables)
* [EXIT VALUES](#EXIT-VALUES)
* [TO DO](#TO-DO)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [SOURCE AVAILABILITY](#SOURCE-AVAILABILITY)
* [CREDITS](#CREDITS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
cpan - easily interact with CPAN from the command line
SYNOPSIS
--------
```
# with arguments and no switches, installs specified modules
cpan module_name [ module_name ... ]
# with switches, installs modules with extra behavior
cpan [-cfFimtTw] module_name [ module_name ... ]
# use local::lib
cpan -I module_name [ module_name ... ]
# one time mirror override for faster mirrors
cpan -p ...
# with just the dot, install from the distribution in the
# current directory
cpan .
# without arguments, starts CPAN.pm shell
cpan
# without arguments, but some switches
cpan [-ahpruvACDLOPX]
```
DESCRIPTION
-----------
This script provides a command interface (not a shell) to CPAN. At the moment it uses CPAN.pm to do the work, but it is not a one-shot command runner for CPAN.pm.
### Options
-a Creates a CPAN.pm autobundle with CPAN::Shell->autobundle.
-A module [ module ... ] Shows the primary maintainers for the specified modules.
-c module Runs a `make clean` in the specified module's directories.
-C module [ module ... ] Show the *Changes* files for the specified modules
-D module [ module ... ] Show the module details. This prints one line for each out-of-date module (meaning, modules locally installed but have newer versions on CPAN). Each line has three columns: module name, local version, and CPAN version.
-f Force the specified action, when it normally would have failed. Use this to install a module even if its tests fail. When you use this option, -i is not optional for installing a module when you need to force it:
```
% cpan -f -i Module::Foo
```
-F Turn off CPAN.pm's attempts to lock anything. You should be careful with this since you might end up with multiple scripts trying to muck in the same directory. This isn't so much of a concern if you're loading a special config with `-j`, and that config sets up its own work directories.
-g module [ module ... ] Downloads to the current directory the latest distribution of the module.
-G module [ module ... ] UNIMPLEMENTED
Download to the current directory the latest distribution of the modules, unpack each distribution, and create a git repository for each distribution.
If you want this feature, check out Yanick Champoux's `Git::CPAN::Patch` distribution.
-h Print a help message and exit. When you specify `-h`, it ignores all of the other options and arguments.
-i module [ module ... ] Install the specified modules. With no other switches, this switch is implied.
-I Load `local::lib` (think like `-I` for loading lib paths). Too bad `-l` was already taken.
-j Config.pm Load the file that has the CPAN configuration data. This should have the same format as the standard *CPAN/Config.pm* file, which defines `$CPAN::Config` as an anonymous hash.
-J Dump the configuration in the same format that CPAN.pm uses. This is useful for checking the configuration as well as using the dump as a starting point for a new, custom configuration.
-l List all installed modules with their versions
-L author [ author ... ] List the modules by the specified authors.
-m Make the specified modules.
-M mirror1,mirror2,... A comma-separated list of mirrors to use for just this run. The `-P` option can find them for you automatically.
-n Do a dry run, but don't actually install anything. (unimplemented)
-O Show the out-of-date modules.
-p Ping the configured mirrors and print a report
-P Find the best mirrors you could be using and use them for the current session.
-r Recompiles dynamically loaded modules with CPAN::Shell->recompile.
-s Drop in the CPAN.pm shell. This command does this automatically if you don't specify any arguments.
-t module [ module ... ] Run a `make test` on the specified modules.
-T Do not test modules. Simply install them.
-u Upgrade all installed modules. Blindly doing this can really break things, so keep a backup.
-v Print the script version and CPAN.pm version then exit.
-V Print detailed information about the cpan client.
-w UNIMPLEMENTED
Turn on cpan warnings. This checks various things, like directory permissions, and tells you about problems you might have.
-x module [ module ... ] Find close matches to the named modules that you think you might have mistyped. This requires the optional installation of Text::Levenshtein or Text::Levenshtein::Damerau.
-X Dump all the namespaces to standard output.
### Examples
```
# print a help message
cpan -h
# print the version numbers
cpan -v
# create an autobundle
cpan -a
# recompile modules
cpan -r
# upgrade all installed modules
cpan -u
# install modules ( sole -i is optional )
cpan -i Netscape::Booksmarks Business::ISBN
# force install modules ( must use -i )
cpan -fi CGI::Minimal URI
# install modules but without testing them
cpan -Ti CGI::Minimal URI
```
###
Environment variables
There are several components in CPAN.pm that use environment variables. The build tools, <ExtUtils::MakeMaker> and <Module::Build> use some, while others matter to the levels above them. Some of these are specified by the Perl Toolchain Gang:
Lancaster Consensus: <https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/lancaster-consensus.md>
Oslo Consensus: <https://github.com/Perl-Toolchain-Gang/toolchain-site/blob/master/oslo-consensus.md>
NONINTERACTIVE\_TESTING Assume no one is paying attention and skips prompts for distributions that do that correctly. `cpan(1)` sets this to `1` unless it already has a value (even if that value is false).
PERL\_MM\_USE\_DEFAULT Use the default answer for a prompted questions. `cpan(1)` sets this to `1` unless it already has a value (even if that value is false).
CPAN\_OPTS As with `PERL5OPT`, a string of additional `cpan(1)` options to add to those you specify on the command line.
CPANSCRIPT\_LOGLEVEL The log level to use, with either the embedded, minimal logger or <Log::Log4perl> if it is installed. Possible values are the same as the `Log::Log4perl` levels: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, and `FATAL`. The default is `INFO`.
GIT\_COMMAND The path to the `git` binary to use for the Git features. The default is `/usr/local/bin/git`.
EXIT VALUES
------------
The script exits with zero if it thinks that everything worked, or a positive number if it thinks that something failed. Note, however, that in some cases it has to divine a failure by the output of things it does not control. For now, the exit codes are vague:
```
1 An unknown error
2 The was an external problem
4 There was an internal problem with the script
8 A module failed to install
```
TO DO
------
\* one shot configuration values from the command line
BUGS
----
\* none noted
SEE ALSO
---------
Most behaviour, including environment variables and configuration, comes directly from CPAN.pm.
SOURCE AVAILABILITY
--------------------
This code is in Github in the CPAN.pm repository:
```
https://github.com/andk/cpanpm
```
The source used to be tracked separately in another GitHub repo, but the canonical source is now in the above repo.
CREDITS
-------
Japheth Cleaver added the bits to allow a forced install (-f).
Jim Brandt suggest and provided the initial implementation for the up-to-date and Changes features.
Adam Kennedy pointed out that exit() causes problems on Windows where this script ends up with a .bat extension
AUTHOR
------
brian d foy, `<[email protected]>`
COPYRIGHT
---------
Copyright (c) 2001-2015, brian d foy, All Rights Reserved.
You may redistribute this under the same terms as Perl itself.
perl ExtUtils::Constant ExtUtils::Constant
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [FUNCTIONS](#FUNCTIONS)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Constant - generate XS code to import C header constants
SYNOPSIS
--------
```
use ExtUtils::Constant qw (WriteConstants);
WriteConstants(
NAME => 'Foo',
NAMES => [qw(FOO BAR BAZ)],
);
# Generates wrapper code to make the values of the constants FOO BAR BAZ
# available to perl
```
DESCRIPTION
-----------
ExtUtils::Constant facilitates generating C and XS wrapper code to allow perl modules to AUTOLOAD constants defined in C library header files. It is principally used by the `h2xs` utility, on which this code is based. It doesn't contain the routines to scan header files to extract these constants.
USAGE
-----
Generally one only needs to call the `WriteConstants` function, and then
```
#include "const-c.inc"
```
in the C section of `Foo.xs`
```
INCLUDE: const-xs.inc
```
in the XS section of `Foo.xs`.
For greater flexibility use `constant_types()`, `C_constant` and `XS_constant`, with which `WriteConstants` is implemented.
Currently this module understands the following types. h2xs may only know a subset. The sizes of the numeric types are chosen by the `Configure` script at compile time.
IV signed integer, at least 32 bits.
UV unsigned integer, the same size as *IV*
NV floating point type, probably `double`, possibly `long double`
PV NUL terminated string, length will be determined with `strlen`
PVN A fixed length thing, given as a [pointer, length] pair. If you know the length of a string at compile time you may use this instead of *PV*
SV A **mortal** SV.
YES Truth. (`PL_sv_yes`) The value is not needed (and ignored).
NO Defined Falsehood. (`PL_sv_no`) The value is not needed (and ignored).
UNDEF `undef`. The value of the macro is not needed.
FUNCTIONS
---------
constant\_types A function returning a single scalar with `#define` definitions for the constants used internally between the generated C and XS functions.
XS\_constant PACKAGE, TYPES, XS\_SUBNAME, C\_SUBNAME A function to generate the XS code to implement the perl subroutine *PACKAGE*::constant used by *PACKAGE*::AUTOLOAD to load constants. This XS code is a wrapper around a C subroutine usually generated by `C_constant`, and usually named `constant`.
*TYPES* should be given either as a comma separated list of types that the C subroutine `constant` will generate or as a reference to a hash. It should be the same list of types as `C_constant` was given. [Otherwise `XS_constant` and `C_constant` may have different ideas about the number of parameters passed to the C function `constant`]
You can call the perl visible subroutine something other than `constant` if you give the parameter *XS\_SUBNAME*. The C subroutine it calls defaults to the name of the perl visible subroutine, unless you give the parameter *C\_SUBNAME*.
autoload PACKAGE, VERSION, AUTOLOADER A function to generate the AUTOLOAD subroutine for the module *PACKAGE* *VERSION* is the perl version the code should be backwards compatible with. It defaults to the version of perl running the subroutine. If *AUTOLOADER* is true, the AUTOLOAD subroutine falls back on AutoLoader::AUTOLOAD for all names that the constant() routine doesn't recognise.
WriteMakefileSnippet WriteMakefileSnippet ATTRIBUTE => VALUE [, ...]
A function to generate perl code for Makefile.PL that will regenerate the constant subroutines. Parameters are named as passed to `WriteConstants`, with the addition of `INDENT` to specify the number of leading spaces (default 2).
Currently only `INDENT`, `NAME`, `DEFAULT_TYPE`, `NAMES`, `C_FILE` and `XS_FILE` are recognised.
WriteConstants ATTRIBUTE => VALUE [, ...] Writes a file of C code and a file of XS code which you should `#include` and `INCLUDE` in the C and XS sections respectively of your module's XS code. You probably want to do this in your `Makefile.PL`, so that you can easily edit the list of constants without touching the rest of your module. The attributes supported are
NAME Name of the module. This must be specified
DEFAULT\_TYPE The default type for the constants. If not specified `IV` is assumed.
BREAKOUT\_AT The names of the constants are grouped by length. Generate child subroutines for each group with this number or more names in.
NAMES An array of constants' names, either scalars containing names, or hashrefs as detailed in ["C\_constant"](#C_constant).
PROXYSUBS If true, uses proxy subs. See <ExtUtils::Constant::ProxySubs>.
C\_FH A filehandle to write the C code to. If not given, then *C\_FILE* is opened for writing.
C\_FILE The name of the file to write containing the C code. The default is `const-c.inc`. The `-` in the name ensures that the file can't be mistaken for anything related to a legitimate perl package name, and not naming the file `.c` avoids having to override Makefile.PL's `.xs` to `.c` rules.
XS\_FH A filehandle to write the XS code to. If not given, then *XS\_FILE* is opened for writing.
XS\_FILE The name of the file to write containing the XS code. The default is `const-xs.inc`.
XS\_SUBNAME The perl visible name of the XS subroutine generated which will return the constants. The default is `constant`.
C\_SUBNAME The name of the C subroutine generated which will return the constants. The default is *XS\_SUBNAME*. Child subroutines have `_` and the name length appended, so constants with 10 character names would be in `constant_10` with the default *XS\_SUBNAME*.
AUTHOR
------
Nicholas Clark <[email protected]> based on the code in `h2xs` by Larry Wall and others
perl Hash::Util Hash::Util
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Restricted hashes](#Restricted-hashes)
+ [Operating on references to hashes.](#Operating-on-references-to-hashes.)
* [CAVEATS](#CAVEATS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Hash::Util - A selection of general-utility hash subroutines
SYNOPSIS
--------
```
# Restricted hashes
use Hash::Util qw(
fieldhash fieldhashes
all_keys
lock_keys unlock_keys
lock_value unlock_value
lock_hash unlock_hash
lock_keys_plus
hash_locked hash_unlocked
hashref_locked hashref_unlocked
hidden_keys legal_keys
lock_ref_keys unlock_ref_keys
lock_ref_value unlock_ref_value
lock_hashref unlock_hashref
lock_ref_keys_plus
hidden_ref_keys legal_ref_keys
hash_seed hash_value hv_store
bucket_stats bucket_info bucket_array
lock_hash_recurse unlock_hash_recurse
lock_hashref_recurse unlock_hashref_recurse
hash_traversal_mask
);
%hash = (foo => 42, bar => 23);
# Ways to restrict a hash
lock_keys(%hash);
lock_keys(%hash, @keyset);
lock_keys_plus(%hash, @additional_keys);
# Ways to inspect the properties of a restricted hash
my @legal = legal_keys(%hash);
my @hidden = hidden_keys(%hash);
my $ref = all_keys(%hash,@keys,@hidden);
my $is_locked = hash_locked(%hash);
# Remove restrictions on the hash
unlock_keys(%hash);
# Lock individual values in a hash
lock_value (%hash, 'foo');
unlock_value(%hash, 'foo');
# Ways to change the restrictions on both keys and values
lock_hash (%hash);
unlock_hash(%hash);
my $hashes_are_randomised = hash_seed() !~ /^\0+$/;
my $int_hash_value = hash_value( 'string' );
my $mask= hash_traversal_mask(%hash);
hash_traversal_mask(%hash,1234);
```
DESCRIPTION
-----------
`Hash::Util` and `Hash::Util::FieldHash` contain special functions for manipulating hashes that don't really warrant a keyword.
`Hash::Util` contains a set of functions that support [restricted hashes](#Restricted-hashes). These are described in this document. `Hash::Util::FieldHash` contains an (unrelated) set of functions that support the use of hashes in *inside-out classes*, described in <Hash::Util::FieldHash>.
By default `Hash::Util` does not export anything.
###
Restricted hashes
5.8.0 introduces the ability to restrict a hash to a certain set of keys. No keys outside of this set can be added. It also introduces the ability to lock an individual key so it cannot be deleted and the ability to ensure that an individual value cannot be changed.
This is intended to largely replace the deprecated pseudo-hashes.
**lock\_keys** **unlock\_keys**
```
lock_keys(%hash);
lock_keys(%hash, @keys);
```
Restricts the given %hash's set of keys to @keys. If @keys is not given it restricts it to its current keyset. No more keys can be added. delete() and exists() will still work, but will not alter the set of allowed keys. **Note**: the current implementation prevents the hash from being bless()ed while it is in a locked state. Any attempt to do so will raise an exception. Of course you can still bless() the hash before you call lock\_keys() so this shouldn't be a problem.
```
unlock_keys(%hash);
```
Removes the restriction on the %hash's keyset.
**Note** that if any of the values of the hash have been locked they will not be unlocked after this sub executes.
Both routines return a reference to the hash operated on.
**lock\_keys\_plus**
```
lock_keys_plus(%hash,@additional_keys)
```
Similar to `lock_keys()`, with the difference being that the optional key list specifies keys that may or may not be already in the hash. Essentially this is an easier way to say
```
lock_keys(%hash,@additional_keys,keys %hash);
```
Returns a reference to %hash
**lock\_value** **unlock\_value**
```
lock_value (%hash, $key);
unlock_value(%hash, $key);
```
Locks and unlocks the value for an individual key of a hash. The value of a locked key cannot be changed.
Unless %hash has already been locked the key/value could be deleted regardless of this setting.
Returns a reference to the %hash.
**lock\_hash** **unlock\_hash**
```
lock_hash(%hash);
```
lock\_hash() locks an entire hash, making all keys and values read-only. No value can be changed, no keys can be added or deleted.
```
unlock_hash(%hash);
```
unlock\_hash() does the opposite of lock\_hash(). All keys and values are made writable. All values can be changed and keys can be added and deleted.
Returns a reference to the %hash.
**lock\_hash\_recurse** **unlock\_hash\_recurse**
```
lock_hash_recurse(%hash);
```
lock\_hash() locks an entire hash and any hashes it references recursively, making all keys and values read-only. No value can be changed, no keys can be added or deleted.
This method **only** recurses into hashes that are referenced by another hash. Thus a Hash of Hashes (HoH) will all be restricted, but a Hash of Arrays of Hashes (HoAoH) will only have the top hash restricted.
```
unlock_hash_recurse(%hash);
```
unlock\_hash\_recurse() does the opposite of lock\_hash\_recurse(). All keys and values are made writable. All values can be changed and keys can be added and deleted. Identical recursion restrictions apply as to lock\_hash\_recurse().
Returns a reference to the %hash.
**hashref\_locked** **hash\_locked**
```
hashref_locked(\%hash) and print "Hash is locked!\n";
hash_locked(%hash) and print "Hash is locked!\n";
```
Returns true if the hash and its keys are locked.
**hashref\_unlocked** **hash\_unlocked**
```
hashref_unlocked(\%hash) and print "Hash is unlocked!\n";
hash_unlocked(%hash) and print "Hash is unlocked!\n";
```
Returns true if the hash and its keys are unlocked.
**legal\_keys**
```
my @keys = legal_keys(%hash);
```
Returns the list of the keys that are legal in a restricted hash. In the case of an unrestricted hash this is identical to calling keys(%hash).
**hidden\_keys**
```
my @keys = hidden_keys(%hash);
```
Returns the list of the keys that are legal in a restricted hash but do not have a value associated to them. Thus if 'foo' is a "hidden" key of the %hash it will return false for both `defined` and `exists` tests.
In the case of an unrestricted hash this will return an empty list.
**NOTE** this is an experimental feature that is heavily dependent on the current implementation of restricted hashes. Should the implementation change, this routine may become meaningless, in which case it will return an empty list.
**all\_keys**
```
all_keys(%hash,@keys,@hidden);
```
Populates the arrays @keys with the all the keys that would pass an `exists` tests, and populates @hidden with the remaining legal keys that have not been utilized.
Returns a reference to the hash.
In the case of an unrestricted hash this will be equivalent to
```
$ref = do {
@keys = keys %hash;
@hidden = ();
\%hash
};
```
**NOTE** this is an experimental feature that is heavily dependent on the current implementation of restricted hashes. Should the implementation change this routine may become meaningless in which case it will behave identically to how it would behave on an unrestricted hash.
**hash\_seed**
```
my $hash_seed = hash_seed();
```
hash\_seed() returns the seed bytes used to randomise hash ordering.
**Note that the hash seed is sensitive information**: by knowing it one can craft a denial-of-service attack against Perl code, even remotely, see ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks) for more information. **Do not disclose the hash seed** to people who don't need to know it. See also ["PERL\_HASH\_SEED\_DEBUG" in perlrun](perlrun#PERL_HASH_SEED_DEBUG).
Prior to Perl 5.17.6 this function returned a UV, it now returns a string, which may be of nearly any size as determined by the hash function your Perl has been built with. Possible sizes may be but are not limited to 4 bytes (for most hash algorithms) and 16 bytes (for siphash).
**hash\_value**
```
my $hash_value = hash_value($string);
my $hash_value = hash_value($string, $seed);
```
`hash_value($string)` returns the current perl's internal hash value for a given string. `hash_value($string, $seed)` returns the hash value as if computed with a different seed. If the custom seed is too short, the function errors out. The minimum length of the seed is implementation-dependent.
Returns a 32-bit integer representing the hash value of the string passed in. The 1-parameter value is only reliable for the lifetime of the process. It may be different depending on invocation, environment variables, perl version, architectures, and build options.
**Note that the hash value of a given string is sensitive information**: by knowing it one can deduce the hash seed which in turn can allow one to craft a denial-of-service attack against Perl code, even remotely, see ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks) for more information. **Do not disclose the hash value of a string** to people who don't need to know it. See also ["PERL\_HASH\_SEED\_DEBUG" in perlrun](perlrun#PERL_HASH_SEED_DEBUG).
**bucket\_info** Return a set of basic information about a hash.
```
my ($keys, $buckets, $used, @length_counts)= bucket_info($hash);
```
Fields are as follows:
```
0: Number of keys in the hash
1: Number of buckets in the hash
2: Number of used buckets in the hash
rest : list of counts, Kth element is the number of buckets
with K keys in it.
```
See also bucket\_stats() and bucket\_array().
**bucket\_stats** Returns a list of statistics about a hash.
```
my ($keys, $buckets, $used, $quality, $utilization_ratio,
$collision_pct, $mean, $stddev, @length_counts)
= bucket_stats($hashref);
```
Fields are as follows:
```
0: Number of keys in the hash
1: Number of buckets in the hash
2: Number of used buckets in the hash
3: Hash Quality Score
4: Percent of buckets used
5: Percent of keys which are in collision
6: Mean bucket length of occupied buckets
7: Standard Deviation of bucket lengths of occupied buckets
rest : list of counts, Kth element is the number of buckets
with K keys in it.
```
See also bucket\_info() and bucket\_array().
Note that Hash Quality Score would be 1 for an ideal hash, numbers close to and below 1 indicate good hashing, and number significantly above indicate a poor score. In practice it should be around 0.95 to 1.05. It is defined as:
```
$score= sum( $count[$length] * ($length * ($length + 1) / 2) )
/
( ( $keys / 2 * $buckets ) *
( $keys + ( 2 * $buckets ) - 1 ) )
```
The formula is from the Red Dragon book (reformulated to use the data available) and is documented at <http://www.strchr.com/hash_functions>
**bucket\_array**
```
my $array= bucket_array(\%hash);
```
Returns a packed representation of the bucket array associated with a hash. Each element of the array is either an integer K, in which case it represents K empty buckets, or a reference to another array which contains the keys that are in that bucket.
**Note that the information returned by bucket\_array is sensitive information**: by knowing it one can directly attack perl's hash function which in turn may allow one to craft a denial-of-service attack against Perl code, even remotely, see ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks) for more information. **Do not disclose the output of this function** to people who don't need to know it. See also ["PERL\_HASH\_SEED\_DEBUG" in perlrun](perlrun#PERL_HASH_SEED_DEBUG). This function is provided strictly for debugging and diagnostics purposes only, it is hard to imagine a reason why it would be used in production code.
**bucket\_stats\_formatted**
```
print bucket_stats_formatted($hashref);
```
Return a formatted report of the information returned by bucket\_stats(). An example report looks like this:
```
Keys: 50 Buckets: 33/64 Quality-Score: 1.01 (Good)
Utilized Buckets: 51.56% Optimal: 78.12% Keys In Collision: 34.00%
Chain Length - mean: 1.52 stddev: 0.66
Buckets 64 [0000000000000000000000000000000111111111111111111122222222222333]
Len 0 Pct: 48.44 [###############################]
Len 1 Pct: 29.69 [###################]
Len 2 Pct: 17.19 [###########]
Len 3 Pct: 4.69 [###]
Keys 50 [11111111111111111111111111111111122222222222222333]
Pos 1 Pct: 66.00 [#################################]
Pos 2 Pct: 28.00 [##############]
Pos 3 Pct: 6.00 [###]
```
The first set of stats gives some summary statistical information, including the quality score translated into "Good", "Poor" and "Bad", (score<=1.05, score<=1.2, score>1.2). See the documentation in bucket\_stats() for more details.
The two sets of barcharts give stats and a visual indication of performance of the hash.
The first gives data on bucket chain lengths and provides insight on how much work a fetch \*miss\* will take. In this case we have to inspect every item in a bucket before we can be sure the item is not in the list. The performance for an insert is equivalent to this case, as is a delete where the item is not in the hash.
The second gives data on how many keys are at each depth in the chain, and gives an idea of how much work a fetch \*hit\* will take. The performance for an update or delete of an item in the hash is equivalent to this case.
Note that these statistics are summary only. Actual performance will depend on real hit/miss ratios accessing the hash. If you are concerned by hit ratios you are recommended to "oversize" your hash by using something like:
```
keys(%hash)= keys(%hash) << $k;
```
With $k chosen carefully, and likely to be a small number like 1 or 2. In theory the larger the bucket array the less chance of collision.
**hv\_store**
```
my $sv = 0;
hv_store(%hash,$key,$sv) or die "Failed to alias!";
$hash{$key} = 1;
print $sv; # prints 1
```
Stores an alias to a variable in a hash instead of copying the value.
**hash\_traversal\_mask** As of Perl 5.18 every hash has its own hash traversal order, and this order changes every time a new element is inserted into the hash. This functionality is provided by maintaining an unsigned integer mask (U32) which is xor'ed with the actual bucket id during a traversal of the hash buckets using keys(), values() or each().
You can use this subroutine to get and set the traversal mask for a specific hash. Setting the mask ensures that a given hash will produce the same key order. **Note** that this does **not** guarantee that **two** hashes will produce the same key order for the same hash seed and traversal mask, items that collide into one bucket may have different orders regardless of this setting.
**bucket\_ratio** This function behaves the same way that scalar(%hash) behaved prior to Perl 5.25. Specifically if the hash is tied, then it calls the SCALAR tied hash method, if untied then if the hash is empty it return 0, otherwise it returns a string containing the number of used buckets in the hash, followed by a slash, followed by the total number of buckets in the hash.
```
my %hash=("foo"=>1);
print Hash::Util::bucket_ratio(%hash); # prints "1/8"
```
**used\_buckets** This function returns the count of used buckets in the hash. It is expensive to calculate and the value is NOT cached, so avoid use of this function in production code.
**num\_buckets** This function returns the total number of buckets the hash holds, or would hold if the array were created. (When a hash is freshly created the array may not be allocated even though this value will be non-zero.)
###
Operating on references to hashes.
Most subroutines documented in this module have equivalent versions that operate on references to hashes instead of native hashes. The following is a list of these subs. They are identical except in name and in that instead of taking a %hash they take a $hashref, and additionally are not prototyped.
lock\_ref\_keys unlock\_ref\_keys lock\_ref\_keys\_plus lock\_ref\_value unlock\_ref\_value lock\_hashref unlock\_hashref lock\_hashref\_recurse unlock\_hashref\_recurse hash\_ref\_unlocked legal\_ref\_keys hidden\_ref\_keys CAVEATS
-------
Note that the trapping of the restricted operations is not atomic: for example
```
eval { %hash = (illegal_key => 1) }
```
leaves the `%hash` empty rather than with its original contents.
BUGS
----
The interface exposed by this module is very close to the current implementation of restricted hashes. Over time it is expected that this behavior will be extended and the interface abstracted further.
AUTHOR
------
Michael G Schwern <[email protected]> on top of code by Nick Ing-Simmons and Jeffrey Friedl.
hv\_store() is from Array::RefElem, Copyright 2000 Gisle Aas.
Additional code by Yves Orton.
Description of `hash_value($string, $seed)` by Christopher Yeleighton <[email protected]>
SEE ALSO
---------
<Scalar::Util>, <List::Util> and ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks).
<Hash::Util::FieldHash>.
| programming_docs |
perl B::Op_private B::Op\_private
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [%bits](#%25bits)
+ [%defines](#%25defines)
+ [%labels](#%25labels)
+ [%ops\_using](#%25ops_using)
NAME
----
B::Op\_private - OP op\_private flag definitions
SYNOPSIS
--------
```
use B::Op_private;
# flag details for bit 7 of OP_AELEM's op_private:
my $name = $B::Op_private::bits{aelem}{7}; # OPpLVAL_INTRO
my $value = $B::Op_private::defines{$name}; # 128
my $label = $B::Op_private::labels{$name}; # LVINTRO
# the bit field at bits 5..6 of OP_AELEM's op_private:
my $bf = $B::Op_private::bits{aelem}{6};
my $mask = $bf->{bitmask}; # etc
```
DESCRIPTION
-----------
This module provides four global hashes:
```
%B::Op_private::bits
%B::Op_private::defines
%B::Op_private::labels
%B::Op_private::ops_using
```
which contain information about the per-op meanings of the bits in the op\_private field.
###
`%bits`
This is indexed by op name and then bit number (0..7). For single bit flags, it returns the name of the define (if any) for that bit:
```
$B::Op_private::bits{aelem}{7} eq 'OPpLVAL_INTRO';
```
For bit fields, it returns a hash ref containing details about the field. The same reference will be returned for all bit positions that make up the bit field; so for example these both return the same hash ref:
```
$bitfield = $B::Op_private::bits{aelem}{5};
$bitfield = $B::Op_private::bits{aelem}{6};
```
The general format of this hash ref is
```
{
# The bit range and mask; these are always present.
bitmin => 5,
bitmax => 6,
bitmask => 0x60,
# (The remaining keys are optional)
# The names of any defines that were requested:
mask_def => 'OPpFOO_MASK',
baseshift_def => 'OPpFOO_SHIFT',
bitcount_def => 'OPpFOO_BITS',
# If present, Concise etc will display the value with a 'FOO='
# prefix. If it equals '-', then Concise will treat the bit
# field as raw bits and not try to interpret it.
label => 'FOO',
# If present, specifies the names of some defines and the
# display labels that are used to assign meaning to particu-
# lar integer values within the bit field; e.g. 3 is dis-
# played as 'C'.
enum => [ qw(
1 OPpFOO_A A
2 OPpFOO_B B
3 OPpFOO_C C
)],
};
```
###
`%defines`
This gives the value of every `OPp` define, e.g.
```
$B::Op_private::defines{OPpLVAL_INTRO} == 128;
```
###
`%labels`
This gives the short display label for each define, as used by `B::Concise` and `perl -Dx`, e.g.
```
$B::Op_private::labels{OPpLVAL_INTRO} eq 'LVINTRO';
```
If the label equals '-', then Concise will treat the bit as a raw bit and not try to display it symbolically.
###
`%ops_using`
For each define, this gives a reference to an array of op names that use the flag.
```
@ops_using_lvintro = @{ $B::Op_private::ops_using{OPp_LVAL_INTRO} };
```
perl Digest::file Digest::file
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Digest::file - Calculate digests of files
SYNOPSIS
--------
```
# Poor mans "md5sum" command
use Digest::file qw(digest_file_hex);
for (@ARGV) {
print digest_file_hex($_, "MD5"), " $_\n";
}
```
DESCRIPTION
-----------
This module provide 3 convenience functions to calculate the digest of files. The following functions are provided:
digest\_file( $file, $algorithm, [$arg,...] ) This function will calculate and return the binary digest of the bytes of the given file. The function will croak if it fails to open or read the file.
The $algorithm is a string like "MD2", "MD5", "SHA-1", "SHA-512". Additional arguments are passed to the constructor for the implementation of the given algorithm.
digest\_file\_hex( $file, $algorithm, [$arg,...] ) Same as digest\_file(), but return the digest in hex form.
digest\_file\_base64( $file, $algorithm, [$arg,...] ) Same as digest\_file(), but return the digest as a base64 encoded string.
SEE ALSO
---------
[Digest](digest)
perl TAP::Parser::Iterator::Array TAP::Parser::Iterator::Array
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [next](#next)
- [next\_raw](#next_raw)
- [wait](#wait)
- [exit](#exit)
* [ATTRIBUTION](#ATTRIBUTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Iterator::Array - Iterator for array-based TAP sources
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Iterator::Array;
my @data = ('foo', 'bar', baz');
my $it = TAP::Parser::Iterator::Array->new(\@data);
my $line = $it->next;
```
DESCRIPTION
-----------
This is a simple iterator wrapper for arrays of scalar content, used by <TAP::Parser>. Unless you're writing a plugin or subclassing, you probably won't need to use this module directly.
METHODS
-------
###
Class Methods
#### `new`
Create an iterator. Takes one argument: an `$array_ref`
###
Instance Methods
#### `next`
Iterate through it, of course.
#### `next_raw`
Iterate raw input without applying any fixes for quirky input syntax.
#### `wait`
Get the wait status for this iterator. For an array iterator this will always be zero.
#### `exit`
Get the exit status for this iterator. For an array iterator this will always be zero.
ATTRIBUTION
-----------
Originally ripped off from <Test::Harness>.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Iterator>,
perl integer integer
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
integer - Perl pragma to use integer arithmetic instead of floating point
SYNOPSIS
--------
```
use integer;
$x = 10/3;
# $x is now 3, not 3.33333333333333333
```
DESCRIPTION
-----------
This tells the compiler to use integer operations from here to the end of the enclosing BLOCK. On many machines, this doesn't matter a great deal for most computations, but on those without floating point hardware, it can make a big difference in performance.
Note that this only affects how most of the arithmetic and relational **operators** handle their operands and results, and **not** how all numbers everywhere are treated. Specifically, `use integer;` has the effect that before computing the results of the arithmetic operators (+, -, \*, /, %, +=, -=, \*=, /=, %=, and unary minus), the comparison operators (<, <=, >, >=, ==, !=, <=>), and the bitwise operators (|, &, ^, <<, >>, |=, &=, ^=, <<=, >>=), the operands have their fractional portions truncated (or floored), and the result will have its fractional portion truncated as well. In addition, the range of operands and results is restricted to that of familiar two's complement integers, i.e., -(2\*\*31) .. (2\*\*31-1) on 32-bit architectures, and -(2\*\*63) .. (2\*\*63-1) on 64-bit architectures. For example, this code
```
use integer;
$x = 5.8;
$y = 2.5;
$z = 2.7;
$a = 2**31 - 1; # Largest positive integer on 32-bit machines
$, = ", ";
print $x, -$x, $x+$y, $x-$y, $x/$y, $x*$y, $y==$z, $a, $a+1;
```
will print: 5.8, -5, 7, 3, 2, 10, 1, 2147483647, -2147483648
Note that $x is still printed as having its true non-integer value of 5.8 since it wasn't operated on. And note too the wrap-around from the largest positive integer to the largest negative one. Also, arguments passed to functions and the values returned by them are **not** affected by `use integer;`. E.g.,
```
srand(1.5);
$, = ", ";
print sin(.5), cos(.5), atan2(1,2), sqrt(2), rand(10);
```
will give the same result with or without `use integer;` The power operator `**` is also not affected, so that 2 \*\* .5 is always the square root of 2. Now, it so happens that the pre- and post- increment and decrement operators, ++ and --, are not affected by `use integer;` either. Some may rightly consider this to be a bug -- but at least it's a long-standing one.
Finally, `use integer;` also has an additional affect on the bitwise operators. Normally, the operands and results are treated as **unsigned** integers, but with `use integer;` the operands and results are **signed**. This means, among other things, that ~0 is -1, and -2 & -5 is -6.
Internally, native integer arithmetic (as provided by your C compiler) is used. This means that Perl's own semantics for arithmetic operations may not be preserved. One common source of trouble is the modulus of negative numbers, which Perl does one way, but your hardware may do another.
```
% perl -le 'print (4 % -3)'
-2
% perl -Minteger -le 'print (4 % -3)'
1
```
See ["Pragmatic Modules" in perlmodlib](perlmodlib#Pragmatic-Modules), ["Integer Arithmetic" in perlop](perlop#Integer-Arithmetic)
perl perlnewmod perlnewmod
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Warning](#Warning)
+ [What should I make into a module?](#What-should-I-make-into-a-module?)
+ [Step-by-step: Preparing the ground](#Step-by-step:-Preparing-the-ground)
+ [Step-by-step: Making the module](#Step-by-step:-Making-the-module)
+ [Step-by-step: Distributing your module](#Step-by-step:-Distributing-your-module)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlnewmod - preparing a new module for distribution
DESCRIPTION
-----------
This document gives you some suggestions about how to go about writing Perl modules, preparing them for distribution, and making them available via CPAN.
One of the things that makes Perl really powerful is the fact that Perl hackers tend to want to share the solutions to problems they've faced, so you and I don't have to battle with the same problem again.
The main way they do this is by abstracting the solution into a Perl module. If you don't know what one of these is, the rest of this document isn't going to be much use to you. You're also missing out on an awful lot of useful code; consider having a look at <perlmod>, <perlmodlib> and <perlmodinstall> before coming back here.
When you've found that there isn't a module available for what you're trying to do, and you've had to write the code yourself, consider packaging up the solution into a module and uploading it to CPAN so that others can benefit.
You should also take a look at <perlmodstyle> for best practices in making a module.
### Warning
We're going to primarily concentrate on Perl-only modules here, rather than XS modules. XS modules serve a rather different purpose, and you should consider different things before distributing them - the popularity of the library you are gluing, the portability to other operating systems, and so on. However, the notes on preparing the Perl side of the module and packaging and distributing it will apply equally well to an XS module as a pure-Perl one.
###
What should I make into a module?
You should make a module out of any code that you think is going to be useful to others. Anything that's likely to fill a hole in the communal library and which someone else can slot directly into their program. Any part of your code which you can isolate and extract and plug into something else is a likely candidate.
Let's take an example. Suppose you're reading in data from a local format into a hash-of-hashes in Perl, turning that into a tree, walking the tree and then piping each node to an Acme Transmogrifier Server.
Now, quite a few people have the Acme Transmogrifier, and you've had to write something to talk the protocol from scratch - you'd almost certainly want to make that into a module. The level at which you pitch it is up to you: you might want protocol-level modules analogous to <Net::SMTP> which then talk to higher level modules analogous to <Mail::Send>. The choice is yours, but you do want to get a module out for that server protocol.
Nobody else on the planet is going to talk your local data format, so we can ignore that. But what about the thing in the middle? Building tree structures from Perl variables and then traversing them is a nice, general problem, and if nobody's already written a module that does that, you might want to modularise that code too.
So hopefully you've now got a few ideas about what's good to modularise. Let's now see how it's done.
###
Step-by-step: Preparing the ground
Before we even start scraping out the code, there are a few things we'll want to do in advance.
Look around Dig into a bunch of modules to see how they're written. I'd suggest starting with <Text::Tabs>, since it's in the standard library and is nice and simple, and then looking at something a little more complex like <File::Copy>. For object oriented code, <WWW::Mechanize> or the `Email::*` modules provide some good examples.
These should give you an overall feel for how modules are laid out and written.
Check it's new There are a lot of modules on CPAN, and it's easy to miss one that's similar to what you're planning on contributing. Have a good plough through <http://metacpan.org> and make sure you're not the one reinventing the wheel!
Discuss the need You might love it. You might feel that everyone else needs it. But there might not actually be any real demand for it out there. If you're unsure about the demand your module will have, consider asking the `[email protected]` mailing list (send an email to `[email protected]` to subscribe; see <https://lists.perl.org/list/module-authors.html> for more information and a link to the archives).
Choose a name Perl modules included on CPAN have a naming hierarchy you should try to fit in with. See <perlmodlib> for more details on how this works, and browse around CPAN and the modules list to get a feel of it. At the very least, remember this: modules should be title capitalised, (This::Thing) fit in with a category, and explain their purpose succinctly.
Check again While you're doing that, make really sure you haven't missed a module similar to the one you're about to write.
When you've got your name sorted out and you're sure that your module is wanted and not currently available, it's time to start coding.
###
Step-by-step: Making the module
Start with *module-starter* or *h2xs*
The *module-starter* utility is distributed as part of the <Module::Starter> CPAN package. It creates a directory with stubs of all the necessary files to start a new module, according to recent "best practice" for module development, and is invoked from the command line, thus:
```
module-starter --module=Foo::Bar \
--author="Your Name" [email protected]
```
If you do not wish to install the <Module::Starter> package from CPAN, *h2xs* is an older tool, originally intended for the development of XS modules, which comes packaged with the Perl distribution.
A typical invocation of <h2xs> for a pure Perl module is:
```
h2xs -AX --skip-exporter --use-new-tests -n Foo::Bar
```
The `-A` omits the Autoloader code, `-X` omits XS elements, `--skip-exporter` omits the Exporter code, `--use-new-tests` sets up a modern testing environment, and `-n` specifies the name of the module.
Use <strict> and <warnings>
A module's code has to be warning and strict-clean, since you can't guarantee the conditions that it'll be used under. Besides, you wouldn't want to distribute code that wasn't warning or strict-clean anyway, right?
Use [Carp](carp)
The [Carp](carp) module allows you to present your error messages from the caller's perspective; this gives you a way to signal a problem with the caller and not your module. For instance, if you say this:
```
warn "No hostname given";
```
the user will see something like this:
```
No hostname given at
/usr/local/lib/perl5/site_perl/5.6.0/Net/Acme.pm line 123.
```
which looks like your module is doing something wrong. Instead, you want to put the blame on the user, and say this:
```
No hostname given at bad_code, line 10.
```
You do this by using [Carp](carp) and replacing your `warn`s with `carp`s. If you need to `die`, say `croak` instead. However, keep `warn` and `die` in place for your sanity checks - where it really is your module at fault.
Use [Exporter](exporter) - wisely! [Exporter](exporter) gives you a standard way of exporting symbols and subroutines from your module into the caller's namespace. For instance, saying `use Net::Acme qw(&frob)` would import the `frob` subroutine.
The package variable `@EXPORT` will determine which symbols will get exported when the caller simply says `use Net::Acme` - you will hardly ever want to put anything in there. `@EXPORT_OK`, on the other hand, specifies which symbols you're willing to export. If you do want to export a bunch of symbols, use the `%EXPORT_TAGS` and define a standard export set - look at [Exporter](exporter) for more details.
Use [plain old documentation](perlpod)
The work isn't over until the paperwork is done, and you're going to need to put in some time writing some documentation for your module. `module-starter` or `h2xs` will provide a stub for you to fill in; if you're not sure about the format, look at <perlpod> for an introduction. Provide a good synopsis of how your module is used in code, a description, and then notes on the syntax and function of the individual subroutines or methods. Use Perl comments for developer notes and POD for end-user notes.
Write tests You're encouraged to create self-tests for your module to ensure it's working as intended on the myriad platforms Perl supports; if you upload your module to CPAN, a host of testers will build your module and send you the results of the tests. Again, `module-starter` and `h2xs` provide a test framework which you can extend - you should do something more than just checking your module will compile. <Test::Simple> and <Test::More> are good places to start when writing a test suite.
Write the *README*
If you're uploading to CPAN, the automated gremlins will extract the README file and place that in your CPAN directory. It'll also appear in the main *by-module* and *by-category* directories if you make it onto the modules list. It's a good idea to put here what the module actually does in detail.
Write *Changes*
Add any user-visible changes since the last release to your *Changes* file.
###
Step-by-step: Distributing your module
Get a CPAN user ID Every developer publishing modules on CPAN needs a CPAN ID. Visit `<http://pause.perl.org/>`, select "Request PAUSE Account", and wait for your request to be approved by the PAUSE administrators.
Make the tarball Once again, `module-starter` or `h2xs` has done all the work for you. They produce the standard `Makefile.PL` you see when you download and install modules, and this produces a Makefile with a `dist` target.
```
perl Makefile.PL && make test && make distcheck && make dist
```
Once you've ensured that your module passes its own tests - always a good thing to make sure - you can `make distcheck` to make sure everything looks OK, followed by `make dist`, and the Makefile will hopefully produce you a nice tarball of your module, ready for upload.
Upload the tarball The email you got when you received your CPAN ID will tell you how to log in to PAUSE, the Perl Authors Upload SErver. From the menus there, you can upload your module to CPAN.
Alternatively you can use the *cpan-upload* script, part of the <CPAN::Uploader> distribution on CPAN.
Fix bugs! Once you start accumulating users, they'll send you bug reports. If you're lucky, they'll even send you patches. Welcome to the joys of maintaining a software project...
AUTHOR
------
Simon Cozens, `[email protected]`
Updated by Kirrily "Skud" Robert, `[email protected]`
SEE ALSO
---------
<perlmod>, <perlmodlib>, <perlmodinstall>, <h2xs>, <strict>, [Carp](carp), [Exporter](exporter), <perlpod>, <Test::Simple>, <Test::More> <ExtUtils::MakeMaker>, <Module::Build>, <Module::Starter> <http://www.cpan.org/>
| programming_docs |
perl Math::Trig Math::Trig
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [TRIGONOMETRIC FUNCTIONS](#TRIGONOMETRIC-FUNCTIONS)
+ [ERRORS DUE TO DIVISION BY ZERO](#ERRORS-DUE-TO-DIVISION-BY-ZERO)
+ [SIMPLE (REAL) ARGUMENTS, COMPLEX RESULTS](#SIMPLE-(REAL)-ARGUMENTS,-COMPLEX-RESULTS)
* [PLANE ANGLE CONVERSIONS](#PLANE-ANGLE-CONVERSIONS)
* [RADIAL COORDINATE CONVERSIONS](#RADIAL-COORDINATE-CONVERSIONS)
+ [COORDINATE SYSTEMS](#COORDINATE-SYSTEMS)
+ [3-D ANGLE CONVERSIONS](#3-D-ANGLE-CONVERSIONS)
* [GREAT CIRCLE DISTANCES AND DIRECTIONS](#GREAT-CIRCLE-DISTANCES-AND-DIRECTIONS)
+ [great\_circle\_distance](#great_circle_distance)
+ [great\_circle\_direction](#great_circle_direction)
+ [great\_circle\_bearing](#great_circle_bearing)
+ [great\_circle\_destination](#great_circle_destination)
+ [great\_circle\_midpoint](#great_circle_midpoint)
+ [great\_circle\_waypoint](#great_circle_waypoint)
* [EXAMPLES](#EXAMPLES)
+ [CAVEAT FOR GREAT CIRCLE FORMULAS](#CAVEAT-FOR-GREAT-CIRCLE-FORMULAS)
+ [Real-valued asin and acos](#Real-valued-asin-and-acos)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [LICENSE](#LICENSE)
NAME
----
Math::Trig - trigonometric functions
SYNOPSIS
--------
```
use Math::Trig;
$x = tan(0.9);
$y = acos(3.7);
$z = asin(2.4);
$halfpi = pi/2;
$rad = deg2rad(120);
# Import constants pi2, pip2, pip4 (2*pi, pi/2, pi/4).
use Math::Trig ':pi';
# Import the conversions between cartesian/spherical/cylindrical.
use Math::Trig ':radial';
# Import the great circle formulas.
use Math::Trig ':great_circle';
```
DESCRIPTION
-----------
`Math::Trig` defines many trigonometric functions not defined by the core Perl which defines only the `sin()` and `cos()`. The constant **pi** is also defined as are a few convenience functions for angle conversions, and *great circle formulas* for spherical movement.
TRIGONOMETRIC FUNCTIONS
------------------------
The tangent
**tan** The cofunctions of the sine, cosine, and tangent (cosec/csc and cotan/cot are aliases)
**csc**, **cosec**, **sec**, **sec**, **cot**, **cotan**
The arcus (also known as the inverse) functions of the sine, cosine, and tangent
**asin**, **acos**, **atan**
The principal value of the arc tangent of y/x
**atan2**(y, x)
The arcus cofunctions of the sine, cosine, and tangent (acosec/acsc and acotan/acot are aliases). Note that atan2(0, 0) is not well-defined.
**acsc**, **acosec**, **asec**, **acot**, **acotan**
The hyperbolic sine, cosine, and tangent
**sinh**, **cosh**, **tanh**
The cofunctions of the hyperbolic sine, cosine, and tangent (cosech/csch and cotanh/coth are aliases)
**csch**, **cosech**, **sech**, **coth**, **cotanh**
The area (also known as the inverse) functions of the hyperbolic sine, cosine, and tangent
**asinh**, **acosh**, **atanh**
The area cofunctions of the hyperbolic sine, cosine, and tangent (acsch/acosech and acoth/acotanh are aliases)
**acsch**, **acosech**, **asech**, **acoth**, **acotanh**
The trigonometric constant **pi** and some of handy multiples of it are also defined.
**pi, pi2, pi4, pip2, pip4**
###
ERRORS DUE TO DIVISION BY ZERO
The following functions
```
acoth
acsc
acsch
asec
asech
atanh
cot
coth
csc
csch
sec
sech
tan
tanh
```
cannot be computed for all arguments because that would mean dividing by zero or taking logarithm of zero. These situations cause fatal runtime errors looking like this
```
cot(0): Division by zero.
(Because in the definition of cot(0), the divisor sin(0) is 0)
Died at ...
```
or
```
atanh(-1): Logarithm of zero.
Died at...
```
For the `csc`, `cot`, `asec`, `acsc`, `acot`, `csch`, `coth`, `asech`, `acsch`, the argument cannot be `0` (zero). For the `atanh`, `acoth`, the argument cannot be `1` (one). For the `atanh`, `acoth`, the argument cannot be `-1` (minus one). For the `tan`, `sec`, `tanh`, `sech`, the argument cannot be *pi/2 + k \* pi*, where *k* is any integer.
Note that atan2(0, 0) is not well-defined.
###
SIMPLE (REAL) ARGUMENTS, COMPLEX RESULTS
Please note that some of the trigonometric functions can break out from the **real axis** into the **complex plane**. For example `asin(2)` has no definition for plain real numbers but it has definition for complex numbers.
In Perl terms this means that supplying the usual Perl numbers (also known as scalars, please see <perldata>) as input for the trigonometric functions might produce as output results that no more are simple real numbers: instead they are complex numbers.
The `Math::Trig` handles this by using the `Math::Complex` package which knows how to handle complex numbers, please see <Math::Complex> for more information. In practice you need not to worry about getting complex numbers as results because the `Math::Complex` takes care of details like for example how to display complex numbers. For example:
```
print asin(2), "\n";
```
should produce something like this (take or leave few last decimals):
```
1.5707963267949-1.31695789692482i
```
That is, a complex number with the real part of approximately `1.571` and the imaginary part of approximately `-1.317`.
PLANE ANGLE CONVERSIONS
------------------------
(Plane, 2-dimensional) angles may be converted with the following functions.
deg2rad
```
$radians = deg2rad($degrees);
```
grad2rad
```
$radians = grad2rad($gradians);
```
rad2deg
```
$degrees = rad2deg($radians);
```
grad2deg
```
$degrees = grad2deg($gradians);
```
deg2grad
```
$gradians = deg2grad($degrees);
```
rad2grad
```
$gradians = rad2grad($radians);
```
The full circle is 2 *pi* radians or *360* degrees or *400* gradians. The result is by default wrapped to be inside the [0, {2pi,360,400}[ circle. If you don't want this, supply a true second argument:
```
$zillions_of_radians = deg2rad($zillions_of_degrees, 1);
$negative_degrees = rad2deg($negative_radians, 1);
```
You can also do the wrapping explicitly by rad2rad(), deg2deg(), and grad2grad().
rad2rad
```
$radians_wrapped_by_2pi = rad2rad($radians);
```
deg2deg
```
$degrees_wrapped_by_360 = deg2deg($degrees);
```
grad2grad
```
$gradians_wrapped_by_400 = grad2grad($gradians);
```
RADIAL COORDINATE CONVERSIONS
------------------------------
**Radial coordinate systems** are the **spherical** and the **cylindrical** systems, explained shortly in more detail.
You can import radial coordinate conversion functions by using the `:radial` tag:
```
use Math::Trig ':radial';
($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z);
($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z);
($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z);
($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z);
($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi);
($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi);
```
**All angles are in radians**.
###
COORDINATE SYSTEMS
**Cartesian** coordinates are the usual rectangular *(x, y, z)*-coordinates.
Spherical coordinates, *(rho, theta, pi)*, are three-dimensional coordinates which define a point in three-dimensional space. They are based on a sphere surface. The radius of the sphere is **rho**, also known as the *radial* coordinate. The angle in the *xy*-plane (around the *z*-axis) is **theta**, also known as the *azimuthal* coordinate. The angle from the *z*-axis is **phi**, also known as the *polar* coordinate. The North Pole is therefore *0, 0, rho*, and the Gulf of Guinea (think of the missing big chunk of Africa) *0, pi/2, rho*. In geographical terms *phi* is latitude (northward positive, southward negative) and *theta* is longitude (eastward positive, westward negative).
**BEWARE**: some texts define *theta* and *phi* the other way round, some texts define the *phi* to start from the horizontal plane, some texts use *r* in place of *rho*.
Cylindrical coordinates, *(rho, theta, z)*, are three-dimensional coordinates which define a point in three-dimensional space. They are based on a cylinder surface. The radius of the cylinder is **rho**, also known as the *radial* coordinate. The angle in the *xy*-plane (around the *z*-axis) is **theta**, also known as the *azimuthal* coordinate. The third coordinate is the *z*, pointing up from the **theta**-plane.
###
3-D ANGLE CONVERSIONS
Conversions to and from spherical and cylindrical coordinates are available. Please notice that the conversions are not necessarily reversible because of the equalities like *pi* angles being equal to *-pi* angles.
cartesian\_to\_cylindrical
```
($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z);
```
cartesian\_to\_spherical
```
($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z);
```
cylindrical\_to\_cartesian
```
($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z);
```
cylindrical\_to\_spherical
```
($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z);
```
Notice that when `$z` is not 0 `$rho_s` is not equal to `$rho_c`.
spherical\_to\_cartesian
```
($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi);
```
spherical\_to\_cylindrical
```
($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi);
```
Notice that when `$z` is not 0 `$rho_c` is not equal to `$rho_s`.
GREAT CIRCLE DISTANCES AND DIRECTIONS
--------------------------------------
A great circle is section of a circle that contains the circle diameter: the shortest distance between two (non-antipodal) points on the spherical surface goes along the great circle connecting those two points.
### great\_circle\_distance
You can compute spherical distances, called **great circle distances**, by importing the great\_circle\_distance() function:
```
use Math::Trig 'great_circle_distance';
$distance = great_circle_distance($theta0, $phi0, $theta1, $phi1, [, $rho]);
```
The *great circle distance* is the shortest distance between two points on a sphere. The distance is in `$rho` units. The `$rho` is optional, it defaults to 1 (the unit sphere), therefore the distance defaults to radians.
If you think geographically the *theta* are longitudes: zero at the Greenwhich meridian, eastward positive, westward negative -- and the *phi* are latitudes: zero at the North Pole, northward positive, southward negative. **NOTE**: this formula thinks in mathematics, not geographically: the *phi* zero is at the North Pole, not at the Equator on the west coast of Africa (Bay of Guinea). You need to subtract your geographical coordinates from *pi/2* (also known as 90 degrees).
```
$distance = great_circle_distance($lon0, pi/2 - $lat0,
$lon1, pi/2 - $lat1, $rho);
```
### great\_circle\_direction
The direction you must follow the great circle (also known as *bearing*) can be computed by the great\_circle\_direction() function:
```
use Math::Trig 'great_circle_direction';
$direction = great_circle_direction($theta0, $phi0, $theta1, $phi1);
```
### great\_circle\_bearing
Alias 'great\_circle\_bearing' for 'great\_circle\_direction' is also available.
```
use Math::Trig 'great_circle_bearing';
$direction = great_circle_bearing($theta0, $phi0, $theta1, $phi1);
```
The result of great\_circle\_direction is in radians, zero indicating straight north, pi or -pi straight south, pi/2 straight west, and -pi/2 straight east.
### great\_circle\_destination
You can inversely compute the destination if you know the starting point, direction, and distance:
```
use Math::Trig 'great_circle_destination';
# $diro is the original direction,
# for example from great_circle_bearing().
# $distance is the angular distance in radians,
# for example from great_circle_distance().
# $thetad and $phid are the destination coordinates,
# $dird is the final direction at the destination.
($thetad, $phid, $dird) =
great_circle_destination($theta, $phi, $diro, $distance);
```
or the midpoint if you know the end points:
### great\_circle\_midpoint
```
use Math::Trig 'great_circle_midpoint';
($thetam, $phim) =
great_circle_midpoint($theta0, $phi0, $theta1, $phi1);
```
The great\_circle\_midpoint() is just a special case of
### great\_circle\_waypoint
```
use Math::Trig 'great_circle_waypoint';
($thetai, $phii) =
great_circle_waypoint($theta0, $phi0, $theta1, $phi1, $way);
```
Where the $way is a value from zero ($theta0, $phi0) to one ($theta1, $phi1). Note that antipodal points (where their distance is *pi* radians) do not have waypoints between them (they would have an an "equator" between them), and therefore `undef` is returned for antipodal points. If the points are the same and the distance therefore zero and all waypoints therefore identical, the first point (either point) is returned.
The thetas, phis, direction, and distance in the above are all in radians.
You can import all the great circle formulas by
```
use Math::Trig ':great_circle';
```
Notice that the resulting directions might be somewhat surprising if you are looking at a flat worldmap: in such map projections the great circles quite often do not look like the shortest routes -- but for example the shortest possible routes from Europe or North America to Asia do often cross the polar regions. (The common Mercator projection does **not** show great circles as straight lines: straight lines in the Mercator projection are lines of constant bearing.)
EXAMPLES
--------
To calculate the distance between London (51.3N 0.5W) and Tokyo (35.7N 139.8E) in kilometers:
```
use Math::Trig qw(great_circle_distance deg2rad);
# Notice the 90 - latitude: phi zero is at the North Pole.
sub NESW { deg2rad($_[0]), deg2rad(90 - $_[1]) }
my @L = NESW( -0.5, 51.3);
my @T = NESW(139.8, 35.7);
my $km = great_circle_distance(@L, @T, 6378); # About 9600 km.
```
The direction you would have to go from London to Tokyo (in radians, straight north being zero, straight east being pi/2).
```
use Math::Trig qw(great_circle_direction);
my $rad = great_circle_direction(@L, @T); # About 0.547 or 0.174 pi.
```
The midpoint between London and Tokyo being
```
use Math::Trig qw(great_circle_midpoint);
my @M = great_circle_midpoint(@L, @T);
```
or about 69 N 89 E, in the frozen wastes of Siberia.
**NOTE**: you **cannot** get from A to B like this:
```
Dist = great_circle_distance(A, B)
Dir = great_circle_direction(A, B)
C = great_circle_destination(A, Dist, Dir)
```
and expect C to be B, because the bearing constantly changes when going from A to B (except in some special case like the meridians or the circles of latitudes) and in great\_circle\_destination() one gives a **constant** bearing to follow.
###
CAVEAT FOR GREAT CIRCLE FORMULAS
The answers may be off by few percentages because of the irregular (slightly aspherical) form of the Earth. The errors are at worst about 0.55%, but generally below 0.3%.
###
Real-valued asin and acos
For small inputs asin() and acos() may return complex numbers even when real numbers would be enough and correct, this happens because of floating-point inaccuracies. You can see these inaccuracies for example by trying theses:
```
print cos(1e-6)**2+sin(1e-6)**2 - 1,"\n";
printf "%.20f", cos(1e-6)**2+sin(1e-6)**2,"\n";
```
which will print something like this
```
-1.11022302462516e-16
0.99999999999999988898
```
even though the expected results are of course exactly zero and one. The formulas used to compute asin() and acos() are quite sensitive to this, and therefore they might accidentally slip into the complex plane even when they should not. To counter this there are two interfaces that are guaranteed to return a real-valued output.
asin\_real
```
use Math::Trig qw(asin_real);
$real_angle = asin_real($input_sin);
```
Return a real-valued arcus sine if the input is between [-1, 1], **inclusive** the endpoints. For inputs greater than one, pi/2 is returned. For inputs less than minus one, -pi/2 is returned.
acos\_real
```
use Math::Trig qw(acos_real);
$real_angle = acos_real($input_cos);
```
Return a real-valued arcus cosine if the input is between [-1, 1], **inclusive** the endpoints. For inputs greater than one, zero is returned. For inputs less than minus one, pi is returned.
BUGS
----
Saying `use Math::Trig;` exports many mathematical routines in the caller environment and even overrides some (`sin`, `cos`). This is construed as a feature by the Authors, actually... ;-)
The code is not optimized for speed, especially because we use `Math::Complex` and thus go quite near complex numbers while doing the computations even when the arguments are not. This, however, cannot be completely avoided if we want things like `asin(2)` to give an answer instead of giving a fatal runtime error.
Do not attempt navigation using these formulas.
<Math::Complex>
AUTHORS
-------
Jarkko Hietaniemi <*jhi!at!iki.fi*>, Raphael Manfredi <*Raphael\_Manfredi!at!pobox.com*>, Zefram <[email protected]>
LICENSE
-------
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl less less
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FOR MODULE AUTHORS](#FOR-MODULE-AUTHORS)
+ [BOOLEAN = less->of( FEATURE )](#BOOLEAN-=-less-%3Eof(-FEATURE-))
+ [FEATURES = less->of()](#FEATURES-=-less-%3Eof())
* [CAVEATS](#CAVEATS)
NAME
----
less - perl pragma to request less of something
SYNOPSIS
--------
```
use less 'CPU';
```
DESCRIPTION
-----------
This is a user-pragma. If you're very lucky some code you're using will know that you asked for less CPU usage or ram or fat or... we just can't know. Consult your documentation on everything you're currently using.
For general suggestions, try requesting `CPU` or `memory`.
```
use less 'memory';
use less 'CPU';
use less 'fat';
```
If you ask for nothing in particular, you'll be asking for `less 'please'`.
```
use less 'please';
```
FOR MODULE AUTHORS
-------------------
<less> has been in the core as a "joke" module for ages now and it hasn't had any real way to communicating any information to anything. Thanks to Nicholas Clark we have user pragmas (see <perlpragma>) and now `less` can do something.
You can probably expect your users to be able to guess that they can request less CPU or memory or just "less" overall.
If the user didn't specify anything, it's interpreted as having used the `please` tag. It's up to you to make this useful.
```
# equivalent
use less;
use less 'please';
```
###
`BOOLEAN = less->of( FEATURE )`
The class method `less->of( NAME )` returns a boolean to tell you whether your user requested less of something.
```
if ( less->of( 'CPU' ) ) {
...
}
elsif ( less->of( 'memory' ) ) {
}
```
###
`FEATURES = less->of()`
If you don't ask for any feature, you get the list of features that the user requested you to be nice to. This has the nice side effect that if you don't respect anything in particular then you can just ask for it and use it like a boolean.
```
if ( less->of ) {
...
}
else {
...
}
```
CAVEATS
-------
This probably does nothing.
This works only on 5.10+ At least it's backwards compatible in not doing much.
perl perlcheat perlcheat
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [The sheet](#The-sheet)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlcheat - Perl 5 Cheat Sheet
DESCRIPTION
-----------
This 'cheat sheet' is a handy reference, meant for beginning Perl programmers. Not everything is mentioned, but 195 features may already be overwhelming.
###
The sheet
```
CONTEXTS SIGILS ref ARRAYS HASHES
void $scalar SCALAR @array %hash
scalar @array ARRAY @array[0, 2] @hash{'a', 'b'}
list %hash HASH $array[0] $hash{'a'}
&sub CODE
*glob GLOB SCALAR VALUES
FORMAT number, string, ref, glob, undef
REFERENCES
\ reference $$foo[1] aka $foo->[1]
$@%&* dereference $$foo{bar} aka $foo->{bar}
[] anon. arrayref ${$$foo[1]}[2] aka $foo->[1]->[2]
{} anon. hashref ${$$foo[1]}[2] aka $foo->[1][2]
\() list of refs
SYNTAX
OPERATOR PRECEDENCE foreach (LIST) { } for (a;b;c) { }
-> while (e) { } until (e) { }
++ -- if (e) { } elsif (e) { } else { }
** unless (e) { } elsif (e) { } else { }
! ~ \ u+ u- given (e) { when (e) {} default {} }
=~ !~
* / % x NUMBERS vs STRINGS FALSE vs TRUE
+ - . = = undef, "", 0, "0"
<< >> + . anything else
named uops == != eq ne
< > <= >= lt gt le ge < > <= >= lt gt le ge
== != <=> eq ne cmp ~~ <=> cmp
&
| ^ REGEX MODIFIERS REGEX METACHARS
&& /i case insensitive ^ string begin
|| // /m line based ^$ $ str end (bfr \n)
.. ... /s . includes \n + one or more
?: /x /xx ign. wh.space * zero or more
= += last goto /p preserve ? zero or one
, => /a ASCII /aa safe {3,7} repeat in range
list ops /l locale /d dual | alternation
not /u Unicode [] character class
and /e evaluate /ee rpts \b boundary
or xor /g global \z string end
/o compile pat once () capture
DEBUG (?:p) no capture
-MO=Deparse REGEX CHARCLASSES (?#t) comment
-MO=Terse . [^\n] (?=p) ZW pos ahead
-D## \s whitespace (?!p) ZW neg ahead
-d:Trace \w word chars (?<=p) ZW pos behind \K
\d digits (?<!p) ZW neg behind
CONFIGURATION \pP named property (?>p) no backtrack
perl -V:ivsize \h horiz.wh.space (?|p|p)branch reset
\R linebreak (?<n>p)named capture
\S \W \D \H negate \g{n} ref to named cap
\K keep left part
FUNCTION RETURN LISTS
stat localtime caller SPECIAL VARIABLES
0 dev 0 second 0 package $_ default variable
1 ino 1 minute 1 filename $0 program name
2 mode 2 hour 2 line $/ input separator
3 nlink 3 day 3 subroutine $\ output separator
4 uid 4 month-1 4 hasargs $| autoflush
5 gid 5 year-1900 5 wantarray $! sys/libcall error
6 rdev 6 weekday 6 evaltext $@ eval error
7 size 7 yearday 7 is_require $$ process ID
8 atime 8 is_dst 8 hints $. line number
9 mtime 9 bitmask @ARGV command line args
10 ctime 10 hinthash @INC include paths
11 blksz 3..10 only @_ subroutine args
12 blcks with EXPR %ENV environment
```
ACKNOWLEDGEMENTS
----------------
The first version of this document appeared on Perl Monks, where several people had useful suggestions. Thank you, Perl Monks.
A special thanks to Damian Conway, who didn't only suggest important changes, but also took the time to count the number of listed features and make a Raku version to show that Perl will stay Perl.
AUTHOR
------
Juerd Waalboer <#####@juerd.nl>, with the help of many Perl Monks.
SEE ALSO
---------
* <https://perlmonks.org/?node_id=216602> - the original PM post
* <https://perlmonks.org/?node_id=238031> - Damian Conway's Raku version
* <https://juerd.nl/site.plp/perlcheat> - home of the Perl Cheat Sheet
| programming_docs |
perl Win32CORE Win32CORE
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [HISTORY](#HISTORY)
NAME
----
Win32CORE - Win32 CORE function stubs
DESCRIPTION
-----------
This library provides stubs for the functions marked as [CORE] in [Win32](win32). See that document for usage information. When any of these functions are called, the full Win32 module is loaded automatically. It is preferred that callers of these functions explicitly `use Win32;`.
HISTORY
-------
Win32CORE was created to provide on cygwin those Win32:: functions that for regular win32 builds were provided by default in perl. In cygwin perl releases prior to 5.8.6, this module was standalone and had to be explicitly used. In 5.8.6 and later, it was statically linked into cygwin perl so this would no longer be necessary.
As of perl 5.9.5/Win32 0.27, these functions have been moved into the Win32 module. Win32CORE provides stubs for each of the former CORE Win32:: functions that internally just load the Win32 module and call it's version, and Win32CORE is statically linked to perl for both cygwin and regular win32 builds. This will permit these functions to be updated in the CPAN Win32 module independently of updating perl.
perl IO::Pipe IO::Pipe
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Pipe - supply object methods for pipes
SYNOPSIS
--------
```
use IO::Pipe;
$pipe = IO::Pipe->new();
if($pid = fork()) { # Parent
$pipe->reader();
while(<$pipe>) {
...
}
}
elsif(defined $pid) { # Child
$pipe->writer();
print $pipe ...
}
or
$pipe = IO::Pipe->new();
$pipe->reader(qw(ls -l));
while(<$pipe>) {
...
}
```
DESCRIPTION
-----------
`IO::Pipe` provides an interface to creating pipes between processes.
CONSTRUCTOR
-----------
new ( [READER, WRITER] ) Creates an `IO::Pipe`, which is a reference to a newly created symbol (see the `Symbol` package). `IO::Pipe::new` optionally takes two arguments, which should be objects blessed into `IO::Handle`, or a subclass thereof. These two objects will be used for the system call to `pipe`. If no arguments are given then method `handles` is called on the new `IO::Pipe` object.
These two handles are held in the array part of the GLOB until either `reader` or `writer` is called.
METHODS
-------
reader ([ARGS]) The object is re-blessed into a sub-class of `IO::Handle`, and becomes a handle at the reading end of the pipe. If `ARGS` are given then `fork` is called and `ARGS` are passed to exec.
writer ([ARGS]) The object is re-blessed into a sub-class of `IO::Handle`, and becomes a handle at the writing end of the pipe. If `ARGS` are given then `fork` is called and `ARGS` are passed to exec.
handles () This method is called during construction by `IO::Pipe::new` on the newly created `IO::Pipe` object. It returns an array of two objects blessed into `IO::Pipe::End`, or a subclass thereof.
SEE ALSO
---------
<IO::Handle>
AUTHOR
------
Graham Barr. Currently maintained by the Perl Porters. Please report all bugs at <https://github.com/Perl/perl5/issues>.
COPYRIGHT
---------
Copyright (c) 1996-8 Graham Barr <[email protected]>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlxs perlxs
======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Introduction](#Introduction)
+ [On The Road](#On-The-Road)
+ [The Anatomy of an XSUB](#The-Anatomy-of-an-XSUB)
+ [The Argument Stack](#The-Argument-Stack)
+ [The RETVAL Variable](#The-RETVAL-Variable)
+ [Returning SVs, AVs and HVs through RETVAL](#Returning-SVs,-AVs-and-HVs-through-RETVAL)
+ [The MODULE Keyword](#The-MODULE-Keyword)
+ [The PACKAGE Keyword](#The-PACKAGE-Keyword)
+ [The PREFIX Keyword](#The-PREFIX-Keyword)
+ [The OUTPUT: Keyword](#The-OUTPUT:-Keyword)
+ [The NO\_OUTPUT Keyword](#The-NO_OUTPUT-Keyword)
+ [The CODE: Keyword](#The-CODE:-Keyword)
+ [The INIT: Keyword](#The-INIT:-Keyword)
+ [The NO\_INIT Keyword](#The-NO_INIT-Keyword)
+ [The TYPEMAP: Keyword](#The-TYPEMAP:-Keyword)
+ [Initializing Function Parameters](#Initializing-Function-Parameters)
+ [Default Parameter Values](#Default-Parameter-Values)
+ [The PREINIT: Keyword](#The-PREINIT:-Keyword)
+ [The SCOPE: Keyword](#The-SCOPE:-Keyword)
+ [The INPUT: Keyword](#The-INPUT:-Keyword)
+ [The IN/OUTLIST/IN\_OUTLIST/OUT/IN\_OUT Keywords](#The-IN/OUTLIST/IN_OUTLIST/OUT/IN_OUT-Keywords)
+ [The length(NAME) Keyword](#The-length(NAME)-Keyword)
+ [Variable-length Parameter Lists](#Variable-length-Parameter-Lists)
+ [The C\_ARGS: Keyword](#The-C_ARGS:-Keyword)
+ [The PPCODE: Keyword](#The-PPCODE:-Keyword)
+ [Returning Undef And Empty Lists](#Returning-Undef-And-Empty-Lists)
+ [The REQUIRE: Keyword](#The-REQUIRE:-Keyword)
+ [The CLEANUP: Keyword](#The-CLEANUP:-Keyword)
+ [The POSTCALL: Keyword](#The-POSTCALL:-Keyword)
+ [The BOOT: Keyword](#The-BOOT:-Keyword)
+ [The VERSIONCHECK: Keyword](#The-VERSIONCHECK:-Keyword)
+ [The PROTOTYPES: Keyword](#The-PROTOTYPES:-Keyword)
+ [The PROTOTYPE: Keyword](#The-PROTOTYPE:-Keyword)
+ [The ALIAS: Keyword](#The-ALIAS:-Keyword)
+ [The OVERLOAD: Keyword](#The-OVERLOAD:-Keyword)
+ [The FALLBACK: Keyword](#The-FALLBACK:-Keyword)
+ [The INTERFACE: Keyword](#The-INTERFACE:-Keyword)
+ [The INTERFACE\_MACRO: Keyword](#The-INTERFACE_MACRO:-Keyword)
+ [The INCLUDE: Keyword](#The-INCLUDE:-Keyword)
+ [The INCLUDE\_COMMAND: Keyword](#The-INCLUDE_COMMAND:-Keyword)
+ [The CASE: Keyword](#The-CASE:-Keyword)
+ [The EXPORT\_XSUB\_SYMBOLS: Keyword](#The-EXPORT_XSUB_SYMBOLS:-Keyword)
+ [The & Unary Operator](#The-&-Unary-Operator)
+ [Inserting POD, Comments and C Preprocessor Directives](#Inserting-POD,-Comments-and-C-Preprocessor-Directives)
+ [Using XS With C++](#Using-XS-With-C++)
+ [Interface Strategy](#Interface-Strategy)
+ [Perl Objects And C Structures](#Perl-Objects-And-C-Structures)
+ [Safely Storing Static Data in XS](#Safely-Storing-Static-Data-in-XS)
- [MY\_CXT REFERENCE](#MY_CXT-REFERENCE)
+ [Thread-aware system interfaces](#Thread-aware-system-interfaces)
* [EXAMPLES](#EXAMPLES)
* [CAVEATS](#CAVEATS)
* [XS VERSION](#XS-VERSION)
* [AUTHOR](#AUTHOR)
NAME
----
perlxs - XS language reference manual
DESCRIPTION
-----------
### Introduction
XS is an interface description file format used to create an extension interface between Perl and C code (or a C library) which one wishes to use with Perl. The XS interface is combined with the library to create a new library which can then be either dynamically loaded or statically linked into perl. The XS interface description is written in the XS language and is the core component of the Perl extension interface.
Before writing XS, read the ["CAVEATS"](#CAVEATS) section below.
An **XSUB** forms the basic unit of the XS interface. After compilation by the **xsubpp** compiler, each XSUB amounts to a C function definition which will provide the glue between Perl calling conventions and C calling conventions.
The glue code pulls the arguments from the Perl stack, converts these Perl values to the formats expected by a C function, calls this C function, and then transfers the return values of the C function back to Perl. Return values here may be a conventional C return value or any C function arguments that may serve as output parameters. These return values may be passed back to Perl either by putting them on the Perl stack, or by modifying the arguments supplied from the Perl side.
The above is a somewhat simplified view of what really happens. Since Perl allows more flexible calling conventions than C, XSUBs may do much more in practice, such as checking input parameters for validity, throwing exceptions (or returning undef/empty list) if the return value from the C function indicates failure, calling different C functions based on numbers and types of the arguments, providing an object-oriented interface, etc.
Of course, one could write such glue code directly in C. However, this would be a tedious task, especially if one needs to write glue for multiple C functions, and/or one is not familiar enough with the Perl stack discipline and other such arcana. XS comes to the rescue here: instead of writing this glue C code in long-hand, one can write a more concise short-hand *description* of what should be done by the glue, and let the XS compiler **xsubpp** handle the rest.
The XS language allows one to describe the mapping between how the C routine is used, and how the corresponding Perl routine is used. It also allows creation of Perl routines which are directly translated to C code and which are not related to a pre-existing C function. In cases when the C interface coincides with the Perl interface, the XSUB declaration is almost identical to a declaration of a C function (in K&R style). In such circumstances, there is another tool called `h2xs` that is able to translate an entire C header file into a corresponding XS file that will provide glue to the functions/macros described in the header file.
The XS compiler is called **xsubpp**. This compiler creates the constructs necessary to let an XSUB manipulate Perl values, and creates the glue necessary to let Perl call the XSUB. The compiler uses **typemaps** to determine how to map C function parameters and output values to Perl values and back. The default typemap (which comes with Perl) handles many common C types. A supplementary typemap may also be needed to handle any special structures and types for the library being linked. For more information on typemaps, see <perlxstypemap>.
A file in XS format starts with a C language section which goes until the first `MODULE =` directive. Other XS directives and XSUB definitions may follow this line. The "language" used in this part of the file is usually referred to as the XS language. **xsubpp** recognizes and skips POD (see <perlpod>) in both the C and XS language sections, which allows the XS file to contain embedded documentation.
See <perlxstut> for a tutorial on the whole extension creation process.
Note: For some extensions, Dave Beazley's SWIG system may provide a significantly more convenient mechanism for creating the extension glue code. See <http://www.swig.org/> for more information.
For simple bindings to C libraries as well as other machine code libraries, consider instead using the much simpler [libffi](http://sourceware.org/libffi/) interface via CPAN modules like <FFI::Platypus> or <FFI::Raw>.
###
On The Road
Many of the examples which follow will concentrate on creating an interface between Perl and the ONC+ RPC bind library functions. The rpcb\_gettime() function is used to demonstrate many features of the XS language. This function has two parameters; the first is an input parameter and the second is an output parameter. The function also returns a status value.
```
bool_t rpcb_gettime(const char *host, time_t *timep);
```
From C this function will be called with the following statements.
```
#include <rpc/rpc.h>
bool_t status;
time_t timep;
status = rpcb_gettime( "localhost", &timep );
```
If an XSUB is created to offer a direct translation between this function and Perl, then this XSUB will be used from Perl with the following code. The $status and $timep variables will contain the output of the function.
```
use RPC;
$status = rpcb_gettime( "localhost", $timep );
```
The following XS file shows an XS subroutine, or XSUB, which demonstrates one possible interface to the rpcb\_gettime() function. This XSUB represents a direct translation between C and Perl and so preserves the interface even from Perl. This XSUB will be invoked from Perl with the usage shown above. Note that the first three #include statements, for `EXTERN.h`, `perl.h`, and `XSUB.h`, will always be present at the beginning of an XS file. This approach and others will be expanded later in this document. A #define for `PERL_NO_GET_CONTEXT` should be present to fetch the interpreter context more efficiently, see [perlguts](perlguts#How-multiple-interpreters-and-concurrency-are-supported) for details.
```
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include <rpc/rpc.h>
MODULE = RPC PACKAGE = RPC
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
OUTPUT:
timep
```
Any extension to Perl, including those containing XSUBs, should have a Perl module to serve as the bootstrap which pulls the extension into Perl. This module will export the extension's functions and variables to the Perl program and will cause the extension's XSUBs to be linked into Perl. The following module will be used for most of the examples in this document and should be used from Perl with the `use` command as shown earlier. Perl modules are explained in more detail later in this document.
```
package RPC;
require Exporter;
require DynaLoader;
@ISA = qw(Exporter DynaLoader);
@EXPORT = qw( rpcb_gettime );
bootstrap RPC;
1;
```
Throughout this document a variety of interfaces to the rpcb\_gettime() XSUB will be explored. The XSUBs will take their parameters in different orders or will take different numbers of parameters. In each case the XSUB is an abstraction between Perl and the real C rpcb\_gettime() function, and the XSUB must always ensure that the real rpcb\_gettime() function is called with the correct parameters. This abstraction will allow the programmer to create a more Perl-like interface to the C function.
###
The Anatomy of an XSUB
The simplest XSUBs consist of 3 parts: a description of the return value, the name of the XSUB routine and the names of its arguments, and a description of types or formats of the arguments.
The following XSUB allows a Perl program to access a C library function called sin(). The XSUB will imitate the C function which takes a single argument and returns a single value.
```
double
sin(x)
double x
```
Optionally, one can merge the description of types and the list of argument names, rewriting this as
```
double
sin(double x)
```
This makes this XSUB look similar to an ANSI C declaration. An optional semicolon is allowed after the argument list, as in
```
double
sin(double x);
```
Parameters with C pointer types can have different semantic: C functions with similar declarations
```
bool string_looks_as_a_number(char *s);
bool make_char_uppercase(char *c);
```
are used in absolutely incompatible manner. Parameters to these functions could be described to **xsubpp** like this:
```
char * s
char &c
```
Both these XS declarations correspond to the `char*` C type, but they have different semantics, see ["The & Unary Operator"](#The-%26-Unary-Operator).
It is convenient to think that the indirection operator `*` should be considered as a part of the type and the address operator `&` should be considered part of the variable. See <perlxstypemap> for more info about handling qualifiers and unary operators in C types.
The function name and the return type must be placed on separate lines and should be flush left-adjusted.
```
INCORRECT CORRECT
double sin(x) double
double x sin(x)
double x
```
The rest of the function description may be indented or left-adjusted. The following example shows a function with its body left-adjusted. Most examples in this document will indent the body for better readability.
```
CORRECT
double
sin(x)
double x
```
More complicated XSUBs may contain many other sections. Each section of an XSUB starts with the corresponding keyword, such as INIT: or CLEANUP:. However, the first two lines of an XSUB always contain the same data: descriptions of the return type and the names of the function and its parameters. Whatever immediately follows these is considered to be an INPUT: section unless explicitly marked with another keyword. (See ["The INPUT: Keyword"](#The-INPUT%3A-Keyword).)
An XSUB section continues until another section-start keyword is found.
###
The Argument Stack
The Perl argument stack is used to store the values which are sent as parameters to the XSUB and to store the XSUB's return value(s). In reality all Perl functions (including non-XSUB ones) keep their values on this stack all the same time, each limited to its own range of positions on the stack. In this document the first position on that stack which belongs to the active function will be referred to as position 0 for that function.
XSUBs refer to their stack arguments with the macro **ST(x)**, where *x* refers to a position in this XSUB's part of the stack. Position 0 for that function would be known to the XSUB as ST(0). The XSUB's incoming parameters and outgoing return values always begin at ST(0). For many simple cases the **xsubpp** compiler will generate the code necessary to handle the argument stack by embedding code fragments found in the typemaps. In more complex cases the programmer must supply the code.
###
The RETVAL Variable
The RETVAL variable is a special C variable that is declared automatically for you. The C type of RETVAL matches the return type of the C library function. The **xsubpp** compiler will declare this variable in each XSUB with non-`void` return type. By default the generated C function will use RETVAL to hold the return value of the C library function being called. In simple cases the value of RETVAL will be placed in ST(0) of the argument stack where it can be received by Perl as the return value of the XSUB.
If the XSUB has a return type of `void` then the compiler will not declare a RETVAL variable for that function. When using a PPCODE: section no manipulation of the RETVAL variable is required, the section may use direct stack manipulation to place output values on the stack.
If PPCODE: directive is not used, `void` return value should be used only for subroutines which do not return a value, *even if* CODE: directive is used which sets ST(0) explicitly.
Older versions of this document recommended to use `void` return value in such cases. It was discovered that this could lead to segfaults in cases when XSUB was *truly* `void`. This practice is now deprecated, and may be not supported at some future version. Use the return value `SV *` in such cases. (Currently `xsubpp` contains some heuristic code which tries to disambiguate between "truly-void" and "old-practice-declared-as-void" functions. Hence your code is at mercy of this heuristics unless you use `SV *` as return value.)
###
Returning SVs, AVs and HVs through RETVAL
When you're using RETVAL to return an `SV *`, there's some magic going on behind the scenes that should be mentioned. When you're manipulating the argument stack using the ST(x) macro, for example, you usually have to pay special attention to reference counts. (For more about reference counts, see <perlguts>.) To make your life easier, the typemap file automatically makes `RETVAL` mortal when you're returning an `SV *`. Thus, the following two XSUBs are more or less equivalent:
```
void
alpha()
PPCODE:
ST(0) = newSVpv("Hello World",0);
sv_2mortal(ST(0));
XSRETURN(1);
SV *
beta()
CODE:
RETVAL = newSVpv("Hello World",0);
OUTPUT:
RETVAL
```
This is quite useful as it usually improves readability. While this works fine for an `SV *`, it's unfortunately not as easy to have `AV *` or `HV *` as a return value. You *should* be able to write:
```
AV *
array()
CODE:
RETVAL = newAV();
/* do something with RETVAL */
OUTPUT:
RETVAL
```
But due to an unfixable bug (fixing it would break lots of existing CPAN modules) in the typemap file, the reference count of the `AV *` is not properly decremented. Thus, the above XSUB would leak memory whenever it is being called. The same problem exists for `HV *`, `CV *`, and `SVREF` (which indicates a scalar reference, not a general `SV *`). In XS code on perls starting with perl 5.16, you can override the typemaps for any of these types with a version that has proper handling of refcounts. In your `TYPEMAP` section, do
```
AV* T_AVREF_REFCOUNT_FIXED
```
to get the repaired variant. For backward compatibility with older versions of perl, you can instead decrement the reference count manually when you're returning one of the aforementioned types using `sv_2mortal`:
```
AV *
array()
CODE:
RETVAL = newAV();
sv_2mortal((SV*)RETVAL);
/* do something with RETVAL */
OUTPUT:
RETVAL
```
Remember that you don't have to do this for an `SV *`. The reference documentation for all core typemaps can be found in <perlxstypemap>.
###
The MODULE Keyword
The MODULE keyword is used to start the XS code and to specify the package of the functions which are being defined. All text preceding the first MODULE keyword is considered C code and is passed through to the output with POD stripped, but otherwise untouched. Every XS module will have a bootstrap function which is used to hook the XSUBs into Perl. The package name of this bootstrap function will match the value of the last MODULE statement in the XS source files. The value of MODULE should always remain constant within the same XS file, though this is not required.
The following example will start the XS code and will place all functions in a package named RPC.
```
MODULE = RPC
```
###
The PACKAGE Keyword
When functions within an XS source file must be separated into packages the PACKAGE keyword should be used. This keyword is used with the MODULE keyword and must follow immediately after it when used.
```
MODULE = RPC PACKAGE = RPC
[ XS code in package RPC ]
MODULE = RPC PACKAGE = RPCB
[ XS code in package RPCB ]
MODULE = RPC PACKAGE = RPC
[ XS code in package RPC ]
```
The same package name can be used more than once, allowing for non-contiguous code. This is useful if you have a stronger ordering principle than package names.
Although this keyword is optional and in some cases provides redundant information it should always be used. This keyword will ensure that the XSUBs appear in the desired package.
###
The PREFIX Keyword
The PREFIX keyword designates prefixes which should be removed from the Perl function names. If the C function is `rpcb_gettime()` and the PREFIX value is `rpcb_` then Perl will see this function as `gettime()`.
This keyword should follow the PACKAGE keyword when used. If PACKAGE is not used then PREFIX should follow the MODULE keyword.
```
MODULE = RPC PREFIX = rpc_
MODULE = RPC PACKAGE = RPCB PREFIX = rpcb_
```
###
The OUTPUT: Keyword
The OUTPUT: keyword indicates that certain function parameters should be updated (new values made visible to Perl) when the XSUB terminates or that certain values should be returned to the calling Perl function. For simple functions which have no CODE: or PPCODE: section, such as the sin() function above, the RETVAL variable is automatically designated as an output value. For more complex functions the **xsubpp** compiler will need help to determine which variables are output variables.
This keyword will normally be used to complement the CODE: keyword. The RETVAL variable is not recognized as an output variable when the CODE: keyword is present. The OUTPUT: keyword is used in this situation to tell the compiler that RETVAL really is an output variable.
The OUTPUT: keyword can also be used to indicate that function parameters are output variables. This may be necessary when a parameter has been modified within the function and the programmer would like the update to be seen by Perl.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
OUTPUT:
timep
```
The OUTPUT: keyword will also allow an output parameter to be mapped to a matching piece of code rather than to a typemap.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
OUTPUT:
timep sv_setnv(ST(1), (double)timep);
```
**xsubpp** emits an automatic `SvSETMAGIC()` for all parameters in the OUTPUT section of the XSUB, except RETVAL. This is the usually desired behavior, as it takes care of properly invoking 'set' magic on output parameters (needed for hash or array element parameters that must be created if they didn't exist). If for some reason, this behavior is not desired, the OUTPUT section may contain a `SETMAGIC: DISABLE` line to disable it for the remainder of the parameters in the OUTPUT section. Likewise, `SETMAGIC: ENABLE` can be used to reenable it for the remainder of the OUTPUT section. See <perlguts> for more details about 'set' magic.
###
The NO\_OUTPUT Keyword
The NO\_OUTPUT can be placed as the first token of the XSUB. This keyword indicates that while the C subroutine we provide an interface to has a non-`void` return type, the return value of this C subroutine should not be returned from the generated Perl subroutine.
With this keyword present ["The RETVAL Variable"](#The-RETVAL-Variable) is created, and in the generated call to the subroutine this variable is assigned to, but the value of this variable is not going to be used in the auto-generated code.
This keyword makes sense only if `RETVAL` is going to be accessed by the user-supplied code. It is especially useful to make a function interface more Perl-like, especially when the C return value is just an error condition indicator. For example,
```
NO_OUTPUT int
delete_file(char *name)
POSTCALL:
if (RETVAL != 0)
croak("Error %d while deleting file '%s'", RETVAL, name);
```
Here the generated XS function returns nothing on success, and will die() with a meaningful error message on error.
###
The CODE: Keyword
This keyword is used in more complicated XSUBs which require special handling for the C function. The RETVAL variable is still declared, but it will not be returned unless it is specified in the OUTPUT: section.
The following XSUB is for a C function which requires special handling of its parameters. The Perl usage is given first.
```
$status = rpcb_gettime( "localhost", $timep );
```
The XSUB follows.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t timep
CODE:
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
###
The INIT: Keyword
The INIT: keyword allows initialization to be inserted into the XSUB before the compiler generates the call to the C function. Unlike the CODE: keyword above, this keyword does not affect the way the compiler handles RETVAL.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
INIT:
printf("# Host is %s\n", host );
OUTPUT:
timep
```
Another use for the INIT: section is to check for preconditions before making a call to the C function:
```
long long
lldiv(a,b)
long long a
long long b
INIT:
if (a == 0 && b == 0)
XSRETURN_UNDEF;
if (b == 0)
croak("lldiv: cannot divide by 0");
```
###
The NO\_INIT Keyword
The NO\_INIT keyword is used to indicate that a function parameter is being used only as an output value. The **xsubpp** compiler will normally generate code to read the values of all function parameters from the argument stack and assign them to C variables upon entry to the function. NO\_INIT will tell the compiler that some parameters will be used for output rather than for input and that they will be handled before the function terminates.
The following example shows a variation of the rpcb\_gettime() function. This function uses the timep variable only as an output variable and does not care about its initial contents.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep = NO_INIT
OUTPUT:
timep
```
###
The TYPEMAP: Keyword
Starting with Perl 5.16, you can embed typemaps into your XS code instead of or in addition to typemaps in a separate file. Multiple such embedded typemaps will be processed in order of appearance in the XS code and like local typemap files take precedence over the default typemap, the embedded typemaps may overwrite previous definitions of TYPEMAP, INPUT, and OUTPUT stanzas. The syntax for embedded typemaps is
```
TYPEMAP: <<HERE
... your typemap code here ...
HERE
```
where the `TYPEMAP` keyword must appear in the first column of a new line.
Refer to <perlxstypemap> for details on writing typemaps.
###
Initializing Function Parameters
C function parameters are normally initialized with their values from the argument stack (which in turn contains the parameters that were passed to the XSUB from Perl). The typemaps contain the code segments which are used to translate the Perl values to the C parameters. The programmer, however, is allowed to override the typemaps and supply alternate (or additional) initialization code. Initialization code starts with the first `=`, `;` or `+` on a line in the INPUT: section. The only exception happens if this `;` terminates the line, then this `;` is quietly ignored.
The following code demonstrates how to supply initialization code for function parameters. The initialization code is eval'ed within double quotes by the compiler before it is added to the output so anything which should be interpreted literally [mainly `$`, `@`, or `\\`] must be protected with backslashes. The variables `$var`, `$arg`, and `$type` can be used as in typemaps.
```
bool_t
rpcb_gettime(host,timep)
char *host = (char *)SvPVbyte_nolen($arg);
time_t &timep = 0;
OUTPUT:
timep
```
This should not be used to supply default values for parameters. One would normally use this when a function parameter must be processed by another library function before it can be used. Default parameters are covered in the next section.
If the initialization begins with `=`, then it is output in the declaration for the input variable, replacing the initialization supplied by the typemap. If the initialization begins with `;` or `+`, then it is performed after all of the input variables have been declared. In the `;` case the initialization normally supplied by the typemap is not performed. For the `+` case, the declaration for the variable will include the initialization from the typemap. A global variable, `%v`, is available for the truly rare case where information from one initialization is needed in another initialization.
Here's a truly obscure example:
```
bool_t
rpcb_gettime(host,timep)
time_t &timep; /* \$v{timep}=@{[$v{timep}=$arg]} */
char *host + SvOK($v{timep}) ? SvPVbyte_nolen($arg) : NULL;
OUTPUT:
timep
```
The construct `\$v{timep}=@{[$v{timep}=$arg]}` used in the above example has a two-fold purpose: first, when this line is processed by **xsubpp**, the Perl snippet `$v{timep}=$arg` is evaluated. Second, the text of the evaluated snippet is output into the generated C file (inside a C comment)! During the processing of `char *host` line, `$arg` will evaluate to `ST(0)`, and `$v{timep}` will evaluate to `ST(1)`.
###
Default Parameter Values
Default values for XSUB arguments can be specified by placing an assignment statement in the parameter list. The default value may be a number, a string or the special string `NO_INIT`. Defaults should always be used on the right-most parameters only.
To allow the XSUB for rpcb\_gettime() to have a default host value the parameters to the XSUB could be rearranged. The XSUB will then call the real rpcb\_gettime() function with the parameters in the correct order. This XSUB can be called from Perl with either of the following statements:
```
$status = rpcb_gettime( $timep, $host );
$status = rpcb_gettime( $timep );
```
The XSUB will look like the code which follows. A CODE: block is used to call the real rpcb\_gettime() function with the parameters in the correct order for that function.
```
bool_t
rpcb_gettime(timep,host="localhost")
char *host
time_t timep = NO_INIT
CODE:
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
###
The PREINIT: Keyword
The PREINIT: keyword allows extra variables to be declared immediately before or after the declarations of the parameters from the INPUT: section are emitted.
If a variable is declared inside a CODE: section it will follow any typemap code that is emitted for the input parameters. This may result in the declaration ending up after C code, which is C syntax error. Similar errors may happen with an explicit `;`-type or `+`-type initialization of parameters is used (see ["Initializing Function Parameters"](#Initializing-Function-Parameters)). Declaring these variables in an INIT: section will not help.
In such cases, to force an additional variable to be declared together with declarations of other variables, place the declaration into a PREINIT: section. The PREINIT: keyword may be used one or more times within an XSUB.
The following examples are equivalent, but if the code is using complex typemaps then the first example is safer.
```
bool_t
rpcb_gettime(timep)
time_t timep = NO_INIT
PREINIT:
char *host = "localhost";
CODE:
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
For this particular case an INIT: keyword would generate the same C code as the PREINIT: keyword. Another correct, but error-prone example:
```
bool_t
rpcb_gettime(timep)
time_t timep = NO_INIT
CODE:
char *host = "localhost";
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
Another way to declare `host` is to use a C block in the CODE: section:
```
bool_t
rpcb_gettime(timep)
time_t timep = NO_INIT
CODE:
{
char *host = "localhost";
RETVAL = rpcb_gettime( host, &timep );
}
OUTPUT:
timep
RETVAL
```
The ability to put additional declarations before the typemap entries are processed is very handy in the cases when typemap conversions manipulate some global state:
```
MyObject
mutate(o)
PREINIT:
MyState st = global_state;
INPUT:
MyObject o;
CLEANUP:
reset_to(global_state, st);
```
Here we suppose that conversion to `MyObject` in the INPUT: section and from MyObject when processing RETVAL will modify a global variable `global_state`. After these conversions are performed, we restore the old value of `global_state` (to avoid memory leaks, for example).
There is another way to trade clarity for compactness: INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine. Thus the above code for mutate() can be rewritten as
```
MyObject
mutate(o)
MyState st = global_state;
MyObject o;
CLEANUP:
reset_to(global_state, st);
```
and the code for rpcb\_gettime() can be rewritten as
```
bool_t
rpcb_gettime(timep)
time_t timep = NO_INIT
char *host = "localhost";
C_ARGS:
host, &timep
OUTPUT:
timep
RETVAL
```
###
The SCOPE: Keyword
The SCOPE: keyword allows scoping to be enabled for a particular XSUB. If enabled, the XSUB will invoke ENTER and LEAVE automatically.
To support potentially complex type mappings, if a typemap entry used by an XSUB contains a comment like `/*scope*/` then scoping will be automatically enabled for that XSUB.
To enable scoping:
```
SCOPE: ENABLE
```
To disable scoping:
```
SCOPE: DISABLE
```
###
The INPUT: Keyword
The XSUB's parameters are usually evaluated immediately after entering the XSUB. The INPUT: keyword can be used to force those parameters to be evaluated a little later. The INPUT: keyword can be used multiple times within an XSUB and can be used to list one or more input variables. This keyword is used with the PREINIT: keyword.
The following example shows how the input parameter `timep` can be evaluated late, after a PREINIT.
```
bool_t
rpcb_gettime(host,timep)
char *host
PREINIT:
time_t tt;
INPUT:
time_t timep
CODE:
RETVAL = rpcb_gettime( host, &tt );
timep = tt;
OUTPUT:
timep
RETVAL
```
The next example shows each input parameter evaluated late.
```
bool_t
rpcb_gettime(host,timep)
PREINIT:
time_t tt;
INPUT:
char *host
PREINIT:
char *h;
INPUT:
time_t timep
CODE:
h = host;
RETVAL = rpcb_gettime( h, &tt );
timep = tt;
OUTPUT:
timep
RETVAL
```
Since INPUT sections allow declaration of C variables which do not appear in the parameter list of a subroutine, this may be shortened to:
```
bool_t
rpcb_gettime(host,timep)
time_t tt;
char *host;
char *h = host;
time_t timep;
CODE:
RETVAL = rpcb_gettime( h, &tt );
timep = tt;
OUTPUT:
timep
RETVAL
```
(We used our knowledge that input conversion for `char *` is a "simple" one, thus `host` is initialized on the declaration line, and our assignment `h = host` is not performed too early. Otherwise one would need to have the assignment `h = host` in a CODE: or INIT: section.)
###
The IN/OUTLIST/IN\_OUTLIST/OUT/IN\_OUT Keywords
In the list of parameters for an XSUB, one can precede parameter names by the `IN`/`OUTLIST`/`IN_OUTLIST`/`OUT`/`IN_OUT` keywords. `IN` keyword is the default, the other keywords indicate how the Perl interface should differ from the C interface.
Parameters preceded by `OUTLIST`/`IN_OUTLIST`/`OUT`/`IN_OUT` keywords are considered to be used by the C subroutine *via pointers*. `OUTLIST`/`OUT` keywords indicate that the C subroutine does not inspect the memory pointed by this parameter, but will write through this pointer to provide additional return values.
Parameters preceded by `OUTLIST` keyword do not appear in the usage signature of the generated Perl function.
Parameters preceded by `IN_OUTLIST`/`IN_OUT`/`OUT` *do* appear as parameters to the Perl function. With the exception of `OUT`-parameters, these parameters are converted to the corresponding C type, then pointers to these data are given as arguments to the C function. It is expected that the C function will write through these pointers.
The return list of the generated Perl function consists of the C return value from the function (unless the XSUB is of `void` return type or `The NO_OUTPUT Keyword` was used) followed by all the `OUTLIST` and `IN_OUTLIST` parameters (in the order of appearance). On the return from the XSUB the `IN_OUT`/`OUT` Perl parameter will be modified to have the values written by the C function.
For example, an XSUB
```
void
day_month(OUTLIST day, IN unix_time, OUTLIST month)
int day
int unix_time
int month
```
should be used from Perl as
```
my ($day, $month) = day_month(time);
```
The C signature of the corresponding function should be
```
void day_month(int *day, int unix_time, int *month);
```
The `IN`/`OUTLIST`/`IN_OUTLIST`/`IN_OUT`/`OUT` keywords can be mixed with ANSI-style declarations, as in
```
void
day_month(OUTLIST int day, int unix_time, OUTLIST int month)
```
(here the optional `IN` keyword is omitted).
The `IN_OUT` parameters are identical with parameters introduced with ["The & Unary Operator"](#The-%26-Unary-Operator) and put into the `OUTPUT:` section (see ["The OUTPUT: Keyword"](#The-OUTPUT%3A-Keyword)). The `IN_OUTLIST` parameters are very similar, the only difference being that the value C function writes through the pointer would not modify the Perl parameter, but is put in the output list.
The `OUTLIST`/`OUT` parameter differ from `IN_OUTLIST`/`IN_OUT` parameters only by the initial value of the Perl parameter not being read (and not being given to the C function - which gets some garbage instead). For example, the same C function as above can be interfaced with as
```
void day_month(OUT int day, int unix_time, OUT int month);
```
or
```
void
day_month(day, unix_time, month)
int &day = NO_INIT
int unix_time
int &month = NO_INIT
OUTPUT:
day
month
```
However, the generated Perl function is called in very C-ish style:
```
my ($day, $month);
day_month($day, time, $month);
```
###
The `length(NAME)` Keyword
If one of the input arguments to the C function is the length of a string argument `NAME`, one can substitute the name of the length-argument by `length(NAME)` in the XSUB declaration. This argument must be omitted when the generated Perl function is called. E.g.,
```
void
dump_chars(char *s, short l)
{
short n = 0;
while (n < l) {
printf("s[%d] = \"\\%#03o\"\n", n, (int)s[n]);
n++;
}
}
MODULE = x PACKAGE = x
void dump_chars(char *s, short length(s))
```
should be called as `dump_chars($string)`.
This directive is supported with ANSI-type function declarations only.
###
Variable-length Parameter Lists
XSUBs can have variable-length parameter lists by specifying an ellipsis `(...)` in the parameter list. This use of the ellipsis is similar to that found in ANSI C. The programmer is able to determine the number of arguments passed to the XSUB by examining the `items` variable which the **xsubpp** compiler supplies for all XSUBs. By using this mechanism one can create an XSUB which accepts a list of parameters of unknown length.
The *host* parameter for the rpcb\_gettime() XSUB can be optional so the ellipsis can be used to indicate that the XSUB will take a variable number of parameters. Perl should be able to call this XSUB with either of the following statements.
```
$status = rpcb_gettime( $timep, $host );
$status = rpcb_gettime( $timep );
```
The XS code, with ellipsis, follows.
```
bool_t
rpcb_gettime(timep, ...)
time_t timep = NO_INIT
PREINIT:
char *host = "localhost";
CODE:
if( items > 1 )
host = (char *)SvPVbyte_nolen(ST(1));
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
###
The C\_ARGS: Keyword
The C\_ARGS: keyword allows creating of XSUBS which have different calling sequence from Perl than from C, without a need to write CODE: or PPCODE: section. The contents of the C\_ARGS: paragraph is put as the argument to the called C function without any change.
For example, suppose that a C function is declared as
```
symbolic nth_derivative(int n, symbolic function, int flags);
```
and that the default flags are kept in a global C variable `default_flags`. Suppose that you want to create an interface which is called as
```
$second_deriv = $function->nth_derivative(2);
```
To do this, declare the XSUB as
```
symbolic
nth_derivative(function, n)
symbolic function
int n
C_ARGS:
n, function, default_flags
```
###
The PPCODE: Keyword
The PPCODE: keyword is an alternate form of the CODE: keyword and is used to tell the **xsubpp** compiler that the programmer is supplying the code to control the argument stack for the XSUBs return values. Occasionally one will want an XSUB to return a list of values rather than a single value. In these cases one must use PPCODE: and then explicitly push the list of values on the stack. The PPCODE: and CODE: keywords should not be used together within the same XSUB.
The actual difference between PPCODE: and CODE: sections is in the initialization of `SP` macro (which stands for the *current* Perl stack pointer), and in the handling of data on the stack when returning from an XSUB. In CODE: sections SP preserves the value which was on entry to the XSUB: SP is on the function pointer (which follows the last parameter). In PPCODE: sections SP is moved backward to the beginning of the parameter list, which allows `PUSH*()` macros to place output values in the place Perl expects them to be when the XSUB returns back to Perl.
The generated trailer for a CODE: section ensures that the number of return values Perl will see is either 0 or 1 (depending on the `void`ness of the return value of the C function, and heuristics mentioned in ["The RETVAL Variable"](#The-RETVAL-Variable)). The trailer generated for a PPCODE: section is based on the number of return values and on the number of times `SP` was updated by `[X]PUSH*()` macros.
Note that macros `ST(i)`, `XST_m*()` and `XSRETURN*()` work equally well in CODE: sections and PPCODE: sections.
The following XSUB will call the C rpcb\_gettime() function and will return its two output values, timep and status, to Perl as a single list.
```
void
rpcb_gettime(host)
char *host
PREINIT:
time_t timep;
bool_t status;
PPCODE:
status = rpcb_gettime( host, &timep );
EXTEND(SP, 2);
PUSHs(sv_2mortal(newSViv(status)));
PUSHs(sv_2mortal(newSViv(timep)));
```
Notice that the programmer must supply the C code necessary to have the real rpcb\_gettime() function called and to have the return values properly placed on the argument stack.
The `void` return type for this function tells the **xsubpp** compiler that the RETVAL variable is not needed or used and that it should not be created. In most scenarios the void return type should be used with the PPCODE: directive.
The EXTEND() macro is used to make room on the argument stack for 2 return values. The PPCODE: directive causes the **xsubpp** compiler to create a stack pointer available as `SP`, and it is this pointer which is being used in the EXTEND() macro. The values are then pushed onto the stack with the PUSHs() macro.
Now the rpcb\_gettime() function can be used from Perl with the following statement.
```
($status, $timep) = rpcb_gettime("localhost");
```
When handling output parameters with a PPCODE section, be sure to handle 'set' magic properly. See <perlguts> for details about 'set' magic.
###
Returning Undef And Empty Lists
Occasionally the programmer will want to return simply `undef` or an empty list if a function fails rather than a separate status value. The rpcb\_gettime() function offers just this situation. If the function succeeds we would like to have it return the time and if it fails we would like to have undef returned. In the following Perl code the value of $timep will either be undef or it will be a valid time.
```
$timep = rpcb_gettime( "localhost" );
```
The following XSUB uses the `SV *` return type as a mnemonic only, and uses a CODE: block to indicate to the compiler that the programmer has supplied all the necessary code. The sv\_newmortal() call will initialize the return value to undef, making that the default return value.
```
SV *
rpcb_gettime(host)
char * host
PREINIT:
time_t timep;
bool_t x;
CODE:
ST(0) = sv_newmortal();
if( rpcb_gettime( host, &timep ) )
sv_setnv( ST(0), (double)timep);
```
The next example demonstrates how one would place an explicit undef in the return value, should the need arise.
```
SV *
rpcb_gettime(host)
char * host
PREINIT:
time_t timep;
bool_t x;
CODE:
if( rpcb_gettime( host, &timep ) ){
ST(0) = sv_newmortal();
sv_setnv( ST(0), (double)timep);
}
else{
ST(0) = &PL_sv_undef;
}
```
To return an empty list one must use a PPCODE: block and then not push return values on the stack.
```
void
rpcb_gettime(host)
char *host
PREINIT:
time_t timep;
PPCODE:
if( rpcb_gettime( host, &timep ) )
PUSHs(sv_2mortal(newSViv(timep)));
else{
/* Nothing pushed on stack, so an empty
* list is implicitly returned. */
}
```
Some people may be inclined to include an explicit `return` in the above XSUB, rather than letting control fall through to the end. In those situations `XSRETURN_EMPTY` should be used, instead. This will ensure that the XSUB stack is properly adjusted. Consult <perlapi> for other `XSRETURN` macros.
Since `XSRETURN_*` macros can be used with CODE blocks as well, one can rewrite this example as:
```
int
rpcb_gettime(host)
char *host
PREINIT:
time_t timep;
CODE:
RETVAL = rpcb_gettime( host, &timep );
if (RETVAL == 0)
XSRETURN_UNDEF;
OUTPUT:
RETVAL
```
In fact, one can put this check into a POSTCALL: section as well. Together with PREINIT: simplifications, this leads to:
```
int
rpcb_gettime(host)
char *host
time_t timep;
POSTCALL:
if (RETVAL == 0)
XSRETURN_UNDEF;
```
###
The REQUIRE: Keyword
The REQUIRE: keyword is used to indicate the minimum version of the **xsubpp** compiler needed to compile the XS module. An XS module which contains the following statement will compile with only **xsubpp** version 1.922 or greater:
```
REQUIRE: 1.922
```
###
The CLEANUP: Keyword
This keyword can be used when an XSUB requires special cleanup procedures before it terminates. When the CLEANUP: keyword is used it must follow any CODE:, or OUTPUT: blocks which are present in the XSUB. The code specified for the cleanup block will be added as the last statements in the XSUB.
###
The POSTCALL: Keyword
This keyword can be used when an XSUB requires special procedures executed after the C subroutine call is performed. When the POSTCALL: keyword is used it must precede OUTPUT: and CLEANUP: blocks which are present in the XSUB.
See examples in ["The NO\_OUTPUT Keyword"](#The-NO_OUTPUT-Keyword) and ["Returning Undef And Empty Lists"](#Returning-Undef-And-Empty-Lists).
The POSTCALL: block does not make a lot of sense when the C subroutine call is supplied by user by providing either CODE: or PPCODE: section.
###
The BOOT: Keyword
The BOOT: keyword is used to add code to the extension's bootstrap function. The bootstrap function is generated by the **xsubpp** compiler and normally holds the statements necessary to register any XSUBs with Perl. With the BOOT: keyword the programmer can tell the compiler to add extra statements to the bootstrap function.
This keyword may be used any time after the first MODULE keyword and should appear on a line by itself. The first blank line after the keyword will terminate the code block.
```
BOOT:
# The following message will be printed when the
# bootstrap function executes.
printf("Hello from the bootstrap!\n");
```
###
The VERSIONCHECK: Keyword
The VERSIONCHECK: keyword corresponds to **xsubpp**'s `-versioncheck` and `-noversioncheck` options. This keyword overrides the command line options. Version checking is enabled by default. When version checking is enabled the XS module will attempt to verify that its version matches the version of the PM module.
To enable version checking:
```
VERSIONCHECK: ENABLE
```
To disable version checking:
```
VERSIONCHECK: DISABLE
```
Note that if the version of the PM module is an NV (a floating point number), it will be stringified with a possible loss of precision (currently chopping to nine decimal places) so that it may not match the version of the XS module anymore. Quoting the $VERSION declaration to make it a string is recommended if long version numbers are used.
###
The PROTOTYPES: Keyword
The PROTOTYPES: keyword corresponds to **xsubpp**'s `-prototypes` and `-noprototypes` options. This keyword overrides the command line options. Prototypes are disabled by default. When prototypes are enabled, XSUBs will be given Perl prototypes. This keyword may be used multiple times in an XS module to enable and disable prototypes for different parts of the module. Note that **xsubpp** will nag you if you don't explicitly enable or disable prototypes, with:
```
Please specify prototyping behavior for Foo.xs (see perlxs manual)
```
To enable prototypes:
```
PROTOTYPES: ENABLE
```
To disable prototypes:
```
PROTOTYPES: DISABLE
```
###
The PROTOTYPE: Keyword
This keyword is similar to the PROTOTYPES: keyword above but can be used to force **xsubpp** to use a specific prototype for the XSUB. This keyword overrides all other prototype options and keywords but affects only the current XSUB. Consult ["Prototypes" in perlsub](perlsub#Prototypes) for information about Perl prototypes.
```
bool_t
rpcb_gettime(timep, ...)
time_t timep = NO_INIT
PROTOTYPE: $;$
PREINIT:
char *host = "localhost";
CODE:
if( items > 1 )
host = (char *)SvPVbyte_nolen(ST(1));
RETVAL = rpcb_gettime( host, &timep );
OUTPUT:
timep
RETVAL
```
If the prototypes are enabled, you can disable it locally for a given XSUB as in the following example:
```
void
rpcb_gettime_noproto()
PROTOTYPE: DISABLE
...
```
###
The ALIAS: Keyword
The ALIAS: keyword allows an XSUB to have two or more unique Perl names and to know which of those names was used when it was invoked. The Perl names may be fully-qualified with package names. Each alias is given an index. The compiler will setup a variable called `ix` which contain the index of the alias which was used. When the XSUB is called with its declared name `ix` will be 0.
The following example will create aliases `FOO::gettime()` and `BAR::getit()` for this function.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
ALIAS:
FOO::gettime = 1
BAR::getit = 2
INIT:
printf("# ix = %d\n", ix );
OUTPUT:
timep
```
###
The OVERLOAD: Keyword
Instead of writing an overloaded interface using pure Perl, you can also use the OVERLOAD keyword to define additional Perl names for your functions (like the ALIAS: keyword above). However, the overloaded functions must be defined in such a way as to accept the number of parameters supplied by perl's overload system. For most overload methods, it will be three parameters; for the `nomethod` function it will be four. However, the bitwise operators `&`, `|`, `^`, and `~` may be called with three *or* five arguments (see <overload>).
If any function has the OVERLOAD: keyword, several additional lines will be defined in the c file generated by xsubpp in order to register with the overload magic.
Since blessed objects are actually stored as RV's, it is useful to use the typemap features to preprocess parameters and extract the actual SV stored within the blessed RV. See the sample for T\_PTROBJ\_SPECIAL below.
To use the OVERLOAD: keyword, create an XS function which takes three input parameters (or use the C-style '...' definition) like this:
```
SV *
cmp (lobj, robj, swap)
My_Module_obj lobj
My_Module_obj robj
IV swap
OVERLOAD: cmp <=>
{ /* function defined here */}
```
In this case, the function will overload both of the three way comparison operators. For all overload operations using non-alpha characters, you must type the parameter without quoting, separating multiple overloads with whitespace. Note that "" (the stringify overload) should be entered as \"\" (i.e. escaped).
Since, as mentioned above, bitwise operators may take extra arguments, you may want to use something like `(lobj, robj, swap, ...)` (with literal `...`) as your parameter list.
###
The FALLBACK: Keyword
In addition to the OVERLOAD keyword, if you need to control how Perl autogenerates missing overloaded operators, you can set the FALLBACK keyword in the module header section, like this:
```
MODULE = RPC PACKAGE = RPC
FALLBACK: TRUE
...
```
where FALLBACK can take any of the three values TRUE, FALSE, or UNDEF. If you do not set any FALLBACK value when using OVERLOAD, it defaults to UNDEF. FALLBACK is not used except when one or more functions using OVERLOAD have been defined. Please see ["fallback" in overload](overload#fallback) for more details.
###
The INTERFACE: Keyword
This keyword declares the current XSUB as a keeper of the given calling signature. If some text follows this keyword, it is considered as a list of functions which have this signature, and should be attached to the current XSUB.
For example, if you have 4 C functions multiply(), divide(), add(), subtract() all having the signature:
```
symbolic f(symbolic, symbolic);
```
you can make them all to use the same XSUB using this:
```
symbolic
interface_s_ss(arg1, arg2)
symbolic arg1
symbolic arg2
INTERFACE:
multiply divide
add subtract
```
(This is the complete XSUB code for 4 Perl functions!) Four generated Perl function share names with corresponding C functions.
The advantage of this approach comparing to ALIAS: keyword is that there is no need to code a switch statement, each Perl function (which shares the same XSUB) knows which C function it should call. Additionally, one can attach an extra function remainder() at runtime by using
```
CV *mycv = newXSproto("Symbolic::remainder",
XS_Symbolic_interface_s_ss, __FILE__, "$$");
XSINTERFACE_FUNC_SET(mycv, remainder);
```
say, from another XSUB. (This example supposes that there was no INTERFACE\_MACRO: section, otherwise one needs to use something else instead of `XSINTERFACE_FUNC_SET`, see the next section.)
###
The INTERFACE\_MACRO: Keyword
This keyword allows one to define an INTERFACE using a different way to extract a function pointer from an XSUB. The text which follows this keyword should give the name of macros which would extract/set a function pointer. The extractor macro is given return type, `CV*`, and `XSANY.any_dptr` for this `CV*`. The setter macro is given cv, and the function pointer.
The default value is `XSINTERFACE_FUNC` and `XSINTERFACE_FUNC_SET`. An INTERFACE keyword with an empty list of functions can be omitted if INTERFACE\_MACRO keyword is used.
Suppose that in the previous example functions pointers for multiply(), divide(), add(), subtract() are kept in a global C array `fp[]` with offsets being `multiply_off`, `divide_off`, `add_off`, `subtract_off`. Then one can use
```
#define XSINTERFACE_FUNC_BYOFFSET(ret,cv,f) \
((XSINTERFACE_CVT_ANON(ret))fp[CvXSUBANY(cv).any_i32])
#define XSINTERFACE_FUNC_BYOFFSET_set(cv,f) \
CvXSUBANY(cv).any_i32 = CAT2( f, _off )
```
in C section,
```
symbolic
interface_s_ss(arg1, arg2)
symbolic arg1
symbolic arg2
INTERFACE_MACRO:
XSINTERFACE_FUNC_BYOFFSET
XSINTERFACE_FUNC_BYOFFSET_set
INTERFACE:
multiply divide
add subtract
```
in XSUB section.
###
The INCLUDE: Keyword
This keyword can be used to pull other files into the XS module. The other files may have XS code. INCLUDE: can also be used to run a command to generate the XS code to be pulled into the module.
The file *Rpcb1.xsh* contains our `rpcb_gettime()` function:
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
OUTPUT:
timep
```
The XS module can use INCLUDE: to pull that file into it.
```
INCLUDE: Rpcb1.xsh
```
If the parameters to the INCLUDE: keyword are followed by a pipe (`|`) then the compiler will interpret the parameters as a command. This feature is mildly deprecated in favour of the `INCLUDE_COMMAND:` directive, as documented below.
```
INCLUDE: cat Rpcb1.xsh |
```
Do not use this to run perl: `INCLUDE: perl |` will run the perl that happens to be the first in your path and not necessarily the same perl that is used to run `xsubpp`. See ["The INCLUDE\_COMMAND: Keyword"](#The-INCLUDE_COMMAND%3A-Keyword).
###
The INCLUDE\_COMMAND: Keyword
Runs the supplied command and includes its output into the current XS document. `INCLUDE_COMMAND` assigns special meaning to the `$^X` token in that it runs the same perl interpreter that is running `xsubpp`:
```
INCLUDE_COMMAND: cat Rpcb1.xsh
INCLUDE_COMMAND: $^X -e ...
```
###
The CASE: Keyword
The CASE: keyword allows an XSUB to have multiple distinct parts with each part acting as a virtual XSUB. CASE: is greedy and if it is used then all other XS keywords must be contained within a CASE:. This means nothing may precede the first CASE: in the XSUB and anything following the last CASE: is included in that case.
A CASE: might switch via a parameter of the XSUB, via the `ix` ALIAS: variable (see ["The ALIAS: Keyword"](#The-ALIAS%3A-Keyword)), or maybe via the `items` variable (see ["Variable-length Parameter Lists"](#Variable-length-Parameter-Lists)). The last CASE: becomes the **default** case if it is not associated with a conditional. The following example shows CASE switched via `ix` with a function `rpcb_gettime()` having an alias `x_gettime()`. When the function is called as `rpcb_gettime()` its parameters are the usual `(char *host, time_t *timep)`, but when the function is called as `x_gettime()` its parameters are reversed, `(time_t *timep, char *host)`.
```
long
rpcb_gettime(a,b)
CASE: ix == 1
ALIAS:
x_gettime = 1
INPUT:
# 'a' is timep, 'b' is host
char *b
time_t a = NO_INIT
CODE:
RETVAL = rpcb_gettime( b, &a );
OUTPUT:
a
RETVAL
CASE:
# 'a' is host, 'b' is timep
char *a
time_t &b = NO_INIT
OUTPUT:
b
RETVAL
```
That function can be called with either of the following statements. Note the different argument lists.
```
$status = rpcb_gettime( $host, $timep );
$status = x_gettime( $timep, $host );
```
###
The EXPORT\_XSUB\_SYMBOLS: Keyword
The EXPORT\_XSUB\_SYMBOLS: keyword is likely something you will never need. In perl versions earlier than 5.16.0, this keyword does nothing. Starting with 5.16, XSUB symbols are no longer exported by default. That is, they are `static` functions. If you include
```
EXPORT_XSUB_SYMBOLS: ENABLE
```
in your XS code, the XSUBs following this line will not be declared `static`. You can later disable this with
```
EXPORT_XSUB_SYMBOLS: DISABLE
```
which, again, is the default that you should probably never change. You cannot use this keyword on versions of perl before 5.16 to make XSUBs `static`.
###
The & Unary Operator
The `&` unary operator in the INPUT: section is used to tell **xsubpp** that it should convert a Perl value to/from C using the C type to the left of `&`, but provide a pointer to this value when the C function is called.
This is useful to avoid a CODE: block for a C function which takes a parameter by reference. Typically, the parameter should be not a pointer type (an `int` or `long` but not an `int*` or `long*`).
The following XSUB will generate incorrect C code. The **xsubpp** compiler will turn this into code which calls `rpcb_gettime()` with parameters `(char *host, time_t timep)`, but the real `rpcb_gettime()` wants the `timep` parameter to be of type `time_t*` rather than `time_t`.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t timep
OUTPUT:
timep
```
That problem is corrected by using the `&` operator. The **xsubpp** compiler will now turn this into code which calls `rpcb_gettime()` correctly with parameters `(char *host, time_t *timep)`. It does this by carrying the `&` through, so the function call looks like `rpcb_gettime(host, &timep)`.
```
bool_t
rpcb_gettime(host,timep)
char *host
time_t &timep
OUTPUT:
timep
```
###
Inserting POD, Comments and C Preprocessor Directives
C preprocessor directives are allowed within BOOT:, PREINIT: INIT:, CODE:, PPCODE:, POSTCALL:, and CLEANUP: blocks, as well as outside the functions. Comments are allowed anywhere after the MODULE keyword. The compiler will pass the preprocessor directives through untouched and will remove the commented lines. POD documentation is allowed at any point, both in the C and XS language sections. POD must be terminated with a `=cut` command; `xsubpp` will exit with an error if it does not. It is very unlikely that human generated C code will be mistaken for POD, as most indenting styles result in whitespace in front of any line starting with `=`. Machine generated XS files may fall into this trap unless care is taken to ensure that a space breaks the sequence "\n=".
Comments can be added to XSUBs by placing a `#` as the first non-whitespace of a line. Care should be taken to avoid making the comment look like a C preprocessor directive, lest it be interpreted as such. The simplest way to prevent this is to put whitespace in front of the `#`.
If you use preprocessor directives to choose one of two versions of a function, use
```
#if ... version1
#else /* ... version2 */
#endif
```
and not
```
#if ... version1
#endif
#if ... version2
#endif
```
because otherwise **xsubpp** will believe that you made a duplicate definition of the function. Also, put a blank line before the #else/#endif so it will not be seen as part of the function body.
###
Using XS With C++
If an XSUB name contains `::`, it is considered to be a C++ method. The generated Perl function will assume that its first argument is an object pointer. The object pointer will be stored in a variable called THIS. The object should have been created by C++ with the new() function and should be blessed by Perl with the sv\_setref\_pv() macro. The blessing of the object by Perl can be handled by a typemap. An example typemap is shown at the end of this section.
If the return type of the XSUB includes `static`, the method is considered to be a static method. It will call the C++ function using the class::method() syntax. If the method is not static the function will be called using the THIS->method() syntax.
The next examples will use the following C++ class.
```
class color {
public:
color();
~color();
int blue();
void set_blue( int );
private:
int c_blue;
};
```
The XSUBs for the blue() and set\_blue() methods are defined with the class name but the parameter for the object (THIS, or "self") is implicit and is not listed.
```
int
color::blue()
void
color::set_blue( val )
int val
```
Both Perl functions will expect an object as the first parameter. In the generated C++ code the object is called `THIS`, and the method call will be performed on this object. So in the C++ code the blue() and set\_blue() methods will be called as this:
```
RETVAL = THIS->blue();
THIS->set_blue( val );
```
You could also write a single get/set method using an optional argument:
```
int
color::blue( val = NO_INIT )
int val
PROTOTYPE $;$
CODE:
if (items > 1)
THIS->set_blue( val );
RETVAL = THIS->blue();
OUTPUT:
RETVAL
```
If the function's name is **DESTROY** then the C++ `delete` function will be called and `THIS` will be given as its parameter. The generated C++ code for
```
void
color::DESTROY()
```
will look like this:
```
color *THIS = ...; // Initialized as in typemap
delete THIS;
```
If the function's name is **new** then the C++ `new` function will be called to create a dynamic C++ object. The XSUB will expect the class name, which will be kept in a variable called `CLASS`, to be given as the first argument.
```
color *
color::new()
```
The generated C++ code will call `new`.
```
RETVAL = new color();
```
The following is an example of a typemap that could be used for this C++ example.
```
TYPEMAP
color * O_OBJECT
OUTPUT
# The Perl object is blessed into 'CLASS', which should be a
# char* having the name of the package for the blessing.
O_OBJECT
sv_setref_pv( $arg, CLASS, (void*)$var );
INPUT
O_OBJECT
if( sv_isobject($arg) && (SvTYPE(SvRV($arg)) == SVt_PVMG) )
$var = ($type)SvIV((SV*)SvRV( $arg ));
else{
warn(\"${Package}::$func_name() -- \"
\"$var is not a blessed SV reference\");
XSRETURN_UNDEF;
}
```
###
Interface Strategy
When designing an interface between Perl and a C library a straight translation from C to XS (such as created by `h2xs -x`) is often sufficient. However, sometimes the interface will look very C-like and occasionally nonintuitive, especially when the C function modifies one of its parameters, or returns failure inband (as in "negative return values mean failure"). In cases where the programmer wishes to create a more Perl-like interface the following strategy may help to identify the more critical parts of the interface.
Identify the C functions with input/output or output parameters. The XSUBs for these functions may be able to return lists to Perl.
Identify the C functions which use some inband info as an indication of failure. They may be candidates to return undef or an empty list in case of failure. If the failure may be detected without a call to the C function, you may want to use an INIT: section to report the failure. For failures detectable after the C function returns one may want to use a POSTCALL: section to process the failure. In more complicated cases use CODE: or PPCODE: sections.
If many functions use the same failure indication based on the return value, you may want to create a special typedef to handle this situation. Put
```
typedef int negative_is_failure;
```
near the beginning of XS file, and create an OUTPUT typemap entry for `negative_is_failure` which converts negative values to `undef`, or maybe croak()s. After this the return value of type `negative_is_failure` will create more Perl-like interface.
Identify which values are used by only the C and XSUB functions themselves, say, when a parameter to a function should be a contents of a global variable. If Perl does not need to access the contents of the value then it may not be necessary to provide a translation for that value from C to Perl.
Identify the pointers in the C function parameter lists and return values. Some pointers may be used to implement input/output or output parameters, they can be handled in XS with the `&` unary operator, and, possibly, using the NO\_INIT keyword. Some others will require handling of types like `int *`, and one needs to decide what a useful Perl translation will do in such a case. When the semantic is clear, it is advisable to put the translation into a typemap file.
Identify the structures used by the C functions. In many cases it may be helpful to use the T\_PTROBJ typemap for these structures so they can be manipulated by Perl as blessed objects. (This is handled automatically by `h2xs -x`.)
If the same C type is used in several different contexts which require different translations, `typedef` several new types mapped to this C type, and create separate *typemap* entries for these new types. Use these types in declarations of return type and parameters to XSUBs.
###
Perl Objects And C Structures
When dealing with C structures one should select either **T\_PTROBJ** or **T\_PTRREF** for the XS type. Both types are designed to handle pointers to complex objects. The T\_PTRREF type will allow the Perl object to be unblessed while the T\_PTROBJ type requires that the object be blessed. By using T\_PTROBJ one can achieve a form of type-checking because the XSUB will attempt to verify that the Perl object is of the expected type.
The following XS code shows the getnetconfigent() function which is used with ONC+ TIRPC. The getnetconfigent() function will return a pointer to a C structure and has the C prototype shown below. The example will demonstrate how the C pointer will become a Perl reference. Perl will consider this reference to be a pointer to a blessed object and will attempt to call a destructor for the object. A destructor will be provided in the XS source to free the memory used by getnetconfigent(). Destructors in XS can be created by specifying an XSUB function whose name ends with the word **DESTROY**. XS destructors can be used to free memory which may have been malloc'd by another XSUB.
```
struct netconfig *getnetconfigent(const char *netid);
```
A `typedef` will be created for `struct netconfig`. The Perl object will be blessed in a class matching the name of the C type, with the tag `Ptr` appended, and the name should not have embedded spaces if it will be a Perl package name. The destructor will be placed in a class corresponding to the class of the object and the PREFIX keyword will be used to trim the name to the word DESTROY as Perl will expect.
```
typedef struct netconfig Netconfig;
MODULE = RPC PACKAGE = RPC
Netconfig *
getnetconfigent(netid)
char *netid
MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
void
rpcb_DESTROY(netconf)
Netconfig *netconf
CODE:
printf("Now in NetconfigPtr::DESTROY\n");
free( netconf );
```
This example requires the following typemap entry. Consult <perlxstypemap> for more information about adding new typemaps for an extension.
```
TYPEMAP
Netconfig * T_PTROBJ
```
This example will be used with the following Perl statements.
```
use RPC;
$netconf = getnetconfigent("udp");
```
When Perl destroys the object referenced by $netconf it will send the object to the supplied XSUB DESTROY function. Perl cannot determine, and does not care, that this object is a C struct and not a Perl object. In this sense, there is no difference between the object created by the getnetconfigent() XSUB and an object created by a normal Perl subroutine.
###
Safely Storing Static Data in XS
Starting with Perl 5.8, a macro framework has been defined to allow static data to be safely stored in XS modules that will be accessed from a multi-threaded Perl.
Although primarily designed for use with multi-threaded Perl, the macros have been designed so that they will work with non-threaded Perl as well.
It is therefore strongly recommended that these macros be used by all XS modules that make use of static data.
The easiest way to get a template set of macros to use is by specifying the `-g` (`--global`) option with h2xs (see <h2xs>).
Below is an example module that makes use of the macros.
```
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* Global Data */
#define MY_CXT_KEY "BlindMice::_guts" XS_VERSION
typedef struct {
int count;
char name[3][100];
} my_cxt_t;
START_MY_CXT
MODULE = BlindMice PACKAGE = BlindMice
BOOT:
{
MY_CXT_INIT;
MY_CXT.count = 0;
strcpy(MY_CXT.name[0], "None");
strcpy(MY_CXT.name[1], "None");
strcpy(MY_CXT.name[2], "None");
}
int
newMouse(char * name)
PREINIT:
dMY_CXT;
CODE:
if (MY_CXT.count >= 3) {
warn("Already have 3 blind mice");
RETVAL = 0;
}
else {
RETVAL = ++ MY_CXT.count;
strcpy(MY_CXT.name[MY_CXT.count - 1], name);
}
OUTPUT:
RETVAL
char *
get_mouse_name(index)
int index
PREINIT:
dMY_CXT;
CODE:
if (index > MY_CXT.count)
croak("There are only 3 blind mice.");
else
RETVAL = MY_CXT.name[index - 1];
OUTPUT:
RETVAL
void
CLONE(...)
CODE:
MY_CXT_CLONE;
```
####
MY\_CXT REFERENCE
MY\_CXT\_KEY This macro is used to define a unique key to refer to the static data for an XS module. The suggested naming scheme, as used by h2xs, is to use a string that consists of the module name, the string "::\_guts" and the module version number.
```
#define MY_CXT_KEY "MyModule::_guts" XS_VERSION
```
typedef my\_cxt\_t This struct typedef *must* always be called `my_cxt_t`. The other `CXT*` macros assume the existence of the `my_cxt_t` typedef name.
Declare a typedef named `my_cxt_t` that is a structure that contains all the data that needs to be interpreter-local.
```
typedef struct {
int some_value;
} my_cxt_t;
```
START\_MY\_CXT Always place the START\_MY\_CXT macro directly after the declaration of `my_cxt_t`.
MY\_CXT\_INIT The MY\_CXT\_INIT macro initializes storage for the `my_cxt_t` struct.
It *must* be called exactly once, typically in a BOOT: section. If you are maintaining multiple interpreters, it should be called once in each interpreter instance, except for interpreters cloned from existing ones. (But see ["MY\_CXT\_CLONE"](#MY_CXT_CLONE) below.)
dMY\_CXT Use the dMY\_CXT macro (a declaration) in all the functions that access MY\_CXT.
MY\_CXT Use the MY\_CXT macro to access members of the `my_cxt_t` struct. For example, if `my_cxt_t` is
```
typedef struct {
int index;
} my_cxt_t;
```
then use this to access the `index` member
```
dMY_CXT;
MY_CXT.index = 2;
```
aMY\_CXT/pMY\_CXT `dMY_CXT` may be quite expensive to calculate, and to avoid the overhead of invoking it in each function it is possible to pass the declaration onto other functions using the `aMY_CXT`/`pMY_CXT` macros, eg
```
void sub1() {
dMY_CXT;
MY_CXT.index = 1;
sub2(aMY_CXT);
}
void sub2(pMY_CXT) {
MY_CXT.index = 2;
}
```
Analogously to `pTHX`, there are equivalent forms for when the macro is the first or last in multiple arguments, where an underscore represents a comma, i.e. `_aMY_CXT`, `aMY_CXT_`, `_pMY_CXT` and `pMY_CXT_`.
MY\_CXT\_CLONE By default, when a new interpreter is created as a copy of an existing one (eg via `threads->create()`), both interpreters share the same physical my\_cxt\_t structure. Calling `MY_CXT_CLONE` (typically via the package's `CLONE()` function), causes a byte-for-byte copy of the structure to be taken, and any future dMY\_CXT will cause the copy to be accessed instead.
MY\_CXT\_INIT\_INTERP(my\_perl)
dMY\_CXT\_INTERP(my\_perl) These are versions of the macros which take an explicit interpreter as an argument.
Note that these macros will only work together within the *same* source file; that is, a dMY\_CTX in one source file will access a different structure than a dMY\_CTX in another source file.
###
Thread-aware system interfaces
Starting from Perl 5.8, in C/C++ level Perl knows how to wrap system/library interfaces that have thread-aware versions (e.g. getpwent\_r()) into frontend macros (e.g. getpwent()) that correctly handle the multithreaded interaction with the Perl interpreter. This will happen transparently, the only thing you need to do is to instantiate a Perl interpreter.
This wrapping happens always when compiling Perl core source (PERL\_CORE is defined) or the Perl core extensions (PERL\_EXT is defined). When compiling XS code outside of the Perl core, the wrapping does not take place before Perl 5.28. Starting in that release you can
```
#define PERL_REENTRANT
```
in your code to enable the wrapping. It is advisable to do so if you are using such functions, as intermixing the `_r`-forms (as Perl compiled for multithreaded operation will do) and the `_r`-less forms is neither well-defined (inconsistent results, data corruption, or even crashes become more likely), nor is it very portable. Unfortunately, not all systems have all the `_r` forms, but using this `#define` gives you whatever protection that Perl is aware is available on each system.
EXAMPLES
--------
File `RPC.xs`: Interface to some ONC+ RPC bind library functions.
```
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* Note: On glibc 2.13 and earlier, this needs be <rpc/rpc.h> */
#include <tirpc/rpc.h>
typedef struct netconfig Netconfig;
MODULE = RPC PACKAGE = RPC
SV *
rpcb_gettime(host="localhost")
char *host
PREINIT:
time_t timep;
CODE:
ST(0) = sv_newmortal();
if( rpcb_gettime( host, &timep ) )
sv_setnv( ST(0), (double)timep );
Netconfig *
getnetconfigent(netid="udp")
char *netid
MODULE = RPC PACKAGE = NetconfigPtr PREFIX = rpcb_
void
rpcb_DESTROY(netconf)
Netconfig *netconf
CODE:
printf("NetconfigPtr::DESTROY\n");
free( netconf );
```
File `typemap`: Custom typemap for RPC.xs. (cf. <perlxstypemap>)
```
TYPEMAP
Netconfig * T_PTROBJ
```
File `RPC.pm`: Perl module for the RPC extension.
```
package RPC;
require Exporter;
require DynaLoader;
@ISA = qw(Exporter DynaLoader);
@EXPORT = qw(rpcb_gettime getnetconfigent);
bootstrap RPC;
1;
```
File `rpctest.pl`: Perl test program for the RPC extension.
```
use RPC;
$netconf = getnetconfigent();
$a = rpcb_gettime();
print "time = $a\n";
print "netconf = $netconf\n";
$netconf = getnetconfigent("tcp");
$a = rpcb_gettime("poplar");
print "time = $a\n";
print "netconf = $netconf\n";
```
In Makefile.PL add -ltirpc and -I/usr/include/tirpc.
CAVEATS
-------
XS code has full access to system calls including C library functions. It thus has the capability of interfering with things that the Perl core or other modules have set up, such as signal handlers or file handles. It could mess with the memory, or any number of harmful things. Don't.
Some modules have an event loop, waiting for user-input. It is highly unlikely that two such modules would work adequately together in a single Perl application.
In general, the perl interpreter views itself as the center of the universe as far as the Perl program goes. XS code is viewed as a help-mate, to accomplish things that perl doesn't do, or doesn't do fast enough, but always subservient to perl. The closer XS code adheres to this model, the less likely conflicts will occur.
One area where there has been conflict is in regards to C locales. (See <perllocale>.) perl, with one exception and unless told otherwise, sets up the underlying locale the program is running in to the locale passed into it from the environment. This is an important difference from a generic C language program, where the underlying locale is the "C" locale unless the program changes it. As of v5.20, this underlying locale is completely hidden from pure Perl code outside the lexical scope of `use locale` except for a couple of function calls in the POSIX module which of necessity use it. But the underlying locale, with that one exception is exposed to XS code, affecting all C library routines whose behavior is locale-dependent. Your XS code better not assume that the underlying locale is "C". The exception is the [`LC_NUMERIC`](perllocale#Category-LC_NUMERIC%3A-Numeric-Formatting) locale category, and the reason it is an exception is that experience has shown that it can be problematic for XS code, whereas we have not had reports of problems with the [other locale categories](perllocale#WHAT-IS-A-LOCALE). And the reason for this one category being problematic is that the character used as a decimal point can vary. Many European languages use a comma, whereas English, and hence Perl are expecting a dot (U+002E: FULL STOP). Many modules can handle only the radix character being a dot, and so perl attempts to make it so. Up through Perl v5.20, the attempt was merely to set `LC_NUMERIC` upon startup to the `"C"` locale. Any [setlocale()](perllocale#The-setlocale-function) otherwise would change it; this caused some failures. Therefore, starting in v5.22, perl tries to keep `LC_NUMERIC` always set to `"C"` for XS code.
To summarize, here's what to expect and how to handle locales in XS code:
Non-locale-aware XS code Keep in mind that even if you think your code is not locale-aware, it may call a library function that is. Hopefully the man page for such a function will indicate that dependency, but the documentation is imperfect.
The current locale is exposed to XS code except possibly `LC_NUMERIC` (explained in the next paragraph). There have not been reports of problems with the other categories. Perl initializes things on start-up so that the current locale is the one which is indicated by the user's environment in effect at that time. See ["ENVIRONMENT" in perllocale](perllocale#ENVIRONMENT).
However, up through v5.20, Perl initialized things on start-up so that `LC_NUMERIC` was set to the "C" locale. But if any code anywhere changed it, it would stay changed. This means that your module can't count on `LC_NUMERIC` being something in particular, and you can't expect floating point numbers (including version strings) to have dots in them. If you don't allow for a non-dot, your code could break if anyone anywhere changed the locale. For this reason, v5.22 changed the behavior so that Perl tries to keep `LC_NUMERIC` in the "C" locale except around the operations internally where it should be something else. Misbehaving XS code will always be able to change the locale anyway, but the most common instance of this is checked for and handled.
Locale-aware XS code If the locale from the user's environment is desired, there should be no need for XS code to set the locale except for `LC_NUMERIC`, as perl has already set the others up. XS code should avoid changing the locale, as it can adversely affect other, unrelated, code and may not be thread-safe. To minimize problems, the macros ["STORE\_LC\_NUMERIC\_SET\_TO\_NEEDED" in perlapi](perlapi#STORE_LC_NUMERIC_SET_TO_NEEDED), ["STORE\_LC\_NUMERIC\_FORCE\_TO\_UNDERLYING" in perlapi](perlapi#STORE_LC_NUMERIC_FORCE_TO_UNDERLYING), and ["RESTORE\_LC\_NUMERIC" in perlapi](perlapi#RESTORE_LC_NUMERIC) should be used to affect any needed change.
But, starting with Perl v5.28, locales are thread-safe on platforms that support this functionality. Windows has this starting with Visual Studio 2005. Many other modern platforms support the thread-safe POSIX 2008 functions. The C `#define` `USE_THREAD_SAFE_LOCALE` will be defined iff this build is using these. From Perl-space, the read-only variable `${SAFE_LOCALES}` is 1 if either the build is not threaded, or if `USE_THREAD_SAFE_LOCALE` is defined; otherwise it is 0.
The way this works under-the-hood is that every thread has a choice of using a locale specific to it (this is the Windows and POSIX 2008 functionality), or the global locale that is accessible to all threads (this is the functionality that has always been there). The implementations for Windows and POSIX are completely different. On Windows, the runtime can be set up so that the standard [`setlocale(3)`](setlocale(3)) function either only knows about the global locale or the locale for this thread. On POSIX, `setlocale` always deals with the global locale, and other functions have been created to handle per-thread locales. Perl makes this transparent to perl-space code. It continues to use `POSIX::setlocale()`, and the interpreter translates that into the per-thread functions.
All other locale-sensitive functions automatically use the per-thread locale, if that is turned on, and failing that, the global locale. Thus calls to `setlocale` are ineffective on POSIX systems for the current thread if that thread is using a per-thread locale. If perl is compiled for single-thread operation, it does not use the per-thread functions, so `setlocale` does work as expected.
If you have loaded the [`POSIX`](posix) module you can use the methods given in <perlcall> to call [`POSIX::setlocale`](posix#setlocale) to safely change or query the locale (on systems where it is safe to do so), or you can use the new 5.28 function ["Perl\_setlocale" in perlapi](perlapi#Perl_setlocale) instead, which is a drop-in replacement for the system [`setlocale(3)`](setlocale(3)), and handles single-threaded and multi-threaded applications transparently.
There are some locale-related library calls that still aren't thread-safe because they return data in a buffer global to all threads. In the past, these didn't matter as locales weren't thread-safe at all. But now you have to be aware of them in case your module is called in a multi-threaded application. The known ones are
```
asctime()
ctime()
gcvt() [POSIX.1-2001 only (function removed in POSIX.1-2008)]
getdate()
wcrtomb() if its final argument is NULL
wcsrtombs() if its final argument is NULL
wcstombs()
wctomb()
```
Some of these shouldn't really be called in a Perl application, and for others there are thread-safe versions of these already implemented:
```
asctime_r()
ctime_r()
Perl_langinfo()
```
The `_r` forms are automatically used, starting in Perl 5.28, if you compile your code, with
```
#define PERL_REENTRANT
```
See also ["Perl\_langinfo" in perlapi](perlapi#Perl_langinfo). You can use the methods given in <perlcall>, to get the best available locale-safe versions of these
```
POSIX::localeconv()
POSIX::wcstombs()
POSIX::wctomb()
```
And note, that some items returned by `Localeconv` are available through ["Perl\_langinfo" in perlapi](perlapi#Perl_langinfo).
The others shouldn't be used in a threaded application.
Some modules may call a non-perl library that is locale-aware. This is fine as long as it doesn't try to query or change the locale using the system `setlocale`. But if these do call the system `setlocale`, those calls may be ineffective. Instead, [`Perl_setlocale`](perlapi#Perl_setlocale) works in all circumstances. Plain setlocale is ineffective on multi-threaded POSIX 2008 systems. It operates only on the global locale, whereas each thread has its own locale, paying no attention to the global one. Since converting these non-Perl libraries to `Perl_setlocale` is out of the question, there is a new function in v5.28 [`switch_to_global_locale`](perlapi#switch_to_global_locale) that will switch the thread it is called from so that any system `setlocale` calls will have their desired effect. The function [`sync_locale`](perlapi#sync_locale) must be called before returning to perl.
This thread can change the locale all it wants and it won't affect any other thread, except any that also have been switched to the global locale. This means that a multi-threaded application can have a single thread using an alien library without a problem; but no more than a single thread can be so-occupied. Bad results likely will happen.
In perls without multi-thread locale support, some alien libraries, such as `Gtk` change locales. This can cause problems for the Perl core and other modules. For these, before control is returned to perl, starting in v5.20.1, calling the function [sync\_locale()](perlapi#sync_locale) from XS should be sufficient to avoid most of these problems. Prior to this, you need a pure Perl statement that does this:
```
POSIX::setlocale(LC_ALL, POSIX::setlocale(LC_ALL));
```
or use the methods given in <perlcall>.
XS VERSION
-----------
This document covers features supported by `ExtUtils::ParseXS` (also known as `xsubpp`) 3.13\_01.
AUTHOR
------
Originally written by Dean Roehrich <*[email protected]*>.
Maintained since 1996 by The Perl Porters <*[email protected]*>.
| programming_docs |
perl Net::servent Net::servent
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
Net::servent - by-name interface to Perl's built-in getserv\*() functions
SYNOPSIS
--------
```
use Net::servent;
$s = getservbyname(shift || 'ftp') || die "no service";
printf "port for %s is %s, aliases are %s\n",
$s->name, $s->port, "@{$s->aliases}";
use Net::servent qw(:FIELDS);
getservbyname(shift || 'ftp') || die "no service";
print "port for $s_name is $s_port, aliases are @s_aliases\n";
```
DESCRIPTION
-----------
This module's default exports override the core getservent(), getservbyname(), and getnetbyport() functions, replacing them with versions that return "Net::servent" objects. They take default second arguments of "tcp". This object has methods that return the similarly named structure field name from the C's servent structure from *netdb.h*; namely name, aliases, port, and proto. The aliases method returns an array reference, the rest scalars.
You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. (Note that this still overrides your core functions.) Access these fields as variables named with a preceding `s_`. Thus, `$serv_obj->name()` corresponds to $s\_name if you import the fields. Array references are available as regular array variables, so for example `@{ $serv_obj->aliases()}` would be simply @s\_aliases.
The getserv() function is a simple front-end that forwards a numeric argument to getservbyport(), and the rest to getservbyname().
To access this functionality without the core overrides, pass the `use` an empty import list, and then access function functions with their full qualified names. On the other hand, the built-ins are still available via the `CORE::` pseudo-package.
EXAMPLES
--------
```
use Net::servent qw(:FIELDS);
while (@ARGV) {
my ($service, $proto) = ((split m!/!, shift), 'tcp');
my $valet = getserv($service, $proto);
unless ($valet) {
warn "$0: No service: $service/$proto\n"
next;
}
printf "service $service/$proto is port %d\n", $valet->port;
print "alias are @s_aliases\n" if @s_aliases;
}
```
NOTE
----
While this class is currently implemented using the Class::Struct module to build a struct-like class, you shouldn't rely upon this.
AUTHOR
------
Tom Christiansen
perl IO::Compress::RawDeflate IO::Compress::RawDeflate
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [rawdeflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#rawdeflate-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
- [Streaming](#Streaming)
- [Compressing a file from the filesystem](#Compressing-a-file-from-the-filesystem)
- [Reading from a Filehandle and writing to an in-memory buffer](#Reading-from-a-Filehandle-and-writing-to-an-in-memory-buffer)
- [Compressing multiple files](#Compressing-multiple-files)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [print](#print)
+ [printf](#printf)
+ [syswrite](#syswrite)
+ [write](#write)
+ [flush](#flush)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [newStream([OPTS])](#newStream(%5BOPTS%5D))
+ [deflateParams](#deflateParams)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
+ [Apache::GZip Revisited](#Apache::GZip-Revisited)
+ [Working with Net::FTP](#Working-with-Net::FTP)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Compress::RawDeflate - Write RFC 1951 files/buffers
SYNOPSIS
--------
```
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
my $status = rawdeflate $input => $output [,OPTS]
or die "rawdeflate failed: $RawDeflateError\n";
my $z = IO::Compress::RawDeflate->new( $output [,OPTS] )
or die "rawdeflate failed: $RawDeflateError\n";
$z->print($string);
$z->printf($format, $string);
$z->write($string);
$z->syswrite($string [, $length, $offset]);
$z->flush();
$z->tell();
$z->eof();
$z->seek($position, $whence);
$z->binmode();
$z->fileno();
$z->opened();
$z->autoflush();
$z->input_line_number();
$z->newStream( [OPTS] );
$z->deflateParams();
$z->close() ;
$RawDeflateError ;
# IO::File mode
print $z $string;
printf $z $format, $string;
tell $z
eof $z
seek $z, $position, $whence
binmode $z
fileno $z
close $z ;
```
DESCRIPTION
-----------
This module provides a Perl interface that allows writing compressed data to files or buffer as defined in RFC 1951.
Note that RFC 1951 data is not a good choice of compression format to use in isolation, especially if you want to auto-detect it.
For reading RFC 1951 files/buffers, see the companion module <IO::Uncompress::RawInflate>.
Functional Interface
---------------------
A top-level function, `rawdeflate`, is provided to carry out "one-shot" compression between buffers and/or files. For finer control over the compression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
rawdeflate $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "rawdeflate failed: $RawDeflateError\n";
```
The functional interface needs Perl5.005 or better.
###
rawdeflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`rawdeflate` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the uncompressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is compressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `rawdeflate` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the compressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the compressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the compressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the compressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the compressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `rawdeflate` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple files/buffers and `$output_filename_or_reference` is a single file/buffer the input files/buffers will be stored in `$output_filename_or_reference` as a concatenated series of compressed data streams.
###
Optional Parameters
The optional parameters for the one-shot function `rawdeflate` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `rawdeflate` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `rawdeflate` has completed.
This parameter defaults to 0.
`BinModeIn => 0|1`
This option is now a no-op. All files will be read in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all compressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any compressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any compressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any compressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all compressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any compressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all compressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any compressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any compressed data is output.
Defaults to 0.
### Examples
Here are a few example that show the capabilities of the module.
#### Streaming
This very simple command line example demonstrates the streaming capabilities of the module. The code reads data from STDIN, compresses it, and writes the compressed data to STDOUT.
```
$ echo hello world | perl -MIO::Compress::RawDeflate=rawdeflate -e 'rawdeflate \*STDIN => \*STDOUT' >output.1951
```
The special filename "-" can be used as a standin for both `\*STDIN` and `\*STDOUT`, so the above can be rewritten as
```
$ echo hello world | perl -MIO::Compress::RawDeflate=rawdeflate -e 'rawdeflate "-" => "-"' >output.1951
```
####
Compressing a file from the filesystem
To read the contents of the file `file1.txt` and write the compressed data to the file `file1.txt.1951`.
```
use strict ;
use warnings ;
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
my $input = "file1.txt";
rawdeflate $input => "$input.1951"
or die "rawdeflate failed: $RawDeflateError\n";
```
####
Reading from a Filehandle and writing to an in-memory buffer
To read from an existing Perl filehandle, `$input`, and write the compressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt" )
or die "Cannot open 'file1.txt': $!\n" ;
my $buffer ;
rawdeflate $input => \$buffer
or die "rawdeflate failed: $RawDeflateError\n";
```
####
Compressing multiple files
To compress all files in the directory "/my/home" that match "\*.txt" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
rawdeflate '</my/home/*.txt>' => '<*.1951>'
or die "rawdeflate failed: $RawDeflateError\n";
```
and if you want to compress each file one at a time, this will do the trick
```
use strict ;
use warnings ;
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ;
for my $input ( glob "/my/home/*.txt" )
{
my $output = "$input.1951" ;
rawdeflate $input => $output
or die "Error compressing '$input': $RawDeflateError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for `IO::Compress::RawDeflate` is shown below
```
my $z = IO::Compress::RawDeflate->new( $output [,OPTS] )
or die "IO::Compress::RawDeflate failed: $RawDeflateError\n";
```
It returns an `IO::Compress::RawDeflate` object on success and undef on failure. The variable `$RawDeflateError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Compress::RawDeflate can be used exactly like an <IO::File> filehandle. This means that all normal output file operations can be carried out with `$z`. For example, to write to a compressed file/buffer you can use either of these forms
```
$z->print("hello world\n");
print $z "hello world\n";
```
The mandatory parameter `$output` is used to control the destination of the compressed data. This parameter can take one of these forms.
A filename If the `$output` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the compressed data will be written to it.
A filehandle If the `$output` parameter is a filehandle, the compressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output` is a scalar reference, the compressed data will be stored in `$$output`.
If the `$output` parameter is any other type, `IO::Compress::RawDeflate`::new will return undef.
###
Constructor Options
`OPTS` is any combination of zero or more the following options:
`AutoClose => 0|1`
This option is only valid when the `$output` parameter is a filehandle. If specified, and the value is true, it will result in the `$output` being closed once either the `close` method is called or the `IO::Compress::RawDeflate` object is destroyed.
This parameter defaults to 0.
`Append => 0|1`
Opens `$output` in append mode.
The behaviour of this option is dependent on the type of `$output`.
* A Buffer
If `$output` is a buffer and `Append` is enabled, all compressed data will be append to the end of `$output`. Otherwise `$output` will be cleared before any data is written to it.
* A Filename
If `$output` is a filename and `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any compressed data is written to it.
* A Filehandle
If `$output` is a filehandle, the file pointer will be positioned to the end of the file via a call to `seek` before any compressed data is written to it. Otherwise the file pointer will not be moved.
This parameter defaults to 0.
`Merge => 0|1`
This option is used to compress input data and append it to an existing compressed data stream in `$output`. The end result is a single compressed data stream stored in `$output`.
It is a fatal error to attempt to use this option when `$output` is not an RFC 1951 data stream.
There are a number of other limitations with the `Merge` option:
1. This module needs to have been built with zlib 1.2.1 or better to work. A fatal error will be thrown if `Merge` is used with an older version of zlib.
2. If `$output` is a file or a filehandle, it must be seekable.
This parameter defaults to 0.
-Level Defines the compression level used by zlib. The value should either be a number between 0 and 9 (0 means no compression and 9 is maximum compression), or one of the symbolic constants defined below.
```
Z_NO_COMPRESSION
Z_BEST_SPEED
Z_BEST_COMPRESSION
Z_DEFAULT_COMPRESSION
```
The default is Z\_DEFAULT\_COMPRESSION.
Note, these constants are not imported by `IO::Compress::RawDeflate` by default.
```
use IO::Compress::RawDeflate qw(:strategy);
use IO::Compress::RawDeflate qw(:constants);
use IO::Compress::RawDeflate qw(:all);
```
-Strategy Defines the strategy used to tune the compression. Use one of the symbolic constants defined below.
```
Z_FILTERED
Z_HUFFMAN_ONLY
Z_RLE
Z_FIXED
Z_DEFAULT_STRATEGY
```
The default is Z\_DEFAULT\_STRATEGY.
`Strict => 0|1`
This is a placeholder option.
### Examples
TODO
Methods
-------
### print
Usage is
```
$z->print($data)
print $z $data
```
Compresses and outputs the contents of the `$data` parameter. This has the same behaviour as the `print` built-in.
Returns true if successful.
### printf
Usage is
```
$z->printf($format, $data)
printf $z $format, $data
```
Compresses and outputs the contents of the `$data` parameter.
Returns true if successful.
### syswrite
Usage is
```
$z->syswrite $data
$z->syswrite $data, $length
$z->syswrite $data, $length, $offset
```
Compresses and outputs the contents of the `$data` parameter.
Returns the number of uncompressed bytes written, or `undef` if unsuccessful.
### write
Usage is
```
$z->write $data
$z->write $data, $length
$z->write $data, $length, $offset
```
Compresses and outputs the contents of the `$data` parameter.
Returns the number of uncompressed bytes written, or `undef` if unsuccessful.
### flush
Usage is
```
$z->flush;
$z->flush($flush_type);
```
Flushes any pending compressed data to the output file/buffer.
This method takes an optional parameter, `$flush_type`, that controls how the flushing will be carried out. By default the `$flush_type` used is `Z_FINISH`. Other valid values for `$flush_type` are `Z_NO_FLUSH`, `Z_SYNC_FLUSH`, `Z_FULL_FLUSH` and `Z_BLOCK`. It is strongly recommended that you only set the `flush_type` parameter if you fully understand the implications of what it does - overuse of `flush` can seriously degrade the level of compression achieved. See the `zlib` documentation for details.
Returns true on success.
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the `close` method has been called.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the output file/buffer. It is a fatal error to attempt to seek backward.
Empty parts of the file/buffer will have NULL (0x00) bytes written to them.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
This method always returns `undef` when compressing.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Flushes any pending compressed data and then closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Compress::RawDeflate object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Compress::RawDeflate object was created, and the object is associated with a file, the underlying file will also be closed.
###
newStream([OPTS])
Usage is
```
$z->newStream( [OPTS] )
```
Closes the current compressed data stream and starts a new one.
OPTS consists of any of the options that are available when creating the `$z` object.
See the ["Constructor Options"](#Constructor-Options) section for more details.
### deflateParams
Usage is
```
$z->deflateParams
```
TODO
Importing
---------
A number of symbolic constants are required by some methods in `IO::Compress::RawDeflate`. None are imported by default.
:all Imports `rawdeflate`, `$RawDeflateError` and all symbolic constants that can be used by `IO::Compress::RawDeflate`. Same as doing this
```
use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError :constants) ;
```
:constants Import all symbolic constants. Same as doing this
```
use IO::Compress::RawDeflate qw(:flush :level :strategy) ;
```
:flush These symbolic constants are used by the `flush` method.
```
Z_NO_FLUSH
Z_PARTIAL_FLUSH
Z_SYNC_FLUSH
Z_FULL_FLUSH
Z_FINISH
Z_BLOCK
```
:level These symbolic constants are used by the `Level` option in the constructor.
```
Z_NO_COMPRESSION
Z_BEST_SPEED
Z_BEST_COMPRESSION
Z_DEFAULT_COMPRESSION
```
:strategy These symbolic constants are used by the `Strategy` option in the constructor.
```
Z_FILTERED
Z_HUFFMAN_ONLY
Z_RLE
Z_FIXED
Z_DEFAULT_STRATEGY
```
EXAMPLES
--------
###
Apache::GZip Revisited
See [IO::Compress::FAQ](IO::Compress::FAQ#Apache%3A%3AGZip-Revisited)
###
Working with Net::FTP
See [IO::Compress::FAQ](IO::Compress::FAQ#Compressed-files-and-Net%3A%3AFTP)
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
For RFC 1950, 1951 and 1952 see <https://datatracker.ietf.org/doc/html/rfc1950>, <https://datatracker.ietf.org/doc/html/rfc1951> and <https://datatracker.ietf.org/doc/html/rfc1952>
The *zlib* compression library was written by Jean-loup Gailly `[email protected]` and Mark Adler `[email protected]`.
The primary site for the *zlib* compression library is <http://www.zlib.org>.
The primary site for gzip is <http://www.gzip.org>.
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Math::BigInt::Calc Math::BigInt::Calc
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Math::BigInt::Calc - pure Perl module to support Math::BigInt
SYNOPSIS
--------
```
# to use it with Math::BigInt
use Math::BigInt lib => 'Calc';
# to use it with Math::BigFloat
use Math::BigFloat lib => 'Calc';
# to use it with Math::BigRat
use Math::BigRat lib => 'Calc';
# explicitly set base length and whether to "use integer"
use Math::BigInt::Calc base_len => 4, use_int => 1;
use Math::BigInt lib => 'Calc';
```
DESCRIPTION
-----------
Math::BigInt::Calc inherits from Math::BigInt::Lib.
In this library, the numbers are represented interenally in base B = 10\*\*N, where N is the largest possible integer that does not cause overflow in the intermediate computations. The base B elements are stored in an array, with the least significant element stored in array element zero. There are no leading zero elements, except a single zero element when the number is zero. For instance, if B = 10000, the number 1234567890 is represented internally as [7890, 3456, 12].
OPTIONS
-------
When the module is loaded, it computes the maximum exponent, i.e., power of 10, that can be used with and without "use integer" in the computations. The default is to use this maximum exponent. If the combination of the 'base\_len' value and the 'use\_int' value exceeds the maximum value, an error is thrown.
base\_len The base length can be specified explicitly with the 'base\_len' option. The value must be a positive integer.
```
use Math::BigInt::Calc base_len => 4; # use 10000 as internal base
```
use\_int This option is used to specify whether "use integer" should be used in the internal computations. The value is interpreted as a boolean value, so use 0 or "" for false and anything else for true. If the 'base\_len' is not specified together with 'use\_int', the current value for the base length is used.
```
use Math::BigInt::Calc use_int => 1; # use "use integer" internally
```
METHODS
-------
This overview constains only the methods that are specific to `Math::BigInt::Calc`. For the other methods, see <Math::BigInt::Lib>.
\_base\_len() Specify the desired base length and whether to enable "use integer" in the computations.
```
Math::BigInt::Calc -> _base_len($base_len, $use_int);
```
Note that it is better to specify the base length and whether to use integers as options when the module is loaded, for example like this
```
use Math::BigInt::Calc base_len => 6, use_int => 1;
```
SEE ALSO
---------
<Math::BigInt::Lib> for a description of the API.
Alternative libraries <Math::BigInt::FastCalc>, <Math::BigInt::GMP>, <Math::BigInt::Pari>, <Math::BigInt::GMPz>, and <Math::BigInt::BitVect>.
Some of the modules that use these libraries <Math::BigInt>, <Math::BigFloat>, and <Math::BigRat>.
perl Test::Builder::Tester::Color Test::Builder::Tester::Color
============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Test::Builder::Tester::Color - turn on colour in Test::Builder::Tester
SYNOPSIS
--------
```
When running a test script
perl -MTest::Builder::Tester::Color test.t
```
DESCRIPTION
-----------
Importing this module causes the subroutine color in Test::Builder::Tester to be called with a true value causing colour highlighting to be turned on in debug output.
The sole purpose of this module is to enable colour highlighting from the command line.
AUTHOR
------
Copyright Mark Fowler <[email protected]> 2002.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
BUGS
----
This module will have no effect unless Term::ANSIColor is installed.
SEE ALSO
---------
<Test::Builder::Tester>, <Term::ANSIColor>
perl TAP::Parser::Scheduler TAP::Parser::Scheduler
======================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Rules data structure](#Rules-data-structure)
- [Rules examples](#Rules-examples)
- [Rules resolution](#Rules-resolution)
- [Glob-style pattern matching for rules](#Glob-style-pattern-matching-for-rules)
+ [Instance Methods](#Instance-Methods)
- [get\_all](#get_all)
- [get\_job](#get_job)
- [as\_string](#as_string)
NAME
----
TAP::Parser::Scheduler - Schedule tests during parallel testing
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Scheduler;
```
DESCRIPTION
-----------
METHODS
-------
###
Class Methods
#### `new`
```
my $sched = TAP::Parser::Scheduler->new(tests => \@tests);
my $sched = TAP::Parser::Scheduler->new(
tests => [ ['t/test_name.t','Test Description'], ... ],
rules => \%rules,
);
```
Given 'tests' and optional 'rules' as input, returns a new `TAP::Parser::Scheduler` object. Each member of `@tests` should be either a a test file name, or a two element arrayref, where the first element is a test file name, and the second element is a test description. By default, we'll use the test name as the description.
The optional `rules` attribute provides direction on which tests should be run in parallel and which should be run sequentially. If no rule data structure is provided, a default data structure is used which makes every test eligible to be run in parallel:
```
{ par => '**' },
```
The rules data structure is documented more in the next section.
###
Rules data structure
The "`rules`" data structure is the the heart of the scheduler. It allows you to express simple rules like "run all tests in sequence" or "run all tests in parallel except these five tests.". However, the rules structure also supports glob-style pattern matching and recursive definitions, so you can also express arbitarily complicated patterns.
The rule must only have one top level key: either 'par' for "parallel" or 'seq' for "sequence".
Values must be either strings with possible glob-style matching, or arrayrefs of strings or hashrefs which follow this pattern recursively.
Every element in an arrayref directly below a 'par' key is eligible to be run in parallel, while vavalues directly below a 'seq' key must be run in sequence.
####
Rules examples
Here are some examples:
```
# All tests be run in parallel (the default rule)
{ par => '**' },
# Run all tests in sequence, except those starting with "p"
{ par => 't/p*.t' },
# Run all tests in parallel, except those starting with "p"
{
seq => [
{ seq => 't/p*.t' },
{ par => '**' },
],
}
# Run some startup tests in sequence, then some parallel tests then some
# teardown tests in sequence.
{
seq => [
{ seq => 't/startup/*.t' },
{ par => ['t/a/*.t','t/b/*.t','t/c/*.t'], }
{ seq => 't/shutdown/*.t' },
],
},
```
####
Rules resolution
* By default, all tests are eligible to be run in parallel. Specifying any of your own rules removes this one.
* "First match wins". The first rule that matches a test will be the one that applies.
* Any test which does not match a rule will be run in sequence at the end of the run.
* The existence of a rule does not imply selecting a test. You must still specify the tests to run.
* Specifying a rule to allow tests to run in parallel does not make the run in parallel. You still need specify the number of parallel `jobs` in your Harness object.
####
Glob-style pattern matching for rules
We implement our own glob-style pattern matching. Here are the patterns it supports:
```
** is any number of characters, including /, within a pathname
* is zero or more characters within a filename/directory name
? is exactly one character within a filename/directory name
{foo,bar,baz} is any of foo, bar or baz.
\ is an escape character
```
###
Instance Methods
#### `get_all`
Get a list of all remaining tests.
#### `get_job`
Return the next available job as <TAP::Parser::Scheduler::Job> object or `undef` if none are available. Returns a <TAP::Parser::Scheduler::Spinner> if the scheduler still has pending jobs but none are available to run right now.
#### `as_string`
Return a human readable representation of the scheduling tree. For example:
```
my @tests = (qw{
t/startup/foo.t
t/shutdown/foo.t
t/a/foo.t t/b/foo.t t/c/foo.t t/d/foo.t
});
my $sched = TAP::Parser::Scheduler->new(
tests => \@tests,
rules => {
seq => [
{ seq => 't/startup/*.t' },
{ par => ['t/a/*.t','t/b/*.t','t/c/*.t'] },
{ seq => 't/shutdown/*.t' },
],
},
);
```
Produces:
```
par:
seq:
par:
seq:
par:
seq:
't/startup/foo.t'
par:
seq:
't/a/foo.t'
seq:
't/b/foo.t'
seq:
't/c/foo.t'
par:
seq:
't/shutdown/foo.t'
't/d/foo.t'
```
perl Unicode::Normalize Unicode::Normalize
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Normalization Forms](#Normalization-Forms)
+ [Decomposition and Composition](#Decomposition-and-Composition)
+ [Quick Check](#Quick-Check)
+ [Character Data](#Character-Data)
* [EXPORT](#EXPORT)
* [CAVEATS](#CAVEATS)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Normalize - Unicode Normalization Forms
SYNOPSIS
--------
(1) using function names exported by default:
```
use Unicode::Normalize;
$NFD_string = NFD($string); # Normalization Form D
$NFC_string = NFC($string); # Normalization Form C
$NFKD_string = NFKD($string); # Normalization Form KD
$NFKC_string = NFKC($string); # Normalization Form KC
```
(2) using function names exported on request:
```
use Unicode::Normalize 'normalize';
$NFD_string = normalize('D', $string); # Normalization Form D
$NFC_string = normalize('C', $string); # Normalization Form C
$NFKD_string = normalize('KD', $string); # Normalization Form KD
$NFKC_string = normalize('KC', $string); # Normalization Form KC
```
DESCRIPTION
-----------
Parameters:
`$string` is used as a string under character semantics (see <perlunicode>).
`$code_point` should be an unsigned integer representing a Unicode code point.
Note: Between XSUB and pure Perl, there is an incompatibility about the interpretation of `$code_point` as a decimal number. XSUB converts `$code_point` to an unsigned integer, but pure Perl does not. Do not use a floating point nor a negative sign in `$code_point`.
###
Normalization Forms
`$NFD_string = NFD($string)`
It returns the Normalization Form D (formed by canonical decomposition).
`$NFC_string = NFC($string)`
It returns the Normalization Form C (formed by canonical decomposition followed by canonical composition).
`$NFKD_string = NFKD($string)`
It returns the Normalization Form KD (formed by compatibility decomposition).
`$NFKC_string = NFKC($string)`
It returns the Normalization Form KC (formed by compatibility decomposition followed by **canonical** composition).
`$FCD_string = FCD($string)`
If the given string is in FCD ("Fast C or D" form; cf. UTN #5), it returns the string without modification; otherwise it returns an FCD string.
Note: FCD is not always unique, then plural forms may be equivalent each other. `FCD()` will return one of these equivalent forms.
`$FCC_string = FCC($string)`
It returns the FCC form ("Fast C Contiguous"; cf. UTN #5).
Note: FCC is unique, as well as four normalization forms (NF\*).
`$normalized_string = normalize($form_name, $string)`
It returns the normalization form of `$form_name`.
As `$form_name`, one of the following names must be given.
```
'C' or 'NFC' for Normalization Form C (UAX #15)
'D' or 'NFD' for Normalization Form D (UAX #15)
'KC' or 'NFKC' for Normalization Form KC (UAX #15)
'KD' or 'NFKD' for Normalization Form KD (UAX #15)
'FCD' for "Fast C or D" Form (UTN #5)
'FCC' for "Fast C Contiguous" (UTN #5)
```
###
Decomposition and Composition
`$decomposed_string = decompose($string [, $useCompatMapping])`
It returns the concatenation of the decomposition of each character in the string.
If the second parameter (a boolean) is omitted or false, the decomposition is canonical decomposition; if the second parameter (a boolean) is true, the decomposition is compatibility decomposition.
The string returned is not always in NFD/NFKD. Reordering may be required.
```
$NFD_string = reorder(decompose($string)); # eq. to NFD()
$NFKD_string = reorder(decompose($string, TRUE)); # eq. to NFKD()
```
`$reordered_string = reorder($string)`
It returns the result of reordering the combining characters according to Canonical Ordering Behavior.
For example, when you have a list of NFD/NFKD strings, you can get the concatenated NFD/NFKD string from them, by saying
```
$concat_NFD = reorder(join '', @NFD_strings);
$concat_NFKD = reorder(join '', @NFKD_strings);
```
`$composed_string = compose($string)`
It returns the result of canonical composition without applying any decomposition.
For example, when you have a NFD/NFKD string, you can get its NFC/NFKC string, by saying
```
$NFC_string = compose($NFD_string);
$NFKC_string = compose($NFKD_string);
```
`($processed, $unprocessed) = splitOnLastStarter($normalized)`
It returns two strings: the first one, `$processed`, is a part before the last starter, and the second one, `$unprocessed` is another part after the first part. A starter is a character having a combining class of zero (see UAX #15).
Note that `$processed` may be empty (when `$normalized` contains no starter or starts with the last starter), and then `$unprocessed` should be equal to the entire `$normalized`.
When you have a `$normalized` string and an `$unnormalized` string following it, a simple concatenation is wrong:
```
$concat = $normalized . normalize($form, $unnormalized); # wrong!
```
Instead of it, do like this:
```
($processed, $unprocessed) = splitOnLastStarter($normalized);
$concat = $processed . normalize($form,$unprocessed.$unnormalized);
```
`splitOnLastStarter()` should be called with a pre-normalized parameter `$normalized`, that is in the same form as `$form` you want.
If you have an array of `@string` that should be concatenated and then normalized, you can do like this:
```
my $result = "";
my $unproc = "";
foreach my $str (@string) {
$unproc .= $str;
my $n = normalize($form, $unproc);
my($p, $u) = splitOnLastStarter($n);
$result .= $p;
$unproc = $u;
}
$result .= $unproc;
# instead of normalize($form, join('', @string))
```
`$processed = normalize_partial($form, $unprocessed)`
A wrapper for the combination of `normalize()` and `splitOnLastStarter()`. Note that `$unprocessed` will be modified as a side-effect.
If you have an array of `@string` that should be concatenated and then normalized, you can do like this:
```
my $result = "";
my $unproc = "";
foreach my $str (@string) {
$unproc .= $str;
$result .= normalize_partial($form, $unproc);
}
$result .= $unproc;
# instead of normalize($form, join('', @string))
```
`$processed = NFD_partial($unprocessed)`
It does like `normalize_partial('NFD', $unprocessed)`. Note that `$unprocessed` will be modified as a side-effect.
`$processed = NFC_partial($unprocessed)`
It does like `normalize_partial('NFC', $unprocessed)`. Note that `$unprocessed` will be modified as a side-effect.
`$processed = NFKD_partial($unprocessed)`
It does like `normalize_partial('NFKD', $unprocessed)`. Note that `$unprocessed` will be modified as a side-effect.
`$processed = NFKC_partial($unprocessed)`
It does like `normalize_partial('NFKC', $unprocessed)`. Note that `$unprocessed` will be modified as a side-effect.
###
Quick Check
(see Annex 8, UAX #15; and *DerivedNormalizationProps.txt*)
The following functions check whether the string is in that normalization form.
The result returned will be one of the following:
```
YES The string is in that normalization form.
NO The string is not in that normalization form.
MAYBE Dubious. Maybe yes, maybe no.
```
`$result = checkNFD($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`.
`$result = checkNFC($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`; `undef` if `MAYBE`.
`$result = checkNFKD($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`.
`$result = checkNFKC($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`; `undef` if `MAYBE`.
`$result = checkFCD($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`.
`$result = checkFCC($string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`; `undef` if `MAYBE`.
Note: If a string is not in FCD, it must not be in FCC. So `checkFCC($not_FCD_string)` should return `NO`.
`$result = check($form_name, $string)`
It returns true (`1`) if `YES`; false (`empty string`) if `NO`; `undef` if `MAYBE`.
As `$form_name`, one of the following names must be given.
```
'C' or 'NFC' for Normalization Form C (UAX #15)
'D' or 'NFD' for Normalization Form D (UAX #15)
'KC' or 'NFKC' for Normalization Form KC (UAX #15)
'KD' or 'NFKD' for Normalization Form KD (UAX #15)
'FCD' for "Fast C or D" Form (UTN #5)
'FCC' for "Fast C Contiguous" (UTN #5)
```
**Note**
In the cases of NFD, NFKD, and FCD, the answer must be either `YES` or `NO`. The answer `MAYBE` may be returned in the cases of NFC, NFKC, and FCC.
A `MAYBE` string should contain at least one combining character or the like. For example, `COMBINING ACUTE ACCENT` has the MAYBE\_NFC/MAYBE\_NFKC property.
Both `checkNFC("A\N{COMBINING ACUTE ACCENT}")` and `checkNFC("B\N{COMBINING ACUTE ACCENT}")` will return `MAYBE`. `"A\N{COMBINING ACUTE ACCENT}"` is not in NFC (its NFC is `"\N{LATIN CAPITAL LETTER A WITH ACUTE}"`), while `"B\N{COMBINING ACUTE ACCENT}"` is in NFC.
If you want to check exactly, compare the string with its NFC/NFKC/FCC.
```
if ($string eq NFC($string)) {
# $string is exactly normalized in NFC;
} else {
# $string is not normalized in NFC;
}
if ($string eq NFKC($string)) {
# $string is exactly normalized in NFKC;
} else {
# $string is not normalized in NFKC;
}
```
###
Character Data
These functions are interface of character data used internally. If you want only to get Unicode normalization forms, you don't need call them yourself.
`$canonical_decomposition = getCanon($code_point)`
If the character is canonically decomposable (including Hangul Syllables), it returns the (full) canonical decomposition as a string. Otherwise it returns `undef`.
**Note:** According to the Unicode standard, the canonical decomposition of the character that is not canonically decomposable is same as the character itself.
`$compatibility_decomposition = getCompat($code_point)`
If the character is compatibility decomposable (including Hangul Syllables), it returns the (full) compatibility decomposition as a string. Otherwise it returns `undef`.
**Note:** According to the Unicode standard, the compatibility decomposition of the character that is not compatibility decomposable is same as the character itself.
`$code_point_composite = getComposite($code_point_here, $code_point_next)`
If two characters here and next (as code points) are composable (including Hangul Jamo/Syllables and Composition Exclusions), it returns the code point of the composite.
If they are not composable, it returns `undef`.
`$combining_class = getCombinClass($code_point)`
It returns the combining class (as an integer) of the character.
`$may_be_composed_with_prev_char = isComp2nd($code_point)`
It returns a boolean whether the character of the specified codepoint may be composed with the previous one in a certain composition (including Hangul Compositions, but excluding Composition Exclusions and Non-Starter Decompositions).
`$is_exclusion = isExclusion($code_point)`
It returns a boolean whether the code point is a composition exclusion.
`$is_singleton = isSingleton($code_point)`
It returns a boolean whether the code point is a singleton
`$is_non_starter_decomposition = isNonStDecomp($code_point)`
It returns a boolean whether the code point has Non-Starter Decomposition.
`$is_Full_Composition_Exclusion = isComp_Ex($code_point)`
It returns a boolean of the derived property Comp\_Ex (Full\_Composition\_Exclusion). This property is generated from Composition Exclusions + Singletons + Non-Starter Decompositions.
`$NFD_is_NO = isNFD_NO($code_point)`
It returns a boolean of the derived property NFD\_NO (NFD\_Quick\_Check=No).
`$NFC_is_NO = isNFC_NO($code_point)`
It returns a boolean of the derived property NFC\_NO (NFC\_Quick\_Check=No).
`$NFC_is_MAYBE = isNFC_MAYBE($code_point)`
It returns a boolean of the derived property NFC\_MAYBE (NFC\_Quick\_Check=Maybe).
`$NFKD_is_NO = isNFKD_NO($code_point)`
It returns a boolean of the derived property NFKD\_NO (NFKD\_Quick\_Check=No).
`$NFKC_is_NO = isNFKC_NO($code_point)`
It returns a boolean of the derived property NFKC\_NO (NFKC\_Quick\_Check=No).
`$NFKC_is_MAYBE = isNFKC_MAYBE($code_point)`
It returns a boolean of the derived property NFKC\_MAYBE (NFKC\_Quick\_Check=Maybe).
EXPORT
------
`NFC`, `NFD`, `NFKC`, `NFKD`: by default.
`normalize` and other some functions: on request.
CAVEATS
-------
Perl's version vs. Unicode version Since this module refers to perl core's Unicode database in the directory */lib/unicore* (or formerly */lib/unicode*), the Unicode version of normalization implemented by this module depends on what has been compiled into your perl. The following table lists the default Unicode version that comes with various perl versions. (It is possible to change the Unicode version in any perl version to be any earlier Unicode version, so one could cause Unicode 3.2 to be used in any perl version starting with 5.8.0. Read *`$Config{privlib}`/unicore/README.perl* for details.
```
perl's version implemented Unicode version
5.6.1 3.0.1
5.7.2 3.1.0
5.7.3 3.1.1 (normalization is same as 3.1.0)
5.8.0 3.2.0
5.8.1-5.8.3 4.0.0
5.8.4-5.8.6 4.0.1 (normalization is same as 4.0.0)
5.8.7-5.8.8 4.1.0
5.10.0 5.0.0
5.8.9, 5.10.1 5.1.0
5.12.x 5.2.0
5.14.x 6.0.0
5.16.x 6.1.0
5.18.x 6.2.0
5.20.x 6.3.0
5.22.x 7.0.0
```
Correction of decomposition mapping In older Unicode versions, a small number of characters (all of which are CJK compatibility ideographs as far as they have been found) may have an erroneous decomposition mapping (see *NormalizationCorrections.txt*). Anyhow, this module will neither refer to *NormalizationCorrections.txt* nor provide any specific version of normalization. Therefore this module running on an older perl with an older Unicode database may use the erroneous decomposition mapping blindly conforming to the Unicode database.
Revised definition of canonical composition In Unicode 4.1.0, the definition D2 of canonical composition (which affects NFC and NFKC) has been changed (see Public Review Issue #29 and recent UAX #15). This module has used the newer definition since the version 0.07 (Oct 31, 2001). This module will not support the normalization according to the older definition, even if the Unicode version implemented by perl is lower than 4.1.0.
AUTHOR
------
SADAHIRO Tomoyuki <[email protected]>
Currently maintained by <[email protected]>
Copyright(C) 2001-2012, SADAHIRO Tomoyuki. Japan. All rights reserved.
LICENSE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<http://www.unicode.org/reports/tr15/>
Unicode Normalization Forms - UAX #15
<http://www.unicode.org/Public/UNIDATA/CompositionExclusions.txt>
Composition Exclusion Table
<http://www.unicode.org/Public/UNIDATA/DerivedNormalizationProps.txt>
Derived Normalization Properties
<http://www.unicode.org/Public/UNIDATA/NormalizationCorrections.txt>
Normalization Corrections
<http://www.unicode.org/review/pr-29.html>
Public Review Issue #29: Normalization Issue
<http://www.unicode.org/notes/tn5/>
Canonical Equivalence in Applications - UTN #5
| programming_docs |
perl TAP::Parser::ResultFactory TAP::Parser::ResultFactory
==========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [VERSION](#VERSION)
+ [DESCRIPTION](#DESCRIPTION)
+ [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
- [make\_result](#make_result)
- [class\_for](#class_for)
- [register\_type](#register_type)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::ResultFactory - Factory for creating TAP::Parser output objects
SYNOPSIS
--------
```
use TAP::Parser::ResultFactory;
my $token = {...};
my $factory = TAP::Parser::ResultFactory->new;
my $result = $factory->make_result( $token );
```
VERSION
-------
Version 3.44
### DESCRIPTION
This is a simple factory class which returns a <TAP::Parser::Result> subclass representing the current bit of test data from TAP (usually a single line). It is used primarily by <TAP::Parser::Grammar>. Unless you're subclassing, you probably won't need to use this module directly.
### METHODS
###
Class Methods
#### `new`
Creates a new factory class. *Note:* You currently don't need to instantiate a factory in order to use it.
#### `make_result`
Returns an instance the appropriate class for the test token passed in.
```
my $result = TAP::Parser::ResultFactory->make_result($token);
```
Can also be called as an instance method.
#### `class_for`
Takes one argument: `$type`. Returns the class for this $type, or `croak`s with an error.
#### `register_type`
Takes two arguments: `$type`, `$class`
This lets you override an existing type with your own custom type, or register a completely new type, eg:
```
# create a custom result type:
package MyResult;
use strict;
use base 'TAP::Parser::Result';
# register with the factory:
TAP::Parser::ResultFactory->register_type( 'my_type' => __PACKAGE__ );
# use it:
my $r = TAP::Parser::ResultFactory->( { type => 'my_type' } );
```
Your custom type should then be picked up automatically by the <TAP::Parser>.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
There are a few things to bear in mind when creating your own `ResultFactory`:
1. The factory itself is never instantiated (this *may* change in the future). This means that `_initialize` is never called.
2. `TAP::Parser::Result->new` is never called, $tokens are reblessed. This *will* change in a future version!
3. <TAP::Parser::Result> subclasses will register themselves with <TAP::Parser::ResultFactory> directly:
```
package MyFooResult;
TAP::Parser::ResultFactory->register_type( foo => __PACKAGE__ );
```
Of course, it's up to you to decide whether or not to ignore them.
### Example
```
package MyResultFactory;
use strict;
use MyResult;
use base 'TAP::Parser::ResultFactory';
# force all results to be 'MyResult'
sub class_for {
return 'MyResult';
}
1;
```
SEE ALSO
---------
<TAP::Parser>, <TAP::Parser::Result>, <TAP::Parser::Grammar>
perl App::Prove::State::Result::Test App::Prove::State::Result::Test
===============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [name](#name)
- [elapsed](#elapsed)
- [generation](#generation)
- [last\_pass\_time](#last_pass_time)
- [last\_fail\_time](#last_fail_time)
- [mtime](#mtime)
- [raw](#raw)
- [result](#result)
- [run\_time](#run_time)
- [num\_todo](#num_todo)
- [sequence](#sequence)
- [total\_passes](#total_passes)
- [total\_failures](#total_failures)
- [parser](#parser)
NAME
----
App::Prove::State::Result::Test - Individual test results.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
The `prove` command supports a `--state` option that instructs it to store persistent state across runs. This module encapsulates the results for a single test.
SYNOPSIS
--------
```
# Re-run failed tests
$ prove --state=failed,save -rbv
```
METHODS
-------
###
Class Methods
#### `new`
###
Instance Methods
#### `name`
The name of the test. Usually a filename.
#### `elapsed`
The total elapsed times the test took to run, in seconds from the epoch..
#### `generation`
The number for the "generation" of the test run. The first generation is 1 (one) and subsequent generations are 2, 3, etc.
#### `last_pass_time`
The last time the test program passed, in seconds from the epoch.
Returns `undef` if the program has never passed.
#### `last_fail_time`
The last time the test suite failed, in seconds from the epoch.
Returns `undef` if the program has never failed.
#### `mtime`
Returns the mtime of the test, in seconds from the epoch.
#### `raw`
Returns a hashref of raw test data, suitable for serialization by YAML.
#### `result`
Currently, whether or not the test suite passed with no 'problems' (such as TODO passed).
#### `run_time`
The total time it took for the test to run, in seconds. If `Time::HiRes` is available, it will have finer granularity.
#### `num_todo`
The number of tests with TODO directives.
#### `sequence`
The order in which this test was run for the given test suite result.
#### `total_passes`
The number of times the test has passed.
#### `total_failures`
The number of times the test has failed.
#### `parser`
The underlying parser object. This is useful if you need the full information for the test program.
perl Module::CoreList Module::CoreList
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS API](#FUNCTIONS-API)
* [DATA STRUCTURES](#DATA-STRUCTURES)
* [CAVEATS](#CAVEATS)
* [HISTORY](#HISTORY)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Module::CoreList - what modules shipped with versions of perl
SYNOPSIS
--------
```
use Module::CoreList;
print $Module::CoreList::version{5.00503}{CPAN}; # prints 1.48
print Module::CoreList->first_release('File::Spec');
# prints 5.00405
print Module::CoreList->first_release_by_date('File::Spec');
# prints 5.005
print Module::CoreList->first_release('File::Spec', 0.82);
# prints 5.006001
if (Module::CoreList::is_core('File::Spec')) {
print "File::Spec is a core module\n";
}
print join ', ', Module::CoreList->find_modules(qr/Data/);
# prints 'Data::Dumper'
print join ', ',
Module::CoreList->find_modules(qr/test::h.*::.*s/i, 5.008008);
# prints 'Test::Harness::Assert, Test::Harness::Straps'
print join ", ", @{ $Module::CoreList::families{5.005} };
# prints "5.005, 5.00503, 5.00504"
```
DESCRIPTION
-----------
Module::CoreList provides information on which core and dual-life modules shipped with each version of <perl>.
It provides a number of mechanisms for querying this information.
There is a utility called <corelist> provided with this module which is a convenient way of querying from the command-line.
There is a functional programming API available for programmers to query information.
Programmers may also query the contained hash structures to find relevant information.
FUNCTIONS API
--------------
These are the functions that are available, they may either be called as functions or class methods:
```
Module::CoreList::first_release('File::Spec'); # as a function
Module::CoreList->first_release('File::Spec'); # class method
```
`first_release( MODULE )`
Behaviour since version 2.11
Requires a MODULE name as an argument, returns the perl version when that module first appeared in core as ordered by perl version number or undef ( in scalar context ) or an empty list ( in list context ) if that module is not in core.
`first_release_by_date( MODULE )`
Requires a MODULE name as an argument, returns the perl version when that module first appeared in core as ordered by release date or undef ( in scalar context ) or an empty list ( in list context ) if that module is not in core.
`find_modules( REGEX, [ LIST OF PERLS ] )`
Takes a regex as an argument, returns a list of modules that match the regex given. If only a regex is provided applies to all modules in all perl versions. Optionally you may provide a list of perl versions to limit the regex search.
`find_version( PERL_VERSION )`
Takes a perl version as an argument. Upon successful completion, returns a reference to a hash. Each element of that hash has a key which is the name of a module (*e.g.,* 'File::Path') shipped with that version of perl and a value which is the version number (*e.g.,* '2.09') of that module which shipped with that version of perl . Returns `undef` otherwise.
`is_core( MODULE, [ MODULE_VERSION, [ PERL_VERSION ] ] )`
Available in version 2.99 and above.
Returns true if MODULE was bundled with the specified version of Perl. You can optionally specify a minimum version of the module, and can also specify a version of Perl. If a version of Perl isn't specified, `is_core()` will use the numeric version of Perl that is running (ie `$]`).
If you want to specify the version of Perl, but don't care about the version of the module, pass `undef` for the module version:
`is_deprecated( MODULE, PERL_VERSION )`
Available in version 2.22 and above.
Returns true if MODULE is marked as deprecated in PERL\_VERSION. If PERL\_VERSION is omitted, it defaults to the current version of Perl.
`deprecated_in( MODULE )`
Available in version 2.77 and above.
Returns the first perl version where the MODULE was marked as deprecated. Returns `undef` if the MODULE has not been marked as deprecated.
`removed_from( MODULE )`
Available in version 2.32 and above
Takes a module name as an argument, returns the first perl version where that module was removed from core. Returns undef if the given module was never in core or remains in core.
`removed_from_by_date( MODULE )`
Available in version 2.32 and above
Takes a module name as an argument, returns the first perl version by release date where that module was removed from core. Returns undef if the given module was never in core or remains in core.
`changes_between( PERL_VERSION, PERL_VERSION )`
Available in version 2.66 and above.
Given two perl versions, this returns a list of pairs describing the changes in core module content between them. The list is suitable for storing in a hash. The keys are library names and the values are hashrefs. Each hashref has an entry for one or both of `left` and `right`, giving the versions of the library in each of the left and right perl distributions.
For example, it might return these data (among others) for the difference between 5.008000 and 5.008001:
```
'Pod::ParseLink' => { left => '1.05', right => '1.06' },
'Pod::ParseUtils' => { left => '0.22', right => '0.3' },
'Pod::Perldoc' => { right => '3.10' },
'Pod::Perldoc::BaseTo' => { right => undef },
```
This shows us two libraries being updated and two being added, one of which has an undefined version in the right-hand side version.
DATA STRUCTURES
----------------
These are the hash data structures that are available:
`%Module::CoreList::version`
A hash of hashes that is keyed on perl version as indicated in $]. The second level hash is module => version pairs.
Note, it is possible for the version of a module to be unspecified, whereby the value is `undef`, so use `exists $version{$foo}{$bar}` if that's what you're testing for.
Starting with 2.10, the special module name `Unicode` refers to the version of the Unicode Character Database bundled with Perl.
`%Module::CoreList::delta`
Available in version 3.00 and above.
It is a hash of hashes that is keyed on perl version. Each keyed hash will have the following keys:
```
delta_from - a previous perl version that the changes are based on
changed - a hash of module/versions that have changed
removed - a hash of modules that have been removed
```
`%Module::CoreList::released`
Keyed on perl version this contains ISO formatted versions of the release dates, as gleaned from [perlhist](https://perldoc.perl.org/5.36.0/perlhist).
`%Module::CoreList::families`
New, in 1.96, a hash that clusters known perl releases by their major versions.
`%Module::CoreList::deprecated`
A hash of hashes keyed on perl version and on module name. If a module is defined it indicates that that module is deprecated in that perl version and is scheduled for removal from core at some future point.
`%Module::CoreList::upstream`
A hash that contains information on where patches should be directed for each core module.
UPSTREAM indicates where patches should go. `undef` implies that this hasn't been discussed for the module at hand. `blead` indicates that the copy of the module in the blead sources is to be considered canonical, `cpan` means that the module on CPAN is to be patched first. `first-come` means that blead can be patched freely if it is in sync with the latest release on CPAN.
`%Module::CoreList::bug_tracker`
A hash that contains information on the appropriate bug tracker for each core module.
BUGS is an email or url to post bug reports. For modules with UPSTREAM => 'blead', use <mailto:[email protected]>. rt.cpan.org appears to automatically provide a URL for CPAN modules; any value given here overrides the default: [http://rt.cpan.org/Public/Dist/Display.html?Name=$ModuleName](http://rt.cpan.org/Public/Dist/Display.html?Name=%24ModuleName)
CAVEATS
-------
Module::CoreList currently covers the 5.000, 5.001, 5.002, 5.003\_07, 5.004, 5.004\_05, 5.005, 5.005\_03, 5.005\_04 and 5.7.3 releases of perl.
All stable releases of perl since 5.6.0 are covered.
All development releases of perl since 5.9.0 are covered.
HISTORY
-------
Moved to Changes file.
AUTHOR
------
Richard Clamp <[email protected]>
Currently maintained by the perl 5 porters <[email protected]>.
LICENSE
-------
Copyright (C) 2002-2009 Richard Clamp. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<corelist>, <Module::Info>, <perl>, <http://perlpunks.de/corelist>
perl perlvms perlvms
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Installation](#Installation)
* [Organization of Perl Images](#Organization-of-Perl-Images)
+ [Core Images](#Core-Images)
+ [Perl Extensions](#Perl-Extensions)
+ [Installing static extensions](#Installing-static-extensions)
+ [Installing dynamic extensions](#Installing-dynamic-extensions)
* [File specifications](#File-specifications)
+ [Syntax](#Syntax)
+ [Filename Case](#Filename-Case)
+ [Symbolic Links](#Symbolic-Links)
+ [Wildcard expansion](#Wildcard-expansion)
+ [Pipes](#Pipes)
* [PERL5LIB and PERLLIB](#PERL5LIB-and-PERLLIB)
* [The Perl Forked Debugger](#The-Perl-Forked-Debugger)
* [PERL\_VMS\_EXCEPTION\_DEBUG](#PERL_VMS_EXCEPTION_DEBUG)
* [Command line](#Command-line)
+ [I/O redirection and backgrounding](#I/O-redirection-and-backgrounding)
+ [Command line switches](#Command-line-switches)
* [Perl functions](#Perl-functions)
* [Perl variables](#Perl-variables)
* [Standard modules with VMS-specific differences](#Standard-modules-with-VMS-specific-differences)
+ [SDBM\_File](#SDBM_File)
* [Revision date](#Revision-date)
* [AUTHOR](#AUTHOR)
NAME
----
perlvms - VMS-specific documentation for Perl
DESCRIPTION
-----------
Gathered below are notes describing details of Perl 5's behavior on VMS. They are a supplement to the regular Perl 5 documentation, so we have focussed on the ways in which Perl 5 functions differently under VMS than it does under Unix, and on the interactions between Perl and the rest of the operating system. We haven't tried to duplicate complete descriptions of Perl features from the main Perl documentation, which can be found in the *[.pod]* subdirectory of the Perl distribution.
We hope these notes will save you from confusion and lost sleep when writing Perl scripts on VMS. If you find we've missed something you think should appear here, please don't hesitate to drop a line to [email protected].
Installation
------------
Directions for building and installing Perl 5 can be found in the file *README.vms* in the main source directory of the Perl distribution.
Organization of Perl Images
----------------------------
###
Core Images
During the build process, three Perl images are produced. *Miniperl.Exe* is an executable image which contains all of the basic functionality of Perl, but cannot take advantage of Perl XS extensions and has a hard-wired list of library locations for loading pure-Perl modules. It is used extensively to build and test Perl and various extensions, but is not installed.
Most of the complete Perl resides in the shareable image *PerlShr.Exe*, which provides a core to which the Perl executable image and all Perl extensions are linked. It is generally located via the logical name *PERLSHR*. While it's possible to put the image in *SYS$SHARE* to make it loadable, that's not recommended. And while you may wish to INSTALL the image for performance reasons, you should not install it with privileges; if you do, the result will not be what you expect as image privileges are disabled during Perl start-up.
Finally, *Perl.Exe* is an executable image containing the main entry point for Perl, as well as some initialization code. It should be placed in a public directory, and made world executable. In order to run Perl with command line arguments, you should define a foreign command to invoke this image.
###
Perl Extensions
Perl extensions are packages which provide both XS and Perl code to add new functionality to perl. (XS is a meta-language which simplifies writing C code which interacts with Perl, see <perlxs> for more details.) The Perl code for an extension is treated like any other library module - it's made available in your script through the appropriate `use` or `require` statement, and usually defines a Perl package containing the extension.
The portion of the extension provided by the XS code may be connected to the rest of Perl in either of two ways. In the **static** configuration, the object code for the extension is linked directly into *PerlShr.Exe*, and is initialized whenever Perl is invoked. In the **dynamic** configuration, the extension's machine code is placed into a separate shareable image, which is mapped by Perl's DynaLoader when the extension is `use`d or `require`d in your script. This allows you to maintain the extension as a separate entity, at the cost of keeping track of the additional shareable image. Most extensions can be set up as either static or dynamic.
The source code for an extension usually resides in its own directory. At least three files are generally provided: *Extshortname**.xs* (where *Extshortname* is the portion of the extension's name following the last `::`), containing the XS code, *Extshortname**.pm*, the Perl library module for the extension, and *Makefile.PL*, a Perl script which uses the `MakeMaker` library modules supplied with Perl to generate a *Descrip.MMS* file for the extension.
###
Installing static extensions
Since static extensions are incorporated directly into *PerlShr.Exe*, you'll have to rebuild Perl to incorporate a new extension. You should edit the main *Descrip.MMS* or *Makefile* you use to build Perl, adding the extension's name to the `ext` macro, and the extension's object file to the `extobj` macro. You'll also need to build the extension's object file, either by adding dependencies to the main *Descrip.MMS*, or using a separate *Descrip.MMS* for the extension. Then, rebuild *PerlShr.Exe* to incorporate the new code.
Finally, you'll need to copy the extension's Perl library module to the *[.**Extname**]* subdirectory under one of the directories in `@INC`, where *Extname* is the name of the extension, with all `::` replaced by `.` (e.g. the library module for extension Foo::Bar would be copied to a *[.Foo.Bar]* subdirectory).
###
Installing dynamic extensions
In general, the distributed kit for a Perl extension includes a file named Makefile.PL, which is a Perl program which is used to create a *Descrip.MMS* file which can be used to build and install the files required by the extension. The kit should be unpacked into a directory tree **not** under the main Perl source directory, and the procedure for building the extension is simply
```
$ perl Makefile.PL ! Create Descrip.MMS
$ mmk ! Build necessary files
$ mmk test ! Run test code, if supplied
$ mmk install ! Install into public Perl tree
```
VMS support for this process in the current release of Perl is sufficient to handle most extensions. (See the MakeMaker documentation for more details on installation options for extensions.)
* the *[.Lib.Auto.**Arch**$PVers**Extname**]* subdirectory of one of the directories in `@INC` (where *PVers* is the version of Perl you're using, as supplied in `$]`, with '.' converted to '\_'), or
* one of the directories in `@INC`, or
* a directory which the extensions Perl library module passes to the DynaLoader when asking it to map the shareable image, or
* *Sys$Share* or *Sys$Library*.
If the shareable image isn't in any of these places, you'll need to define a logical name *Extshortname*, where *Extshortname* is the portion of the extension's name after the last `::`, which translates to the full file specification of the shareable image.
File specifications
--------------------
### Syntax
We have tried to make Perl aware of both VMS-style and Unix-style file specifications wherever possible. You may use either style, or both, on the command line and in scripts, but you may not combine the two styles within a single file specification. VMS Perl interprets Unix pathnames in much the same way as the CRTL (*e.g.* the first component of an absolute path is read as the device name for the VMS file specification). There are a set of functions provided in the `VMS::Filespec` package for explicit interconversion between VMS and Unix syntax; its documentation provides more details.
We've tried to minimize the dependence of Perl library modules on Unix syntax, but you may find that some of these, as well as some scripts written for Unix systems, will require that you use Unix syntax, since they will assume that '/' is the directory separator, *etc.* If you find instances of this in the Perl distribution itself, please let us know, so we can try to work around them.
Also when working on Perl programs on VMS, if you need a syntax in a specific operating system format, then you need either to check the appropriate DECC$ feature logical, or call a conversion routine to force it to that format.
The feature logical name DECC$FILENAME\_UNIX\_REPORT modifies traditional Perl behavior in the conversion of file specifications from Unix to VMS format in order to follow the extended character handling rules now expected by the CRTL. Specifically, when this feature is in effect, the `./.../` in a Unix path is now translated to `[.^.^.^.]` instead of the traditional VMS `[...]`. To be compatible with what MakeMaker expects, if a VMS path cannot be translated to a Unix path, it is passed through unchanged, so `unixify("[...]")` will return `[...]`.
There are several ambiguous cases where a conversion routine cannot determine whether an input filename is in Unix format or in VMS format, since now both VMS and Unix file specifications may have characters in them that could be mistaken for syntax delimiters of the other type. So some pathnames simply cannot be used in a mode that allows either type of pathname to be present. Perl will tend to assume that an ambiguous filename is in Unix format.
Allowing "." as a version delimiter is simply incompatible with determining whether a pathname is in VMS format or in Unix format with extended file syntax. There is no way to know whether "perl-5.8.6" is a Unix "perl-5.8.6" or a VMS "perl-5.8;6" when passing it to unixify() or vmsify().
The DECC$FILENAME\_UNIX\_REPORT logical name controls how Perl interprets filenames to the extent that Perl uses the CRTL internally for many purposes, and attempts to follow CRTL conventions for reporting filenames. The DECC$FILENAME\_UNIX\_ONLY feature differs in that it expects all filenames passed to the C run-time to be already in Unix format. This feature is not yet supported in Perl since Perl uses traditional OpenVMS file specifications internally and in the test harness, and it is not yet clear whether this mode will be useful or useable. The feature logical name DECC$POSIX\_COMPLIANT\_PATHNAMES is new with the RMS Symbolic Link SDK and included with OpenVMS v8.3, but is not yet supported in Perl.
###
Filename Case
Perl enables DECC$EFS\_CASE\_PRESERVE and DECC$ARGV\_PARSE\_STYLE by default. Note that the latter only takes effect when extended parse is set in the process in which Perl is running. When these features are explicitly disabled in the environment or the CRTL does not support them, Perl follows the traditional CRTL behavior of downcasing command-line arguments and returning file specifications in lower case only.
*N. B.* It is very easy to get tripped up using a mixture of other programs, external utilities, and Perl scripts that are in varying states of being able to handle case preservation. For example, a file created by an older version of an archive utility or a build utility such as MMK or MMS may generate a filename in all upper case even on an ODS-5 volume. If this filename is later retrieved by a Perl script or module in a case preserving environment, that upper case name may not match the mixed-case or lower-case expectations of the Perl code. Your best bet is to follow an all-or-nothing approach to case preservation: either don't use it at all, or make sure your entire toolchain and application environment support and use it.
OpenVMS Alpha v7.3-1 and later and all version of OpenVMS I64 support case sensitivity as a process setting (see `SET PROCESS /CASE_LOOKUP=SENSITIVE`). Perl does not currently support case sensitivity on VMS, but it may in the future, so Perl programs should use the `File::Spec->case_tolerant` method to determine the state, and not the `$^O` variable.
###
Symbolic Links
When built on an ODS-5 volume with symbolic links enabled, Perl by default supports symbolic links when the requisite support is available in the filesystem and CRTL (generally 64-bit OpenVMS v8.3 and later). There are a number of limitations and caveats to be aware of when working with symbolic links on VMS. Most notably, the target of a valid symbolic link must be expressed as a Unix-style path and it must exist on a volume visible from your POSIX root (see the `SHOW ROOT` command in DCL help). For further details on symbolic link capabilities and requirements, see chapter 12 of the CRTL manual that ships with OpenVMS v8.3 or later.
###
Wildcard expansion
File specifications containing wildcards are allowed both on the command line and within Perl globs (e.g. `<*.c>`). If the wildcard filespec uses VMS syntax, the resultant filespecs will follow VMS syntax; if a Unix-style filespec is passed in, Unix-style filespecs will be returned. Similar to the behavior of wildcard globbing for a Unix shell, one can escape command line wildcards with double quotation marks `"` around a perl program command line argument. However, owing to the stripping of `"` characters carried out by the C handling of argv you will need to escape a construct such as this one (in a directory containing the files *PERL.C*, *PERL.EXE*, *PERL.H*, and *PERL.OBJ*):
```
$ perl -e "print join(' ',@ARGV)" perl.*
perl.c perl.exe perl.h perl.obj
```
in the following triple quoted manner:
```
$ perl -e "print join(' ',@ARGV)" """perl.*"""
perl.*
```
In both the case of unquoted command line arguments or in calls to `glob()` VMS wildcard expansion is performed. (csh-style wildcard expansion is available if you use `File::Glob::glob`.) If the wildcard filespec contains a device or directory specification, then the resultant filespecs will also contain a device and directory; otherwise, device and directory information are removed. VMS-style resultant filespecs will contain a full device and directory, while Unix-style resultant filespecs will contain only as much of a directory path as was present in the input filespec. For example, if your default directory is Perl\_Root:[000000], the expansion of `[.t]*.*` will yield filespecs like "perl\_root:[t]base.dir", while the expansion of `t/*/*` will yield filespecs like "t/base.dir". (This is done to match the behavior of glob expansion performed by Unix shells.)
Similarly, the resultant filespec will contain the file version only if one was present in the input filespec.
### Pipes
Input and output pipes to Perl filehandles are supported; the "file name" is passed to lib$spawn() for asynchronous execution. You should be careful to close any pipes you have opened in a Perl script, lest you leave any "orphaned" subprocesses around when Perl exits.
You may also use backticks to invoke a DCL subprocess, whose output is used as the return value of the expression. The string between the backticks is handled as if it were the argument to the `system` operator (see below). In this case, Perl will wait for the subprocess to complete before continuing.
The mailbox (MBX) that perl can create to communicate with a pipe defaults to a buffer size of 8192 on 64-bit systems, 512 on VAX. The default buffer size is adjustable via the logical name PERL\_MBX\_SIZE provided that the value falls between 128 and the SYSGEN parameter MAXBUF inclusive. For example, to set the mailbox size to 32767 use `$ENV{'PERL_MBX_SIZE'} = 32767;` and then open and use pipe constructs. An alternative would be to issue the command:
```
$ Define PERL_MBX_SIZE 32767
```
before running your wide record pipe program. A larger value may improve performance at the expense of the BYTLM UAF quota.
PERL5LIB and PERLLIB
---------------------
The PERL5LIB and PERLLIB environment elements work as documented in <perl>, except that the element separator is, by default, '|' instead of ':'. However, when running under a Unix shell as determined by the logical name `GNV$UNIX_SHELL`, the separator will be ':' as on Unix systems. The directory specifications may use either VMS or Unix syntax.
The Perl Forked Debugger
-------------------------
The Perl forked debugger places the debugger commands and output in a separate X-11 terminal window so that commands and output from multiple processes are not mixed together.
Perl on VMS supports an emulation of the forked debugger when Perl is run on a VMS system that has X11 support installed.
To use the forked debugger, you need to have the default display set to an X-11 Server and some environment variables set that Unix expects.
The forked debugger requires the environment variable `TERM` to be `xterm`, and the environment variable `DISPLAY` to exist. `xterm` must be in lower case.
```
$define TERM "xterm"
$define DISPLAY "hostname:0.0"
```
Currently the value of `DISPLAY` is ignored. It is recommended that it be set to be the hostname of the display, the server and screen in Unix notation. In the future the value of DISPLAY may be honored by Perl instead of using the default display.
It may be helpful to always use the forked debugger so that script I/O is separated from debugger I/O. You can force the debugger to be forked by assigning a value to the logical name <PERLDB\_PIDS> that is not a process identification number.
```
$define PERLDB_PIDS XXXX
```
PERL\_VMS\_EXCEPTION\_DEBUG
---------------------------
The PERL\_VMS\_EXCEPTION\_DEBUG being defined as "ENABLE" will cause the VMS debugger to be invoked if a fatal exception that is not otherwise handled is raised. The purpose of this is to allow debugging of internal Perl problems that would cause such a condition.
This allows the programmer to look at the execution stack and variables to find out the cause of the exception. As the debugger is being invoked as the Perl interpreter is about to do a fatal exit, continuing the execution in debug mode is usually not practical.
Starting Perl in the VMS debugger may change the program execution profile in a way that such problems are not reproduced.
The `kill` function can be used to test this functionality from within a program.
In typical VMS style, only the first letter of the value of this logical name is actually checked in a case insensitive mode, and it is considered enabled if it is the value "T","1" or "E".
This logical name must be defined before Perl is started.
Command line
-------------
###
I/O redirection and backgrounding
Perl for VMS supports redirection of input and output on the command line, using a subset of Bourne shell syntax:
* `<file` reads stdin from `file`,
* `>file` writes stdout to `file`,
* `>>file` appends stdout to `file`,
* `2>file` writes stderr to `file`,
* `2>>file` appends stderr to `file`, and
* `2>&1` redirects stderr to stdout.
In addition, output may be piped to a subprocess, using the character '|'. Anything after this character on the command line is passed to a subprocess for execution; the subprocess takes the output of Perl as its input.
Finally, if the command line ends with '&', the entire command is run in the background as an asynchronous subprocess.
###
Command line switches
The following command line switches behave differently under VMS than described in <perlrun>. Note also that in order to pass uppercase switches to Perl, you need to enclose them in double-quotes on the command line, since the CRTL downcases all unquoted strings.
On newer 64 bit versions of OpenVMS, a process setting now controls if the quoting is needed to preserve the case of command line arguments.
-i If the `-i` switch is present but no extension for a backup copy is given, then inplace editing creates a new version of a file; the existing copy is not deleted. (Note that if an extension is given, an existing file is renamed to the backup file, as is the case under other operating systems, so it does not remain as a previous version under the original filename.)
-S If the `"-S"` or `-"S"` switch is present *and* the script name does not contain a directory, then Perl translates the logical name DCL$PATH as a searchlist, using each translation as a directory in which to look for the script. In addition, if no file type is specified, Perl looks in each directory for a file matching the name specified, with a blank type, a type of *.pl*, and a type of *.com*, in that order.
-u The `-u` switch causes the VMS debugger to be invoked after the Perl program is compiled, but before it has run. It does not create a core dump file.
Perl functions
---------------
As of the time this document was last revised, the following Perl functions were implemented in the VMS port of Perl (functions marked with \* are discussed in more detail below):
```
file tests*, abs, alarm, atan, backticks*, binmode*, bless,
caller, chdir, chmod, chown, chomp, chop, chr,
close, closedir, cos, crypt*, defined, delete, die, do, dump*,
each, endgrent, endpwent, eof, eval, exec*, exists, exit, exp,
fileno, flock getc, getgrent*, getgrgid*, getgrnam, getlogin,
getppid, getpwent*, getpwnam*, getpwuid*, glob, gmtime*, goto,
grep, hex, ioctl, import, index, int, join, keys, kill*,
last, lc, lcfirst, lchown*, length, link*, local, localtime, log,
lstat, m//, map, mkdir, my, next, no, oct, open, opendir, ord,
pack, pipe, pop, pos, print, printf, push, q//, qq//, qw//,
qx//*, quotemeta, rand, read, readdir, readlink*, redo, ref,
rename, require, reset, return, reverse, rewinddir, rindex,
rmdir, s///, scalar, seek, seekdir, select(internal),
select (system call)*, setgrent, setpwent, shift, sin, sleep,
socketpair, sort, splice, split, sprintf, sqrt, srand, stat,
study, substr, symlink*, sysread, system*, syswrite, tell,
telldir, tie, time, times*, tr///, uc, ucfirst, umask,
undef, unlink*, unpack, untie, unshift, use, utime*,
values, vec, wait, waitpid*, wantarray, warn, write, y///
```
The following functions were not implemented in the VMS port, and calling them produces a fatal error (usually) or undefined behavior (rarely, we hope):
```
chroot, dbmclose, dbmopen, fork*, getpgrp, getpriority,
msgctl, msgget, msgsend, msgrcv, semctl,
semget, semop, setpgrp, setpriority, shmctl, shmget,
shmread, shmwrite, syscall
```
The following functions are available on Perls compiled with Dec C 5.2 or greater and running VMS 7.0 or greater:
```
truncate
```
The following functions are available on Perls built on VMS 7.2 or greater:
```
fcntl (without locking)
```
The following functions may or may not be implemented, depending on what type of socket support you've built into your copy of Perl:
```
accept, bind, connect, getpeername,
gethostbyname, getnetbyname, getprotobyname,
getservbyname, gethostbyaddr, getnetbyaddr,
getprotobynumber, getservbyport, gethostent,
getnetent, getprotoent, getservent, sethostent,
setnetent, setprotoent, setservent, endhostent,
endnetent, endprotoent, endservent, getsockname,
getsockopt, listen, recv, select(system call)*,
send, setsockopt, shutdown, socket
```
The following function is available on Perls built on 64 bit OpenVMS v8.2 with hard links enabled on an ODS-5 formatted build disk. CRTL support is in principle available as of OpenVMS v7.3-1, and better configuration support could detect this.
```
link
```
The following functions are available on Perls built on 64 bit OpenVMS v8.2 and later. CRTL support is in principle available as of OpenVMS v7.3-2, and better configuration support could detect this.
```
getgrgid, getgrnam, getpwnam, getpwuid,
setgrent, ttyname
```
The following functions are available on Perls built on 64 bit OpenVMS v8.2 and later.
```
statvfs, socketpair
```
File tests The tests `-b`, `-B`, `-c`, `-C`, `-d`, `-e`, `-f`, `-o`, `-M`, `-s`, `-S`, `-t`, `-T`, and `-z` work as advertised. The return values for `-r`, `-w`, and `-x` tell you whether you can actually access the file; this may not reflect the UIC-based file protections. Since real and effective UIC don't differ under VMS, `-O`, `-R`, `-W`, and `-X` are equivalent to `-o`, `-r`, `-w`, and `-x`. Similarly, several other tests, including `-A`, `-g`, `-k`, `-l`, `-p`, and `-u`, aren't particularly meaningful under VMS, and the values returned by these tests reflect whatever your CRTL `stat()` routine does to the equivalent bits in the st\_mode field. Finally, `-d` returns true if passed a device specification without an explicit directory (e.g. `DUA1:`), as well as if passed a directory.
There are DECC feature logical names AND ODS-5 volume attributes that also control what values are returned for the date fields.
Note: Some sites have reported problems when using the file-access tests (`-r`, `-w`, and `-x`) on files accessed via DEC's DFS. Specifically, since DFS does not currently provide access to the extended file header of files on remote volumes, attempts to examine the ACL fail, and the file tests will return false, with `$!` indicating that the file does not exist. You can use `stat` on these files, since that checks UIC-based protection only, and then manually check the appropriate bits, as defined by your C compiler's *stat.h*, in the mode value it returns, if you need an approximation of the file's protections.
backticks Backticks create a subprocess, and pass the enclosed string to it for execution as a DCL command. Since the subprocess is created directly via `lib$spawn()`, any valid DCL command string may be specified.
binmode FILEHANDLE The `binmode` operator will attempt to insure that no translation of carriage control occurs on input from or output to this filehandle. Since this involves reopening the file and then restoring its file position indicator, if this function returns FALSE, the underlying filehandle may no longer point to an open file, or may point to a different position in the file than before `binmode` was called.
Note that `binmode` is generally not necessary when using normal filehandles; it is provided so that you can control I/O to existing record-structured files when necessary. You can also use the `vmsfopen` function in the VMS::Stdio extension to gain finer control of I/O to files and devices with different record structures.
crypt PLAINTEXT, USER The `crypt` operator uses the `sys$hash_password` system service to generate the hashed representation of PLAINTEXT. If USER is a valid username, the algorithm and salt values are taken from that user's UAF record. If it is not, then the preferred algorithm and a salt of 0 are used. The quadword encrypted value is returned as an 8-character string.
The value returned by `crypt` may be compared against the encrypted password from the UAF returned by the `getpw*` functions, in order to authenticate users. If you're going to do this, remember that the encrypted password in the UAF was generated using uppercase username and password strings; you'll have to upcase the arguments to `crypt` to insure that you'll get the proper value:
```
sub validate_passwd {
my($user,$passwd) = @_;
my($pwdhash);
if ( !($pwdhash = (getpwnam($user))[1]) ||
$pwdhash ne crypt("\U$passwd","\U$name") ) {
intruder_alert($name);
}
return 1;
}
```
die `die` will force the native VMS exit status to be an SS$\_ABORT code if neither of the $! or $? status values are ones that would cause the native status to be interpreted as being what VMS classifies as SEVERE\_ERROR severity for DCL error handling.
When `PERL_VMS_POSIX_EXIT` is active (see ["$?"](#%24%3F) below), the native VMS exit status value will have either one of the `$!` or `$?` or `$^E` or the Unix value 255 encoded into it in a way that the effective original value can be decoded by other programs written in C, including Perl and the GNV package. As per the normal non-VMS behavior of `die` if either `$!` or `$?` are non-zero, one of those values will be encoded into a native VMS status value. If both of the Unix status values are 0, and the `$^E` value is set one of ERROR or SEVERE\_ERROR severity, then the `$^E` value will be used as the exit code as is. If none of the above apply, the Unix value of 255 will be encoded into a native VMS exit status value.
Please note a significant difference in the behavior of `die` in the `PERL_VMS_POSIX_EXIT` mode is that it does not force a VMS SEVERE\_ERROR status on exit. The Unix exit values of 2 through 255 will be encoded in VMS status values with severity levels of SUCCESS. The Unix exit value of 1 will be encoded in a VMS status value with a severity level of ERROR. This is to be compatible with how the VMS C library encodes these values.
The minimum severity level set by `die` in `PERL_VMS_POSIX_EXIT` mode may be changed to be ERROR or higher in the future depending on the results of testing and further review.
See ["$?"](#%24%3F) for a description of the encoding of the Unix value to produce a native VMS status containing it.
dump Rather than causing Perl to abort and dump core, the `dump` operator invokes the VMS debugger. If you continue to execute the Perl program under the debugger, control will be transferred to the label specified as the argument to `dump`, or, if no label was specified, back to the beginning of the program. All other state of the program (*e.g.* values of variables, open file handles) are not affected by calling `dump`.
exec LIST A call to `exec` will cause Perl to exit, and to invoke the command given as an argument to `exec` via `lib$do_command`. If the argument begins with '@' or '$' (other than as part of a filespec), then it is executed as a DCL command. Otherwise, the first token on the command line is treated as the filespec of an image to run, and an attempt is made to invoke it (using *.Exe* and the process defaults to expand the filespec) and pass the rest of `exec`'s argument to it as parameters. If the token has no file type, and matches a file with null type, then an attempt is made to determine whether the file is an executable image which should be invoked using `MCR` or a text file which should be passed to DCL as a command procedure.
fork While in principle the `fork` operator could be implemented via (and with the same rather severe limitations as) the CRTL `vfork()` routine, and while some internal support to do just that is in place, the implementation has never been completed, making `fork` currently unavailable. A true kernel `fork()` is expected in a future version of VMS, and the pseudo-fork based on interpreter threads may be available in a future version of Perl on VMS (see <perlfork>). In the meantime, use `system`, backticks, or piped filehandles to create subprocesses.
getpwent getpwnam getpwuid These operators obtain the information described in <perlfunc>, if you have the privileges necessary to retrieve the named user's UAF information via `sys$getuai`. If not, then only the `$name`, `$uid`, and `$gid` items are returned. The `$dir` item contains the login directory in VMS syntax, while the `$comment` item contains the login directory in Unix syntax. The `$gcos` item contains the owner field from the UAF record. The `$quota` item is not used.
gmtime The `gmtime` operator will function properly if you have a working CRTL `gmtime()` routine, or if the logical name SYS$TIMEZONE\_DIFFERENTIAL is defined as the number of seconds which must be added to UTC to yield local time. (This logical name is defined automatically if you are running a version of VMS with built-in UTC support.) If neither of these cases is true, a warning message is printed, and `undef` is returned.
kill In most cases, `kill` is implemented via the undocumented system service `$SIGPRC`, which has the same calling sequence as `$FORCEX`, but throws an exception in the target process rather than forcing it to call `$EXIT`. Generally speaking, `kill` follows the behavior of the CRTL's `kill()` function, but unlike that function can be called from within a signal handler. Also, unlike the `kill` in some versions of the CRTL, Perl's `kill` checks the validity of the signal passed in and returns an error rather than attempting to send an unrecognized signal.
Also, negative signal values don't do anything special under VMS; they're just converted to the corresponding positive value.
qx// See the entry on `backticks` above.
select (system call) If Perl was not built with socket support, the system call version of `select` is not available at all. If socket support is present, then the system call version of `select` functions only for file descriptors attached to sockets. It will not provide information about regular files or pipes, since the CRTL `select()` routine does not provide this functionality.
stat EXPR Since VMS keeps track of files according to a different scheme than Unix, it's not really possible to represent the file's ID in the `st_dev` and `st_ino` fields of a `struct stat`. Perl tries its best, though, and the values it uses are pretty unlikely to be the same for two different files. We can't guarantee this, though, so caveat scriptor.
system LIST The `system` operator creates a subprocess, and passes its arguments to the subprocess for execution as a DCL command. Since the subprocess is created directly via `lib$spawn()`, any valid DCL command string may be specified. If the string begins with '@', it is treated as a DCL command unconditionally. Otherwise, if the first token contains a character used as a delimiter in file specification (e.g. `:` or `]`), an attempt is made to expand it using a default type of *.Exe* and the process defaults, and if successful, the resulting file is invoked via `MCR`. This allows you to invoke an image directly simply by passing the file specification to `system`, a common Unixish idiom. If the token has no file type, and matches a file with null type, then an attempt is made to determine whether the file is an executable image which should be invoked using `MCR` or a text file which should be passed to DCL as a command procedure.
If LIST consists of the empty string, `system` spawns an interactive DCL subprocess, in the same fashion as typing **SPAWN** at the DCL prompt.
Perl waits for the subprocess to complete before continuing execution in the current process. As described in <perlfunc>, the return value of `system` is a fake "status" which follows POSIX semantics unless the pragma `use vmsish 'status'` is in effect; see the description of `$?` in this document for more detail.
time The value returned by `time` is the offset in seconds from 01-JAN-1970 00:00:00 (just like the CRTL's times() routine), in order to make life easier for code coming in from the POSIX/Unix world.
times The array returned by the `times` operator is divided up according to the same rules the CRTL `times()` routine. Therefore, the "system time" elements will always be 0, since there is no difference between "user time" and "system" time under VMS, and the time accumulated by a subprocess may or may not appear separately in the "child time" field, depending on whether `times()` keeps track of subprocesses separately. Note especially that the VAXCRTL (at least) keeps track only of subprocesses spawned using `fork()` and `exec()`; it will not accumulate the times of subprocesses spawned via pipes, `system()`, or backticks.
unlink LIST `unlink` will delete the highest version of a file only; in order to delete all versions, you need to say
```
1 while unlink LIST;
```
You may need to make this change to scripts written for a Unix system which expect that after a call to `unlink`, no files with the names passed to `unlink` will exist. (Note: This can be changed at compile time; if you `use Config` and `$Config{'d_unlink_all_versions'}` is `define`, then `unlink` will delete all versions of a file on the first call.)
`unlink` will delete a file if at all possible, even if it requires changing file protection (though it won't try to change the protection of the parent directory). You can tell whether you've got explicit delete access to a file by using the `VMS::Filespec::candelete` operator. For instance, in order to delete only files to which you have delete access, you could say something like
```
sub safe_unlink {
my($file,$num);
foreach $file (@_) {
next unless VMS::Filespec::candelete($file);
$num += unlink $file;
}
$num;
}
```
(or you could just use `VMS::Stdio::remove`, if you've installed the VMS::Stdio extension distributed with Perl). If `unlink` has to change the file protection to delete the file, and you interrupt it in midstream, the file may be left intact, but with a changed ACL allowing you delete access.
This behavior of `unlink` is to be compatible with POSIX behavior and not traditional VMS behavior.
utime LIST This operator changes only the modification time of the file (VMS revision date) on ODS-2 volumes and ODS-5 volumes without access dates enabled. On ODS-5 volumes with access dates enabled, the true access time is modified.
waitpid PID,FLAGS If PID is a subprocess started by a piped `open()` (see <open>), `waitpid` will wait for that subprocess, and return its final status value in `$?`. If PID is a subprocess created in some other way (e.g. SPAWNed before Perl was invoked), `waitpid` will simply check once per second whether the process has completed, and return when it has. (If PID specifies a process that isn't a subprocess of the current process, and you invoked Perl with the `-w` switch, a warning will be issued.)
Returns PID on success, -1 on error. The FLAGS argument is ignored in all cases.
Perl variables
---------------
The following VMS-specific information applies to the indicated "special" Perl variables, in addition to the general information in <perlvar>. Where there is a conflict, this information takes precedence.
%ENV The operation of the `%ENV` array depends on the translation of the logical name *PERL\_ENV\_TABLES*. If defined, it should be a search list, each element of which specifies a location for `%ENV` elements. If you tell Perl to read or set the element `$ENV{`*name*`}`, then Perl uses the translations of *PERL\_ENV\_TABLES* as follows:
CRTL\_ENV This string tells Perl to consult the CRTL's internal `environ` array of key-value pairs, using *name* as the key. In most cases, this contains only a few keys, but if Perl was invoked via the C `exec[lv]e()` function, as is the case for some embedded Perl applications or when running under a shell such as GNV bash, the `environ` array may have been populated by the calling program.
CLISYM\_[LOCAL] A string beginning with `CLISYM_`tells Perl to consult the CLI's symbol tables, using *name* as the name of the symbol. When reading an element of `%ENV`, the local symbol table is scanned first, followed by the global symbol table.. The characters following `CLISYM_` are significant when an element of `%ENV` is set or deleted: if the complete string is `CLISYM_LOCAL`, the change is made in the local symbol table; otherwise the global symbol table is changed.
Any other string If an element of *PERL\_ENV\_TABLES* translates to any other string, that string is used as the name of a logical name table, which is consulted using *name* as the logical name. The normal search order of access modes is used.
*PERL\_ENV\_TABLES* is translated once when Perl starts up; any changes you make while Perl is running do not affect the behavior of `%ENV`. If *PERL\_ENV\_TABLES* is not defined, then Perl defaults to consulting first the logical name tables specified by *LNM$FILE\_DEV*, and then the CRTL `environ` array. This default order is reversed when the logical name *GNV$UNIX\_SHELL* is defined, such as when running under GNV bash.
For operations on %ENV entries based on logical names or DCL symbols, the key string is treated as if it were entirely uppercase, regardless of the case actually specified in the Perl expression. Entries in %ENV based on the CRTL's environ array preserve the case of the key string when stored, and lookups are case sensitive.
When an element of `%ENV` is read, the locations to which *PERL\_ENV\_TABLES* points are checked in order, and the value obtained from the first successful lookup is returned. If the name of the `%ENV` element contains a semi-colon, it and any characters after it are removed. These are ignored when the CRTL `environ` array or a CLI symbol table is consulted. However, the name is looked up in a logical name table, the suffix after the semi-colon is treated as the translation index to be used for the lookup. This lets you look up successive values for search list logical names. For instance, if you say
```
$ Define STORY once,upon,a,time,there,was
$ perl -e "for ($i = 0; $i <= 6; $i++) " -
_$ -e "{ print $ENV{'story;'.$i},' '}"
```
Perl will print `ONCE UPON A TIME THERE WAS`, assuming, of course, that *PERL\_ENV\_TABLES* is set up so that the logical name `story` is found, rather than a CLI symbol or CRTL `environ` element with the same name.
When an element of `%ENV` is set to a defined string, the corresponding definition is made in the location to which the first translation of *PERL\_ENV\_TABLES* points. If this causes a logical name to be created, it is defined in supervisor mode. (The same is done if an existing logical name was defined in executive or kernel mode; an existing user or supervisor mode logical name is reset to the new value.) If the value is an empty string, the logical name's translation is defined as a single `NUL` (ASCII `\0`) character, since a logical name cannot translate to a zero-length string. (This restriction does not apply to CLI symbols or CRTL `environ` values; they are set to the empty string.)
When an element of `%ENV` is set to `undef`, the element is looked up as if it were being read, and if it is found, it is deleted. (An item "deleted" from the CRTL `environ` array is set to the empty string.) Using `delete` to remove an element from `%ENV` has a similar effect, but after the element is deleted, another attempt is made to look up the element, so an inner-mode logical name or a name in another location will replace the logical name just deleted. In either case, only the first value found searching PERL\_ENV\_TABLES is altered. It is not possible at present to define a search list logical name via %ENV.
The element `$ENV{DEFAULT}` is special: when read, it returns Perl's current default device and directory, and when set, it resets them, regardless of the definition of *PERL\_ENV\_TABLES*. It cannot be cleared or deleted; attempts to do so are silently ignored.
Note that if you want to pass on any elements of the C-local environ array to a subprocess which isn't started by fork/exec, or isn't running a C program, you can "promote" them to logical names in the current process, which will then be inherited by all subprocesses, by saying
```
foreach my $key (qw[C-local keys you want promoted]) {
my $temp = $ENV{$key}; # read from C-local array
$ENV{$key} = $temp; # and define as logical name
}
```
(You can't just say `$ENV{$key} = $ENV{$key}`, since the Perl optimizer is smart enough to elide the expression.)
Don't try to clear `%ENV` by saying `%ENV = ();`, it will throw a fatal error. This is equivalent to doing the following from DCL:
```
DELETE/LOGICAL *
```
You can imagine how bad things would be if, for example, the SYS$MANAGER or SYS$SYSTEM logical names were deleted.
At present, the first time you iterate over %ENV using `keys`, or `values`, you will incur a time penalty as all logical names are read, in order to fully populate %ENV. Subsequent iterations will not reread logical names, so they won't be as slow, but they also won't reflect any changes to logical name tables caused by other programs.
You do need to be careful with the logical names representing process-permanent files, such as `SYS$INPUT` and `SYS$OUTPUT`. The translations for these logical names are prepended with a two-byte binary value (0x1B 0x00) that needs to be stripped off if you want to use it. (In previous versions of Perl it wasn't possible to get the values of these logical names, as the null byte acted as an end-of-string marker)
$! The string value of `$!` is that returned by the CRTL's strerror() function, so it will include the VMS message for VMS-specific errors. The numeric value of `$!` is the value of `errno`, except if errno is EVMSERR, in which case `$!` contains the value of vaxc$errno. Setting `$!` always sets errno to the value specified. If this value is EVMSERR, it also sets vaxc$errno to 4 (NONAME-F-NOMSG), so that the string value of `$!` won't reflect the VMS error message from before `$!` was set.
$^E This variable provides direct access to VMS status values in vaxc$errno, which are often more specific than the generic Unix-style error messages in `$!`. Its numeric value is the value of vaxc$errno, and its string value is the corresponding VMS message string, as retrieved by sys$getmsg(). Setting `$^E` sets vaxc$errno to the value specified.
While Perl attempts to keep the vaxc$errno value to be current, if errno is not EVMSERR, it may not be from the current operation.
$? The "status value" returned in `$?` is synthesized from the actual exit status of the subprocess in a way that approximates POSIX wait(5) semantics, in order to allow Perl programs to portably test for successful completion of subprocesses. The low order 8 bits of `$?` are always 0 under VMS, since the termination status of a process may or may not have been generated by an exception.
The next 8 bits contain the termination status of the program.
If the child process follows the convention of C programs compiled with the \_POSIX\_EXIT macro set, the status value will contain the actual value of 0 to 255 returned by that program on a normal exit.
With the \_POSIX\_EXIT macro set, the Unix exit value of zero is represented as a VMS native status of 1, and the Unix values from 2 to 255 are encoded by the equation:
```
VMS_status = 0x35a000 + (unix_value * 8) + 1.
```
And in the special case of Unix value 1 the encoding is:
```
VMS_status = 0x35a000 + 8 + 2 + 0x10000000.
```
For other termination statuses, the severity portion of the subprocess's exit status is used: if the severity was success or informational, these bits are all 0; if the severity was warning, they contain a value of 1; if the severity was error or fatal error, they contain the actual severity bits, which turns out to be a value of 2 for error and 4 for severe\_error. Fatal is another term for the severe\_error status.
As a result, `$?` will always be zero if the subprocess's exit status indicated successful completion, and non-zero if a warning or error occurred or a program compliant with encoding \_POSIX\_EXIT values was run and set a status.
How can you tell the difference between a non-zero status that is the result of a VMS native error status or an encoded Unix status? You can not unless you look at the ${^CHILD\_ERROR\_NATIVE} value. The ${^CHILD\_ERROR\_NATIVE} value returns the actual VMS status value and check the severity bits. If the severity bits are equal to 1, then if the numeric value for `$?` is between 2 and 255 or 0, then `$?` accurately reflects a value passed back from a Unix application. If `$?` is 1, and the severity bits indicate a VMS error (2), then `$?` is from a Unix application exit value.
In practice, Perl scripts that call programs that return \_POSIX\_EXIT type status values will be expecting those values, and programs that call traditional VMS programs will either be expecting the previous behavior or just checking for a non-zero status.
And success is always the value 0 in all behaviors.
When the actual VMS termination status of the child is an error, internally the `$!` value will be set to the closest Unix errno value to that error so that Perl scripts that test for error messages will see the expected Unix style error message instead of a VMS message.
Conversely, when setting `$?` in an END block, an attempt is made to convert the POSIX value into a native status intelligible to the operating system upon exiting Perl. What this boils down to is that setting `$?` to zero results in the generic success value SS$\_NORMAL, and setting `$?` to a non-zero value results in the generic failure status SS$\_ABORT. See also ["exit" in perlport](perlport#exit).
With the `PERL_VMS_POSIX_EXIT` logical name defined as "ENABLE", setting `$?` will cause the new value to be encoded into `$^E` so that either the original parent or child exit status values 0 to 255 can be automatically recovered by C programs expecting \_POSIX\_EXIT behavior. If both a parent and a child exit value are non-zero, then it will be assumed that this is actually a VMS native status value to be passed through. The special value of 0xFFFF is almost a NOOP as it will cause the current native VMS status in the C library to become the current native Perl VMS status, and is handled this way as it is known to not be a valid native VMS status value. It is recommend that only values in the range of normal Unix parent or child status numbers, 0 to 255 are used.
The pragma `use vmsish 'status'` makes `$?` reflect the actual VMS exit status instead of the default emulation of POSIX status described above. This pragma also disables the conversion of non-zero values to SS$\_ABORT when setting `$?` in an END block (but zero will still be converted to SS$\_NORMAL).
Do not use the pragma `use vmsish 'status'` with `PERL_VMS_POSIX_EXIT` enabled, as they are at times requesting conflicting actions and the consequence of ignoring this advice will be undefined to allow future improvements in the POSIX exit handling.
In general, with `PERL_VMS_POSIX_EXIT` enabled, more detailed information will be available in the exit status for DCL scripts or other native VMS tools, and will give the expected information for Posix programs. It has not been made the default in order to preserve backward compatibility.
N.B. Setting `DECC$FILENAME_UNIX_REPORT` implicitly enables `PERL_VMS_POSIX_EXIT`.
$| Setting `$|` for an I/O stream causes data to be flushed all the way to disk on each write (*i.e.* not just to the underlying RMS buffers for a file). In other words, it's equivalent to calling fflush() and fsync() from C.
Standard modules with VMS-specific differences
-----------------------------------------------
### SDBM\_File
SDBM\_File works properly on VMS. It has, however, one minor difference. The database directory file created has a *.sdbm\_dir* extension rather than a *.dir* extension. *.dir* files are VMS filesystem directory files, and using them for other purposes could cause unacceptable problems.
Revision date
--------------
Please see the git repository for revision history.
AUTHOR
------
Charles Bailey [email protected] Craig Berry [email protected] Dan Sugalski [email protected] John Malmberg [email protected]
| programming_docs |
perl shasum shasum
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
shasum - Print or Check SHA Checksums
SYNOPSIS
--------
```
Usage: shasum [OPTION]... [FILE]...
Print or check SHA checksums.
With no FILE, or when FILE is -, read standard input.
-a, --algorithm 1 (default), 224, 256, 384, 512, 512224, 512256
-b, --binary read in binary mode
-c, --check read SHA sums from the FILEs and check them
--tag create a BSD-style checksum
-t, --text read in text mode (default)
-U, --UNIVERSAL read in Universal Newlines mode
produces same digest on Windows/Unix/Mac
-0, --01 read in BITS mode
ASCII '0' interpreted as 0-bit,
ASCII '1' interpreted as 1-bit,
all other characters ignored
The following five options are useful only when verifying checksums:
--ignore-missing don't fail or report status for missing files
-q, --quiet don't print OK for each successfully verified file
-s, --status don't output anything, status code shows success
--strict exit non-zero for improperly formatted checksum lines
-w, --warn warn about improperly formatted checksum lines
-h, --help display this help and exit
-v, --version output version information and exit
When verifying SHA-512/224 or SHA-512/256 checksums, indicate the
algorithm explicitly using the -a option, e.g.
shasum -a 512224 -c checksumfile
The sums are computed as described in FIPS PUB 180-4. When checking,
the input should be a former output of this program. The default
mode is to print a line with checksum, a character indicating type
(`*' for binary, ` ' for text, `U' for UNIVERSAL, `^' for BITS),
and name for each FILE. The line starts with a `\' character if the
FILE name contains either newlines or backslashes, which are then
replaced by the two-character sequences `\n' and `\\' respectively.
Report shasum bugs to [email protected]
```
DESCRIPTION
-----------
Running *shasum* is often the quickest way to compute SHA message digests. The user simply feeds data to the script through files or standard input, and then collects the results from standard output.
The following command shows how to compute digests for typical inputs such as the NIST test vector "abc":
```
perl -e "print qq(abc)" | shasum
```
Or, if you want to use SHA-256 instead of the default SHA-1, simply say:
```
perl -e "print qq(abc)" | shasum -a 256
```
Since *shasum* mimics the behavior of the combined GNU *sha1sum*, *sha224sum*, *sha256sum*, *sha384sum*, and *sha512sum* programs, you can install this script as a convenient drop-in replacement.
Unlike the GNU programs, *shasum* encompasses the full SHA standard by allowing partial-byte inputs. This is accomplished through the BITS option (*-0*). The following example computes the SHA-224 digest of the 7-bit message *0001100*:
```
perl -e "print qq(0001100)" | shasum -0 -a 224
```
AUTHOR
------
Copyright (C) 2003-2018 Mark Shelor <[email protected]>.
SEE ALSO
---------
*shasum* is implemented using the Perl module <Digest::SHA>.
perl ExtUtils::MakeMaker::FAQ ExtUtils::MakeMaker::FAQ
========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Module Installation](#Module-Installation)
+ [Common errors and problems](#Common-errors-and-problems)
+ [Philosophy and History](#Philosophy-and-History)
+ [Module Writing](#Module-Writing)
+ [XS](#XS)
* [DESIGN](#DESIGN)
+ [MakeMaker object hierarchy (simplified)](#MakeMaker-object-hierarchy-(simplified))
+ [MakeMaker object hierarchy (real)](#MakeMaker-object-hierarchy-(real))
+ [The MM\_\* hierarchy](#The-MM_*-hierarchy)
* [PATCHING](#PATCHING)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MakeMaker::FAQ - Frequently Asked Questions About MakeMaker
DESCRIPTION
-----------
FAQs, tricks and tips for <ExtUtils::MakeMaker>.
###
Module Installation
How do I install a module into my home directory? If you're not the Perl administrator you probably don't have permission to install a module to its default location. Ways of handling this with a **lot** less manual effort on your part are <perlbrew> and <local::lib>.
Otherwise, you can install it for your own use into your home directory like so:
```
# Non-unix folks, replace ~ with /path/to/your/home/dir
perl Makefile.PL INSTALL_BASE=~
```
This will put modules into *~/lib/perl5*, man pages into *~/man* and programs into *~/bin*.
To ensure your Perl programs can see these newly installed modules, set your `PERL5LIB` environment variable to *~/lib/perl5* or tell each of your programs to look in that directory with the following:
```
use lib "$ENV{HOME}/lib/perl5";
```
or if $ENV{HOME} isn't set and you don't want to set it for some reason, do it the long way.
```
use lib "/path/to/your/home/dir/lib/perl5";
```
How do I get MakeMaker and Module::Build to install to the same place? Module::Build, as of 0.28, supports two ways to install to the same location as MakeMaker.
We highly recommend the install\_base method, its the simplest and most closely approximates the expected behavior of an installation prefix.
1) Use INSTALL\_BASE / `--install_base`
MakeMaker (as of 6.31) and Module::Build (as of 0.28) both can install to the same locations using the "install\_base" concept. See ["INSTALL\_BASE" in ExtUtils::MakeMaker](ExtUtils::MakeMaker#INSTALL_BASE) for details. To get MM and MB to install to the same location simply set INSTALL\_BASE in MM and `--install_base` in MB to the same location.
```
perl Makefile.PL INSTALL_BASE=/whatever
perl Build.PL --install_base /whatever
```
This works most like other language's behavior when you specify a prefix. We recommend this method.
2) Use PREFIX / `--prefix`
Module::Build 0.28 added support for `--prefix` which works like MakeMaker's PREFIX.
```
perl Makefile.PL PREFIX=/whatever
perl Build.PL --prefix /whatever
```
We highly discourage this method. It should only be used if you know what you're doing and specifically need the PREFIX behavior. The PREFIX algorithm is complicated and focused on matching the system installation.
How do I keep from installing man pages? Recent versions of MakeMaker will only install man pages on Unix-like operating systems by default. To generate manpages on non-Unix operating systems, make the "manifypods" target.
For an individual module:
```
perl Makefile.PL INSTALLMAN1DIR=none INSTALLMAN3DIR=none
```
If you want to suppress man page installation for all modules you have to reconfigure Perl and tell it 'none' when it asks where to install man pages.
How do I use a module without installing it? Two ways. One is to build the module normally...
```
perl Makefile.PL
make
make test
```
...and then use <blib> to point Perl at the built but uninstalled module:
```
perl -Mblib script.pl
perl -Mblib -e '...'
```
The other is to install the module in a temporary location.
```
perl Makefile.PL INSTALL_BASE=~/tmp
make
make test
make install
```
And then set PERL5LIB to *~/tmp/lib/perl5*. This works well when you have multiple modules to work with. It also ensures that the module goes through its full installation process which may modify it. Again, <local::lib> may assist you here.
How can I organize tests into subdirectories and have them run? Let's take the following test directory structure:
```
t/foo/sometest.t
t/bar/othertest.t
t/bar/baz/anothertest.t
```
Now, inside of the `WriteMakeFile()` function in your *Makefile.PL*, specify where your tests are located with the `test` directive:
```
test => {TESTS => 't/*.t t/*/*.t t/*/*/*.t'}
```
The first entry in the string will run all tests in the top-level *t/* directory. The second will run all test files located in any subdirectory under *t/*. The third, runs all test files within any subdirectory within any other subdirectory located under *t/*.
Note that you do not have to use wildcards. You can specify explicitly which subdirectories to run tests in:
```
test => {TESTS => 't/*.t t/foo/*.t t/bar/baz/*.t'}
```
PREFIX vs INSTALL\_BASE from Module::Build::Cookbook The behavior of PREFIX is complicated and depends closely on how your Perl is configured. The resulting installation locations will vary from machine to machine and even different installations of Perl on the same machine. Because of this, its difficult to document where prefix will place your modules.
In contrast, INSTALL\_BASE has predictable, easy to explain installation locations. Now that Module::Build and MakeMaker both have INSTALL\_BASE there is little reason to use PREFIX other than to preserve your existing installation locations. If you are starting a fresh Perl installation we encourage you to use INSTALL\_BASE. If you have an existing installation installed via PREFIX, consider moving it to an installation structure matching INSTALL\_BASE and using that instead.
Generating \*.pm files with substitutions eg of $VERSION If you want to configure your module files for local conditions, or to automatically insert a version number, you can use EUMM's `PL_FILES` capability, where it will automatically run each *\*.PL* it finds to generate its basename. For instance:
```
# Makefile.PL:
require 'common.pl';
my $version = get_version();
my @pms = qw(Foo.pm);
WriteMakefile(
NAME => 'Foo',
VERSION => $version,
PM => { map { ($_ => "\$(INST_LIB)/$_") } @pms },
clean => { FILES => join ' ', @pms },
);
# common.pl:
sub get_version { '0.04' }
sub process { my $v = get_version(); s/__VERSION__/$v/g; }
1;
# Foo.pm.PL:
require 'common.pl';
$_ = join '', <DATA>;
process();
my $file = shift;
open my $fh, '>', $file or die "$file: $!";
print $fh $_;
__DATA__
package Foo;
our $VERSION = '__VERSION__';
1;
```
You may notice that `PL_FILES` is not specified above, since the default of mapping each .PL file to its basename works well.
If the generated module were architecture-specific, you could replace `$(INST_LIB)` above with `$(INST_ARCHLIB)`, although if you locate modules under *lib*, that would involve ensuring any `lib/` in front of the module location were removed.
###
Common errors and problems
"No rule to make target `/usr/lib/perl5/CORE/config.h', needed by `Makefile'" Just what it says, you're missing that file. MakeMaker uses it to determine if perl has been rebuilt since the Makefile was made. It's a bit of a bug that it halts installation.
Some operating systems don't ship the CORE directory with their base perl install. To solve the problem, you likely need to install a perl development package such as perl-devel (CentOS, Fedora and other Redhat systems) or perl (Ubuntu and other Debian systems).
###
Philosophy and History
Why not just use <insert other build config tool here>? Why did MakeMaker reinvent the build configuration wheel? Why not just use autoconf or automake or ppm or Ant or ...
There are many reasons, but the major one is cross-platform compatibility.
Perl is one of the most ported pieces of software ever. It works on operating systems I've never even heard of (see perlport for details). It needs a build tool that can work on all those platforms and with any wacky C compilers and linkers they might have.
No such build tool exists. Even make itself has wildly different dialects. So we have to build our own.
What is Module::Build and how does it relate to MakeMaker? Module::Build is a project by Ken Williams to supplant MakeMaker. Its primary advantages are:
* pure perl. no make, no shell commands
* easier to customize
* cleaner internals
* less cruft
Module::Build was long the official heir apparent to MakeMaker. The rate of both its development and adoption has slowed in recent years, though, and it is unclear what the future holds for it. That said, Module::Build set the stage for *something* to become the heir to MakeMaker. MakeMaker's maintainers have long said that it is a dead end and should be kept functioning, while being cautious about extending with new features.
###
Module Writing
How do I keep my $VERSION up to date without resetting it manually? Often you want to manually set the $VERSION in the main module distribution because this is the version that everybody sees on CPAN and maybe you want to customize it a bit. But for all the other modules in your dist, $VERSION is really just bookkeeping and all that's important is it goes up every time the module is changed. Doing this by hand is a pain and you often forget.
Probably the easiest way to do this is using *perl-reversion* in <Perl::Version>:
```
perl-reversion -bump
```
If your version control system supports revision numbers (git doesn't easily), the simplest way to do it automatically is to use its revision number (you are using version control, right?).
In CVS, RCS and SVN you use $Revision$ (see the documentation of your version control system for details). Every time the file is checked in the $Revision$ will be updated, updating your $VERSION.
SVN uses a simple integer for $Revision$ so you can adapt it for your $VERSION like so:
```
($VERSION) = q$Revision$ =~ /(\d+)/;
```
In CVS and RCS version 1.9 is followed by 1.10. Since CPAN compares version numbers numerically we use a sprintf() to convert 1.9 to 1.009 and 1.10 to 1.010 which compare properly.
```
$VERSION = sprintf "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/g;
```
If branches are involved (ie. $Revision: 1.5.3.4$) it's a little more complicated.
```
# must be all on one line or MakeMaker will get confused.
$VERSION = do { my @r = (q$Revision$ =~ /\d+/g); sprintf "%d."."%03d" x $#r, @r };
```
In SVN, $Revision$ should be the same for every file in the project so they would all have the same $VERSION. CVS and RCS have a different $Revision$ per file so each file will have a different $VERSION. Distributed version control systems, such as SVK, may have a different $Revision$ based on who checks out the file, leading to a different $VERSION on each machine! Finally, some distributed version control systems, such as darcs, have no concept of revision number at all.
What's this *META.yml* thing and how did it get in my *MANIFEST*?! *META.yml* is a module meta-data file pioneered by Module::Build and automatically generated as part of the 'distdir' target (and thus 'dist'). See ["Module Meta-Data" in ExtUtils::MakeMaker](ExtUtils::MakeMaker#Module-Meta-Data).
To shut off its generation, pass the `NO_META` flag to `WriteMakefile()`.
How do I delete everything not in my *MANIFEST*? Some folks are surprised that `make distclean` does not delete everything not listed in their MANIFEST (thus making a clean distribution) but only tells them what they need to delete. This is done because it is considered too dangerous. While developing your module you might write a new file, not add it to the MANIFEST, then run a `distclean` and be sad because your new work was deleted.
If you really want to do this, you can use `ExtUtils::Manifest::manifind()` to read the MANIFEST and File::Find to delete the files. But you have to be careful. Here's a script to do that. Use at your own risk. Have fun blowing holes in your foot.
```
#!/usr/bin/perl -w
use strict;
use File::Spec;
use File::Find;
use ExtUtils::Manifest qw(maniread);
my %manifest = map {( $_ => 1 )}
grep { File::Spec->canonpath($_) }
keys %{ maniread() };
if( !keys %manifest ) {
print "No files found in MANIFEST. Stopping.\n";
exit;
}
find({
wanted => sub {
my $path = File::Spec->canonpath($_);
return unless -f $path;
return if exists $manifest{ $path };
print "unlink $path\n";
unlink $path;
},
no_chdir => 1
},
"."
);
```
Which tar should I use on Windows? We recommend ptar from Archive::Tar not older than 1.66 with '-C' option.
Which zip should I use on Windows for '[ndg]make zipdist'? We recommend InfoZIP: <http://www.info-zip.org/Zip.html>
### XS
How do I prevent "object version X.XX does not match bootstrap parameter Y.YY" errors? XS code is very sensitive to the module version number and will complain if the version number in your Perl module doesn't match. If you change your module's version # without rerunning Makefile.PL the old version number will remain in the Makefile, causing the XS code to be built with the wrong number.
To avoid this, you can force the Makefile to be rebuilt whenever you change the module containing the version number by adding this to your WriteMakefile() arguments.
```
depend => { '$(FIRST_MAKEFILE)' => '$(VERSION_FROM)' }
```
How do I make two or more XS files coexist in the same directory? Sometimes you need to have two and more XS files in the same package. There are three ways: `XSMULTI`, separate directories, and bootstrapping one XS from another.
XSMULTI Structure your modules so they are all located under *lib*, such that `Foo::Bar` is in *lib/Foo/Bar.pm* and *lib/Foo/Bar.xs*, etc. Have your top-level `WriteMakefile` set the variable `XSMULTI` to a true value.
Er, that's it.
Separate directories Put each XS files into separate directories, each with their own *Makefile.PL*. Make sure each of those *Makefile.PL*s has the correct `CFLAGS`, `INC`, `LIBS` etc. You will need to make sure the top-level *Makefile.PL* refers to each of these using `DIR`.
Bootstrapping Let's assume that we have a package `Cool::Foo`, which includes `Cool::Foo` and `Cool::Bar` modules each having a separate XS file. First we use the following *Makefile.PL*:
```
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'Cool::Foo',
VERSION_FROM => 'Foo.pm',
OBJECT => q/$(O_FILES)/,
# ... other attrs ...
);
```
Notice the `OBJECT` attribute. MakeMaker generates the following variables in *Makefile*:
```
# Handy lists of source code files:
XS_FILES= Bar.xs \
Foo.xs
C_FILES = Bar.c \
Foo.c
O_FILES = Bar.o \
Foo.o
```
Therefore we can use the `O_FILES` variable to tell MakeMaker to use these objects into the shared library.
That's pretty much it. Now write *Foo.pm* and *Foo.xs*, *Bar.pm* and *Bar.xs*, where *Foo.pm* bootstraps the shared library and *Bar.pm* simply loading *Foo.pm*.
The only issue left is to how to bootstrap *Bar.xs*. This is done from *Foo.xs*:
```
MODULE = Cool::Foo PACKAGE = Cool::Foo
BOOT:
# boot the second XS file
boot_Cool__Bar(aTHX_ cv);
```
If you have more than two files, this is the place where you should boot extra XS files from.
The following four files sum up all the details discussed so far.
```
Foo.pm:
-------
package Cool::Foo;
require DynaLoader;
our @ISA = qw(DynaLoader);
our $VERSION = '0.01';
bootstrap Cool::Foo $VERSION;
1;
Bar.pm:
-------
package Cool::Bar;
use Cool::Foo; # bootstraps Bar.xs
1;
Foo.xs:
-------
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
MODULE = Cool::Foo PACKAGE = Cool::Foo
BOOT:
# boot the second XS file
boot_Cool__Bar(aTHX_ cv);
MODULE = Cool::Foo PACKAGE = Cool::Foo PREFIX = cool_foo_
void
cool_foo_perl_rules()
CODE:
fprintf(stderr, "Cool::Foo says: Perl Rules\n");
Bar.xs:
-------
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
MODULE = Cool::Bar PACKAGE = Cool::Bar PREFIX = cool_bar_
void
cool_bar_perl_rules()
CODE:
fprintf(stderr, "Cool::Bar says: Perl Rules\n");
```
And of course a very basic test:
```
t/cool.t:
--------
use Test;
BEGIN { plan tests => 1 };
use Cool::Foo;
use Cool::Bar;
Cool::Foo::perl_rules();
Cool::Bar::perl_rules();
ok 1;
```
This tip has been brought to you by Nick Ing-Simmons and Stas Bekman.
An alternative way to achieve this can be seen in <Gtk2::CodeGen> and <Glib::CodeGen>.
DESIGN
------
###
MakeMaker object hierarchy (simplified)
What most people need to know (superclasses on top.)
```
ExtUtils::MM_Any
|
ExtUtils::MM_Unix
|
ExtUtils::MM_{Current OS}
|
ExtUtils::MakeMaker
|
MY
```
The object actually used is of the class [MY](ExtUtils::MY) which allows you to override bits of MakeMaker inside your Makefile.PL by declaring MY::foo() methods.
###
MakeMaker object hierarchy (real)
Here's how it really works:
```
ExtUtils::MM_Any
|
ExtUtils::MM_Unix
|
ExtUtils::Liblist::Kid ExtUtils::MM_{Current OS} (if necessary)
| |
ExtUtils::Liblist ExtUtils::MakeMaker |
| | |
| | |-----------------------
ExtUtils::MM
| |
ExtUtils::MY MM (created by ExtUtils::MM)
| |
MY (created by ExtUtils::MY) |
. |
(mixin) |
. |
PACK### (created each call to ExtUtils::MakeMaker->new)
```
NOTE: Yes, this is a mess. See <http://archive.develooper.com/[email protected]/msg00134.html> for some history.
NOTE: When <ExtUtils::MM> is loaded it chooses a superclass for MM from amongst the ExtUtils::MM\_\* modules based on the current operating system.
NOTE: ExtUtils::MM\_{Current OS} represents one of the ExtUtils::MM\_\* modules except <ExtUtils::MM_Any> chosen based on your operating system.
NOTE: The main object used by MakeMaker is a PACK### object, \*not\* <ExtUtils::MakeMaker>. It is, effectively, a subclass of [MY](ExtUtils::MY), <ExtUtils::MakeMaker>, <ExtUtils::Liblist> and ExtUtils::MM\_{Current OS}
NOTE: The methods in [MY](ExtUtils::MY) are simply copied into PACK### rather than MY being a superclass of PACK###. I don't remember the rationale.
NOTE: <ExtUtils::Liblist> should be removed from the inheritance hiearchy and simply be called as functions.
NOTE: Modules like <File::Spec> and [Exporter](exporter) have been omitted for clarity.
###
The MM\_\* hierarchy
```
MM_Win95 MM_NW5
\ /
MM_BeOS MM_Cygwin MM_OS2 MM_VMS MM_Win32 MM_DOS MM_UWIN
\ | | | / / /
------------------------------------------------
| |
MM_Unix |
| |
MM_Any
```
NOTE: Each direct [MM\_Unix](ExtUtils::MM_Unix) subclass is also an [MM\_Any](ExtUtils::MM_Any) subclass. This is a temporary hack because MM\_Unix overrides some MM\_Any methods with Unix specific code. It allows the non-Unix modules to see the original MM\_Any implementations.
NOTE: Modules like <File::Spec> and [Exporter](exporter) have been omitted for clarity.
PATCHING
--------
If you have a question you'd like to see added to the FAQ (whether or not you have the answer) please either:
* make a pull request on the MakeMaker github repository
* raise a issue on the MakeMaker github repository
* file an RT ticket
* email [email protected]
AUTHOR
------
The denizens of [email protected].
SEE ALSO
---------
<ExtUtils::MakeMaker>
| programming_docs |
perl None
Perl 5.36.0 Documentation
--------------------------
The *perldoc* program gives you access to all the documentation that comes with Perl. You can get more documentation, tutorials and community support online at <https://www.perl.org/>.
If you're new to Perl, you should start by running [`perldoc perlintro`](perlintro), which is a general intro for beginners and provides some background to help you navigate the rest of Perl's extensive documentation. Run [`perldoc perldoc`](perldoc) to learn more things you can do with *perldoc*.
For ease of access, the Perl manual has been split up into several sections.
* [Overview](perl#Overview)
* [Tutorials](perl#Tutorials)
* [Reference Manual](perl#Reference-Manual)
* [Internals and C Language Interface](perl#Internals-and-C-Language-Interface)
* [History](perl#History)
* [Miscellaneous](perl#Miscellaneous)
* [Language-Specific](perl#Language-Specific)
* [Platform-Specific](perl#Platform-Specific)
* [Stubs for Deleted Documents](perl#Stubs-for-Deleted-Documents)
*Full perl(1) documentation: <perl>*
###
Reference Lists
* [Operators](perlop)
* [Functions](https://perldoc.perl.org/5.36.0/functions)
* [Variables](https://perldoc.perl.org/5.36.0/variables)
* [Modules](modules)
* [Utilities](perlutil)
###
About Perl
Perl officially stands for Practical Extraction and Report Language, except when it doesn't.
Perl was originally a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It quickly became a good language for many system management tasks. Over the years, Perl has grown into a general-purpose programming language. It's widely used for everything from quick "one-liners" to full-scale application development.
The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). It combines (in the author's opinion, anyway) some of the best features of **sed**, **awk**, and **sh**, making it familiar and easy to use for Unix users to whip up quick solutions to annoying problems. Its general-purpose programming facilities support procedural, functional, and object-oriented programming paradigms, making Perl a comfortable language for the long haul on major projects, whatever your bent.
Perl's roots in text processing haven't been forgotten over the years. It still boasts some of the most powerful regular expressions to be found anywhere, and its support for Unicode text is world-class. It handles all kinds of structured text, too, through an extensive collection of extensions. Those libraries, collected in the CPAN, provide ready-made solutions to an astounding array of problems. When they haven't set the standard themselves, they steal from the best -- just like Perl itself.
perl CPAN::Queue CPAN::Queue
===========
CONTENTS
--------
* [NAME](#NAME)
* [LICENSE](#LICENSE)
NAME
----
CPAN::Queue - internal queue support for CPAN.pm
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Net::Cmd Net::Cmd
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Public Methods](#Public-Methods)
+ [Protected Methods](#Protected-Methods)
+ [Pseudo Responses](#Pseudo-Responses)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::Cmd - Network Command class (as used by FTP, SMTP etc)
SYNOPSIS
--------
```
use Net::Cmd;
@ISA = qw(Net::Cmd);
```
DESCRIPTION
-----------
`Net::Cmd` is a collection of methods that can be inherited by a sub-class of `IO::Socket::INET`. These methods implement the functionality required for a command based protocol, for example FTP and SMTP.
If your sub-class does not also derive from `IO::Socket::INET` or similar (e.g. `IO::Socket::IP`, `IO::Socket::INET6` or `IO::Socket::SSL`) then you must provide the following methods by other means yourself: `close()` and `timeout()`.
###
Public Methods
These methods provide a user interface to the `Net::Cmd` object.
`debug($level)`
Set the level of debug information for this object. If `$level` is not given then the current state is returned. Otherwise the state is changed to `$level` and the previous state returned.
Different packages may implement different levels of debug but a non-zero value results in copies of all commands and responses also being sent to STDERR.
If `$level` is `undef` then the debug level will be set to the default debug level for the class.
This method can also be called as a *static* method to set/get the default debug level for a given class.
`message()`
Returns the text message returned from the last command. In a scalar context it returns a single string, in a list context it will return each line as a separate element. (See ["PSEUDO RESPONSES"](#PSEUDO-RESPONSES) below.)
`code()`
Returns the 3-digit code from the last command. If a command is pending then the value 0 is returned. (See ["PSEUDO RESPONSES"](#PSEUDO-RESPONSES) below.)
`ok()`
Returns non-zero if the last code value was greater than zero and less than 400. This holds true for most command servers. Servers where this does not hold may override this method.
`status()`
Returns the most significant digit of the current status code. If a command is pending then `CMD_PENDING` is returned.
`datasend($data)`
Send data to the remote server, converting LF to CRLF. Any line starting with a '.' will be prefixed with another '.'. `$data` may be an array or a reference to an array. The `$data` passed in must be encoded by the caller to octets of whatever encoding is required, e.g. by using the Encode module's `encode()` function.
`dataend()`
End the sending of data to the remote server. This is done by ensuring that the data already sent ends with CRLF then sending '.CRLF' to end the transmission. Once this data has been sent `dataend` calls `response` and returns true if `response` returns CMD\_OK.
###
Protected Methods
These methods are not intended to be called by the user, but used or over-ridden by a sub-class of `Net::Cmd`
`debug_print($dir, $text)`
Print debugging information. `$dir` denotes the direction *true* being data being sent to the server. Calls `debug_text` before printing to STDERR.
`debug_text($dir, $text)`
This method is called to print debugging information. `$text` is the text being sent. The method should return the text to be printed.
This is primarily meant for the use of modules such as FTP where passwords are sent, but we do not want to display them in the debugging information.
`command($cmd[, $args, ... ])`
Send a command to the command server. All arguments are first joined with a space character and CRLF is appended, this string is then sent to the command server.
Returns undef upon failure.
`unsupported()`
Sets the status code to 580 and the response text to 'Unsupported command'. Returns zero.
`response()`
Obtain a response from the server. Upon success the most significant digit of the status code is returned. Upon failure, timeout etc., *CMD\_ERROR* is returned.
`parse_response($text)`
This method is called by `response` as a method with one argument. It should return an array of 2 values, the 3-digit status code and a flag which is true when this is part of a multi-line response and this line is not the last.
`getline()`
Retrieve one line, delimited by CRLF, from the remote server. Returns *undef* upon failure.
**NOTE**: If you do use this method for any reason, please remember to add some `debug_print` calls into your method.
`ungetline($text)`
Unget a line of text from the server.
`rawdatasend($data)`
Send data to the remote server without performing any conversions. `$data` is a scalar. As with `datasend()`, the `$data` passed in must be encoded by the caller to octets of whatever encoding is required, e.g. by using the Encode module's `encode()` function.
`read_until_dot()`
Read data from the remote server until a line consisting of a single '.'. Any lines starting with '..' will have one of the '.'s removed.
Returns a reference to a list containing the lines, or *undef* upon failure.
`tied_fh()`
Returns a filehandle tied to the Net::Cmd object. After issuing a command, you may read from this filehandle using read() or <>. The filehandle will return EOF when the final dot is encountered. Similarly, you may write to the filehandle in order to send data to the server after issuing a command that expects data to be written.
See the Net::POP3 and Net::SMTP modules for examples of this.
###
Pseudo Responses
Normally the values returned by `message()` and `code()` are obtained from the remote server, but in a few circumstances, as detailed below, `Net::Cmd` will return values that it sets. You can alter this behavior by overriding DEF\_REPLY\_CODE() to specify a different default reply code, or overriding one of the specific error handling methods below.
Initial value Before any command has executed or if an unexpected error occurs `code()` will return "421" (temporary connection failure) and `message()` will return undef.
Connection closed If the underlying `IO::Handle` is closed, or if there are any read or write failures, the file handle will be forced closed, and `code()` will return "421" (temporary connection failure) and `message()` will return "[$pkg] Connection closed" (where $pkg is the name of the class that subclassed `Net::Cmd`). The \_set\_status\_closed() method can be overridden to set a different message (by calling set\_status()) or otherwise trap this error.
Timeout If there is a read or write timeout `code()` will return "421" (temporary connection failure) and `message()` will return "[$pkg] Timeout" (where $pkg is the name of the class that subclassed `Net::Cmd`). The \_set\_status\_timeout() method can be overridden to set a different message (by calling set\_status()) or otherwise trap this error.
EXPORTS
-------
The following symbols are, or can be, exported by this module:
Default Exports `CMD_INFO`, `CMD_OK`, `CMD_MORE`, `CMD_REJECT`, `CMD_ERROR`, `CMD_PENDING`.
(These correspond to possible results of `response()` and `status()`.)
Optional Exports *None*.
Export Tags *None*.
KNOWN BUGS
-----------
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 1995-2006 Graham Barr. All rights reserved.
Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
perl perlopenbsd perlopenbsd
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [OpenBSD core dumps from getprotobyname\_r and getservbyname\_r with ithreads](#OpenBSD-core-dumps-from-getprotobyname_r-and-getservbyname_r-with-ithreads)
* [AUTHOR](#AUTHOR)
NAME
----
perlopenbsd - Perl version 5 on OpenBSD systems
DESCRIPTION
-----------
This document describes various features of OpenBSD that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
OpenBSD core dumps from getprotobyname\_r and getservbyname\_r with ithreads
When Perl is configured to use ithreads, it will use re-entrant library calls in preference to non-re-entrant versions. There is an incompatibility in OpenBSD's `getprotobyname_r` and `getservbyname_r` function in versions 3.7 and later that will cause a SEGV when called without doing a `bzero` on their return structs prior to calling these functions. Current Perl's should handle this problem correctly. Older threaded Perls (5.8.6 or earlier) will run into this problem. If you want to run a threaded Perl on OpenBSD 3.7 or higher, you will need to upgrade to at least Perl 5.8.7.
AUTHOR
------
Steve Peters <[email protected]>
Please report any errors, updates, or suggestions to <https://github.com/Perl/perl5/issues>.
perl perlcygwin perlcygwin
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [PREREQUISITES FOR COMPILING PERL ON CYGWIN](#PREREQUISITES-FOR-COMPILING-PERL-ON-CYGWIN)
+ [Cygwin = GNU+Cygnus+Windows (Don't leave UNIX without it)](#Cygwin-=-GNU+Cygnus+Windows-(Don't-leave-UNIX-without-it))
+ [Cygwin Configuration](#Cygwin-Configuration)
* [CONFIGURE PERL ON CYGWIN](#CONFIGURE-PERL-ON-CYGWIN)
+ [Stripping Perl Binaries on Cygwin](#Stripping-Perl-Binaries-on-Cygwin)
+ [Optional Libraries for Perl on Cygwin](#Optional-Libraries-for-Perl-on-Cygwin)
+ [Configure-time Options for Perl on Cygwin](#Configure-time-Options-for-Perl-on-Cygwin)
+ [Suspicious Warnings on Cygwin](#Suspicious-Warnings-on-Cygwin)
* [MAKE ON CYGWIN](#MAKE-ON-CYGWIN)
* [TEST ON CYGWIN](#TEST-ON-CYGWIN)
+ [File Permissions on Cygwin](#File-Permissions-on-Cygwin)
+ [NDBM\_File and ODBM\_File do not work on FAT filesystems](#NDBM_File-and-ODBM_File-do-not-work-on-FAT-filesystems)
+ [fork() failures in io\_\* tests](#fork()-failures-in-io_*-tests)
* [Specific features of the Cygwin port](#Specific-features-of-the-Cygwin-port)
+ [Script Portability on Cygwin](#Script-Portability-on-Cygwin)
+ [Prebuilt methods:](#Prebuilt-methods:)
* [INSTALL PERL ON CYGWIN](#INSTALL-PERL-ON-CYGWIN)
* [MANIFEST ON CYGWIN](#MANIFEST-ON-CYGWIN)
* [BUGS ON CYGWIN](#BUGS-ON-CYGWIN)
* [AUTHORS](#AUTHORS)
* [HISTORY](#HISTORY)
NAME
----
perlcygwin - Perl for Cygwin
SYNOPSIS
--------
This document will help you configure, make, test and install Perl on Cygwin. This document also describes features of Cygwin that will affect how Perl behaves at runtime.
**NOTE:** There are pre-built Perl packages available for Cygwin and a version of Perl is provided in the normal Cygwin install. If you do not need to customize the configuration, consider using one of those packages.
PREREQUISITES FOR COMPILING PERL ON CYGWIN
-------------------------------------------
###
Cygwin = GNU+Cygnus+Windows (Don't leave UNIX without it)
The Cygwin tools are ports of the popular GNU development tools for Win32 platforms. They run thanks to the Cygwin library which provides the UNIX system calls and environment these programs expect. More information about this project can be found at:
<https://www.cygwin.com/>
A recent net or commercial release of Cygwin is required.
At the time this document was last updated, Cygwin 1.7.16 was current.
###
Cygwin Configuration
While building Perl some changes may be necessary to your Cygwin setup so that Perl builds cleanly. These changes are **not** required for normal Perl usage.
**NOTE:** The binaries that are built will run on all Win32 versions. They do not depend on your host system (WinXP/Win2K/Win7) or your Cygwin configuration (binary/text mounts, cvgserver). The only dependencies come from hard-coded pathnames like */usr/local*. However, your host system and Cygwin configuration will affect Perl's runtime behavior (see ["TEST"](#TEST)).
* `PATH`
Set the `PATH` environment variable so that Configure finds the Cygwin versions of programs. Any not-needed Windows directories should be removed or moved to the end of your `PATH`.
* *nroff*
If you do not have *nroff* (which is part of the *groff* package), Configure will **not** prompt you to install *man* pages.
CONFIGURE PERL ON CYGWIN
-------------------------
The default options gathered by Configure with the assistance of *hints/cygwin.sh* will build a Perl that supports dynamic loading (which requires a shared *cygperl5\_16.dll*).
This will run Configure and keep a record:
```
./Configure 2>&1 | tee log.configure
```
If you are willing to accept all the defaults run Configure with **-de**. However, several useful customizations are available.
###
Stripping Perl Binaries on Cygwin
It is possible to strip the EXEs and DLLs created by the build process. The resulting binaries will be significantly smaller. If you want the binaries to be stripped, you can either add a **-s** option when Configure prompts you,
```
Any additional ld flags (NOT including libraries)? [none] -s
Any special flags to pass to g++ to create a dynamically loaded
library?
[none] -s
Any special flags to pass to gcc to use dynamic linking? [none] -s
```
or you can edit *hints/cygwin.sh* and uncomment the relevant variables near the end of the file.
###
Optional Libraries for Perl on Cygwin
Several Perl functions and modules depend on the existence of some optional libraries. Configure will find them if they are installed in one of the directories listed as being used for library searches. Pre-built packages for most of these are available from the Cygwin installer.
* `-lcrypt`
The crypt package distributed with Cygwin is a Linux compatible 56-bit DES crypt port by Corinna Vinschen.
Alternatively, the crypt libraries in GNU libc have been ported to Cygwin.
As of libcrypt 1.3 (March 2016), you will need to install the libcrypt-devel package for Configure to detect crypt().
* `-lgdbm_compat` (`use GDBM_File`)
GDBM is available for Cygwin.
NOTE: The GDBM library only works on NTFS partitions.
* `-ldb` (`use DB_File`)
BerkeleyDB is available for Cygwin.
NOTE: The BerkeleyDB library only completely works on NTFS partitions.
* `cygserver` (`use IPC::SysV`)
A port of SysV IPC is available for Cygwin.
NOTE: This has **not** been extensively tested. In particular, `d_semctl_semun` is undefined because it fails a Configure test and on Win9x the *shm\*()* functions seem to hang. It also creates a compile time dependency because *perl.h* includes *<sys/ipc.h*> and *<sys/sem.h*> (which will be required in the future when compiling CPAN modules). CURRENTLY NOT SUPPORTED!
* `-lutil`
Included with the standard Cygwin netrelease is the inetutils package which includes libutil.a.
###
Configure-time Options for Perl on Cygwin
The *INSTALL* document describes several Configure-time options. Some of these will work with Cygwin, others are not yet possible. Also, some of these are experimental. You can either select an option when Configure prompts you or you can define (undefine) symbols on the command line.
* `-Uusedl`
Undefining this symbol forces Perl to be compiled statically.
* `-Dusemymalloc`
By default Perl does not use the `malloc()` included with the Perl source, because it was slower and not entirely thread-safe. If you want to force Perl to build with the old -Dusemymalloc define this.
* `-Uuseperlio`
Undefining this symbol disables the PerlIO abstraction. PerlIO is now the default; it is not recommended to disable PerlIO.
* `-Dusemultiplicity`
Multiplicity is required when embedding Perl in a C program and using more than one interpreter instance. This is only required when you build a not-threaded perl with `-Uuseithreads`.
* `-Uuse64bitint`
By default Perl uses 64 bit integers. If you want to use smaller 32 bit integers, define this symbol.
* `-Duselongdouble`
*gcc* supports long doubles (12 bytes). However, several additional long double math functions are necessary to use them within Perl (*{atan2, cos, exp, floor, fmod, frexp, isnan, log, modf, pow, sin, sqrt}l, strtold*). These are **not** yet available with newlib, the Cygwin libc.
* `-Uuseithreads`
Define this symbol if you want not-threaded faster perl.
* `-Duselargefiles`
Cygwin uses 64-bit integers for internal size and position calculations, this will be correctly detected and defined by Configure.
* `-Dmksymlinks`
Use this to build perl outside of the source tree. Details can be found in the *INSTALL* document. This is the recommended way to build perl from sources.
###
Suspicious Warnings on Cygwin
You may see some messages during Configure that seem suspicious.
* Win9x and `d_eofnblk`
Win9x does not correctly report `EOF` with a non-blocking read on a closed pipe. You will see the following messages:
```
But it also returns -1 to signal EOF, so be careful!
WARNING: you can't distinguish between EOF and no data!
*** WHOA THERE!!! ***
The recommended value for $d_eofnblk on this machine was
"define"!
Keep the recommended value? [y]
```
At least for consistency with WinNT, you should keep the recommended value.
* Compiler/Preprocessor defines
The following error occurs because of the Cygwin `#define` of `_LONG_DOUBLE`:
```
Guessing which symbols your C compiler and preprocessor define...
try.c:<line#>: missing binary operator
```
This failure does not seem to cause any problems. With older gcc versions, "parse error" is reported instead of "missing binary operator".
MAKE ON CYGWIN
---------------
Simply run *make* and wait:
```
make 2>&1 | tee log.make
```
TEST ON CYGWIN
---------------
There are two steps to running the test suite:
```
make test 2>&1 | tee log.make-test
cd t; ./perl harness 2>&1 | tee ../log.harness
```
The same tests are run both times, but more information is provided when running as `./perl harness`.
Test results vary depending on your host system and your Cygwin configuration. If a test can pass in some Cygwin setup, it is always attempted and explainable test failures are documented. It is possible for Perl to pass all the tests, but it is more likely that some tests will fail for one of the reasons listed below.
###
File Permissions on Cygwin
UNIX file permissions are based on sets of mode bits for {read,write,execute} for each {user,group,other}. By default Cygwin only tracks the Win32 read-only attribute represented as the UNIX file user write bit (files are always readable, files are executable if they have a *.{com,bat,exe}* extension or begin with `#!`, directories are always readable and executable). On WinNT with the *ntea* `CYGWIN` setting, the additional mode bits are stored as extended file attributes. On WinNT with the default *ntsec* `CYGWIN` setting, permissions use the standard WinNT security descriptors and access control lists. Without one of these options, these tests will fail (listing not updated yet):
```
Failed Test List of failed
------------------------------------
io/fs.t 5, 7, 9-10
lib/anydbm.t 2
lib/db-btree.t 20
lib/db-hash.t 16
lib/db-recno.t 18
lib/gdbm.t 2
lib/ndbm.t 2
lib/odbm.t 2
lib/sdbm.t 2
op/stat.t 9, 20 (.tmp not an executable extension)
```
###
NDBM\_File and ODBM\_File do not work on FAT filesystems
Do not use NDBM\_File or ODBM\_File on FAT filesystem. They can be built on a FAT filesystem, but many tests will fail:
```
../ext/NDBM_File/ndbm.t 13 3328 71 59 83.10% 1-2 4 16-71
../ext/ODBM_File/odbm.t 255 65280 ?? ?? % ??
../lib/AnyDBM_File.t 2 512 12 2 16.67% 1 4
../lib/Memoize/t/errors.t 0 139 11 5 45.45% 7-11
../lib/Memoize/t/tie_ndbm.t 13 3328 4 4 100.00% 1-4
run/fresh_perl.t 97 1 1.03% 91
```
If you intend to run only on FAT (or if using AnyDBM\_File on FAT), run Configure with the -Ui\_ndbm and -Ui\_dbm options to prevent NDBM\_File and ODBM\_File being built.
With NTFS (and no CYGWIN=nontsec), there should be no problems even if perl was built on FAT.
###
`fork()` failures in io\_\* tests
A `fork()` failure may result in the following tests failing:
```
ext/IO/lib/IO/t/io_multihomed.t
ext/IO/lib/IO/t/io_sock.t
ext/IO/lib/IO/t/io_unix.t
```
See comment on fork in ["Miscellaneous"](#Miscellaneous) below.
Specific features of the Cygwin port
-------------------------------------
###
Script Portability on Cygwin
Cygwin does an outstanding job of providing UNIX-like semantics on top of Win32 systems. However, in addition to the items noted above, there are some differences that you should know about. This is a very brief guide to portability, more information can be found in the Cygwin documentation.
* Pathnames
Cygwin pathnames are separated by forward (*/*) slashes, Universal Naming Codes (*//UNC*) are also supported Since cygwin-1.7 non-POSIX pathnames are discouraged. Names may contain all printable characters.
File names are case insensitive, but case preserving. A pathname that contains a backslash or drive letter is a Win32 pathname, and not subject to the translations applied to POSIX style pathnames, but cygwin will warn you, so better convert them to POSIX.
For conversion we have `Cygwin::win_to_posix_path()` and `Cygwin::posix_to_win_path()`.
Since cygwin-1.7 pathnames are UTF-8 encoded.
* Text/Binary
Since cygwin-1.7 textmounts are deprecated and strongly discouraged.
When a file is opened it is in either text or binary mode. In text mode a file is subject to CR/LF/Ctrl-Z translations. With Cygwin, the default mode for an `open()` is determined by the mode of the mount that underlies the file. See ["Cygwin::is\_binmount"](#Cygwin%3A%3Ais_binmount)(). Perl provides a `binmode()` function to set binary mode on files that otherwise would be treated as text. `sysopen()` with the `O_TEXT` flag sets text mode on files that otherwise would be treated as binary:
```
sysopen(FOO, "bar", O_WRONLY|O_CREAT|O_TEXT)
```
`lseek()`, `tell()` and `sysseek()` only work with files opened in binary mode.
The text/binary issue is covered at length in the Cygwin documentation.
* PerlIO
PerlIO overrides the default Cygwin Text/Binary behaviour. A file will always be treated as binary, regardless of the mode of the mount it lives on, just like it is in UNIX. So CR/LF translation needs to be requested in either the `open()` call like this:
```
open(FH, ">:crlf", "out.txt");
```
which will do conversion from LF to CR/LF on the output, or in the environment settings (add this to your .bashrc):
```
export PERLIO=crlf
```
which will pull in the crlf PerlIO layer which does LF -> CRLF conversion on every output generated by perl.
* *.exe*
The Cygwin `stat()`, `lstat()` and `readlink()` functions make the *.exe* extension transparent by looking for *foo.exe* when you ask for *foo* (unless a *foo* also exists). Cygwin does not require a *.exe* extension, but *gcc* adds it automatically when building a program. However, when accessing an executable as a normal file (e.g., *cp* in a makefile) the *.exe* is not transparent. The *install* program included with Cygwin automatically appends a *.exe* when necessary.
* Cygwin vs. Windows process ids
Cygwin processes have their own pid, which is different from the underlying windows pid. Most posix compliant Proc functions expect the cygwin pid, but several Win32::Process functions expect the winpid. E.g. `$$` is the cygwin pid of */usr/bin/perl*, which is not the winpid. Use `Cygwin::pid_to_winpid()` and `Cygwin::winpid_to_pid()` to translate between them.
* Cygwin vs. Windows errors
Under Cygwin, $^E is the same as $!. When using [Win32 API Functions](win32), use `Win32::GetLastError()` to get the last Windows error.
* rebase errors on fork or system
Using `fork()` or `system()` out to another perl after loading multiple dlls may result on a DLL baseaddress conflict. The internal cygwin error looks like like the following:
```
0 [main] perl 8916 child_info_fork::abort: data segment start:
parent (0xC1A000) != child(0xA6A000)
```
or:
```
183 [main] perl 3588 C:\cygwin\bin\perl.exe: *** fatal error -
unable to remap C:\cygwin\bin\cygsvn_subr-1-0.dll to same address
as parent(0x6FB30000) != 0x6FE60000 46 [main] perl 3488 fork: child
3588 - died waiting for dll loading, errno11
```
See <https://cygwin.com/faq/faq-nochunks.html#faq.using.fixing-fork-failures> It helps if not too many DLLs are loaded in memory so the available address space is larger, e.g. stopping the MS Internet Explorer might help.
Use the perlrebase or rebase utilities to resolve the conflicting dll addresses. The rebase package is included in the Cygwin setup. Use *setup.exe* from <https://cygwin.com/install.html> to install it.
1. kill all perl processes and run `perlrebase` or
2. kill all cygwin processes and services, start dash from cmd.exe and run `rebaseall`.
* `chown()`
On WinNT `chown()` can change a file's user and group IDs. On Win9x `chown()` is a no-op, although this is appropriate since there is no security model.
* Miscellaneous
File locking using the `F_GETLK` command to `fcntl()` is a stub that returns `ENOSYS`.
Win9x can not `rename()` an open file (although WinNT can).
The Cygwin `chroot()` implementation has holes (it can not restrict file access by native Win32 programs).
Inplace editing `perl -i` of files doesn't work without doing a backup of the file being edited `perl -i.bak` because of windowish restrictions, therefore Perl adds the suffix `.bak` automatically if you use `perl -i` without specifying a backup extension.
###
Prebuilt methods:
`Cwd::cwd`
Returns the current working directory.
`Cygwin::pid_to_winpid`
Translates a cygwin pid to the corresponding Windows pid (which may or may not be the same).
`Cygwin::winpid_to_pid`
Translates a Windows pid to the corresponding cygwin pid (if any).
`Cygwin::win_to_posix_path`
Translates a Windows path to the corresponding cygwin path respecting the current mount points. With a second non-null argument returns an absolute path. Double-byte characters will not be translated.
`Cygwin::posix_to_win_path`
Translates a cygwin path to the corresponding cygwin path respecting the current mount points. With a second non-null argument returns an absolute path. Double-byte characters will not be translated.
`Cygwin::mount_table()`
Returns an array of [mnt\_dir, mnt\_fsname, mnt\_type, mnt\_opts].
```
perl -e 'for $i (Cygwin::mount_table) {print join(" ",@$i),"\n";}'
/bin c:\cygwin\bin system binmode,cygexec
/usr/bin c:\cygwin\bin system binmode
/usr/lib c:\cygwin\lib system binmode
/ c:\cygwin system binmode
/cygdrive/c c: system binmode,noumount
/cygdrive/d d: system binmode,noumount
/cygdrive/e e: system binmode,noumount
```
`Cygwin::mount_flags`
Returns the mount type and flags for a specified mount point. A comma-separated string of mntent->mnt\_type (always "system" or "user"), then the mntent->mnt\_opts, where the first is always "binmode" or "textmode".
```
system|user,binmode|textmode,exec,cygexec,cygdrive,mixed,
notexec,managed,nosuid,devfs,proc,noumount
```
If the argument is "/cygdrive", then just the volume mount settings, and the cygdrive mount prefix are returned.
User mounts override system mounts.
```
$ perl -e 'print Cygwin::mount_flags "/usr/bin"'
system,binmode,cygexec
$ perl -e 'print Cygwin::mount_flags "/cygdrive"'
binmode,cygdrive,/cygdrive
```
`Cygwin::is_binmount`
Returns true if the given cygwin path is binary mounted, false if the path is mounted in textmode.
`Cygwin::sync_winenv`
Cygwin does not initialize all original Win32 environment variables. See the bottom of this page <https://cygwin.com/cygwin-ug-net/setup-env.html> for "Restricted Win32 environment".
Certain Win32 programs called from cygwin programs might need some environment variable, such as e.g. ADODB needs %COMMONPROGRAMFILES%. Call Cygwin::sync\_winenv() to copy all Win32 environment variables to your process and note that cygwin will warn on every encounter of non-POSIX paths.
INSTALL PERL ON CYGWIN
-----------------------
This will install Perl, including *man* pages.
```
make install 2>&1 | tee log.make-install
```
NOTE: If `STDERR` is redirected `make install` will **not** prompt you to install *perl* into */usr/bin*.
You may need to be *Administrator* to run `make install`. If you are not, you must have write access to the directories in question.
Information on installing the Perl documentation in HTML format can be found in the *INSTALL* document.
MANIFEST ON CYGWIN
-------------------
These are the files in the Perl release that contain references to Cygwin. These very brief notes attempt to explain the reason for all conditional code. Hopefully, keeping this up to date will allow the Cygwin port to be kept as clean as possible.
Documentation
```
INSTALL README.cygwin README.win32 MANIFEST
pod/perl.pod pod/perlport.pod pod/perlfaq3.pod
pod/perldelta.pod pod/perl5004delta.pod pod/perl56delta.pod
pod/perl561delta.pod pod/perl570delta.pod pod/perl572delta.pod
pod/perl573delta.pod pod/perl58delta.pod pod/perl581delta.pod
pod/perl590delta.pod pod/perlhist.pod pod/perlmodlib.pod
pod/perltoc.pod Porting/Glossary pod/perlgit.pod
Porting/checkAUTHORS.pl
dist/Cwd/Changes ext/Compress-Raw-Zlib/Changes
dist/Time-HiRes/Changes
ext/Compress-Raw-Zlib/README ext/Compress-Zlib/Changes
ext/DB_File/Changes ext/Encode/Changes ext/Sys-Syslog/Changes
ext/Win32API-File/Changes
lib/ExtUtils/CBuilder/Changes lib/ExtUtils/Changes
lib/ExtUtils/NOTES lib/ExtUtils/PATCHING lib/ExtUtils/README
lib/Net/Ping/Changes lib/Test/Harness/Changes
lib/Term/ANSIColor/ChangeLog lib/Term/ANSIColor/README
```
Build, Configure, Make, Install
```
cygwin/Makefile.SHs
ext/IPC/SysV/hints/cygwin.pl
ext/NDBM_File/hints/cygwin.pl
ext/ODBM_File/hints/cygwin.pl
hints/cygwin.sh
Configure - help finding hints from uname,
shared libperl required for dynamic loading
Makefile.SH Cross/Makefile-cross-SH
- linklibperl
Porting/patchls - cygwin in port list
installman - man pages with :: translated to .
installperl - install dll, install to 'pods'
makedepend.SH - uwinfix
regen_lib.pl - file permissions
plan9/mkfile
vms/descrip_mms.template
win32/Makefile
```
Tests
```
t/io/fs.t - no file mode checks if not ntsec
skip rename() check when not
check_case:relaxed
t/io/tell.t - binmode
t/lib/cygwin.t - builtin cygwin function tests
t/op/groups.t - basegroup has ID = 0
t/op/magic.t - $^X/symlink WORKAROUND, s/.exe//
t/op/stat.t - no /dev, skip Win32 ftCreationTime quirk
(cache manager sometimes preserves ctime of
file previously created and deleted), no -u
(setuid)
t/op/taint.t - can't use empty path under Cygwin Perl
t/op/time.t - no tzset()
```
Compiled Perl Source
```
EXTERN.h - __declspec(dllimport)
XSUB.h - __declspec(dllexport)
cygwin/cygwin.c - os_extras (getcwd, spawn, and several
Cygwin:: functions)
perl.c - os_extras, -i.bak
perl.h - binmode
doio.c - win9x can not rename a file when it is open
pp_sys.c - do not define h_errno, init
_pwent_struct.pw_comment
util.c - use setenv
util.h - PERL_FILE_IS_ABSOLUTE macro
pp.c - Comment about Posix vs IEEE math under
Cygwin
perlio.c - CR/LF mode
perliol.c - Comment about EXTCONST under Cygwin
```
Compiled Module Source
```
ext/Compress-Raw-Zlib/Makefile.PL
- Can't install via CPAN shell under Cygwin
ext/Compress-Raw-Zlib/zlib-src/zutil.h
- Cygwin is Unix-like and has vsnprintf
ext/Errno/Errno_pm.PL - Special handling for Win32 Perl under
Cygwin
ext/POSIX/POSIX.xs - tzname defined externally
ext/SDBM_File/sdbm/pair.c
- EXTCONST needs to be redefined from
EXTERN.h
ext/SDBM_File/sdbm/sdbm.c
- binary open
ext/Sys/Syslog/Syslog.xs
- Cygwin has syslog.h
ext/Sys/Syslog/win32/compile.pl
- Convert paths to Windows paths
ext/Time-HiRes/HiRes.xs
- Various timers not available
ext/Time-HiRes/Makefile.PL
- Find w32api/windows.h
ext/Win32/Makefile.PL - Use various libraries under Cygwin
ext/Win32/Win32.xs - Child dir and child env under Cygwin
ext/Win32API-File/File.xs
- _open_osfhandle not implemented under
Cygwin
ext/Win32CORE/Win32CORE.c
- __declspec(dllexport)
```
Perl Modules/Scripts
```
ext/B/t/OptreeCheck.pm - Comment about stderr/stdout order under
Cygwin
ext/Digest-SHA/bin/shasum
- Use binary mode under Cygwin
ext/Sys/Syslog/win32/Win32.pm
- Convert paths to Windows paths
ext/Time-HiRes/HiRes.pm
- Comment about various timers not available
ext/Win32API-File/File.pm
- _open_osfhandle not implemented under
Cygwin
ext/Win32CORE/Win32CORE.pm
- History of Win32CORE under Cygwin
lib/Cwd.pm - hook to internal Cwd::cwd
lib/ExtUtils/CBuilder/Platform/cygwin.pm
- use gcc for ld, and link to libperl.dll.a
lib/ExtUtils/CBuilder.pm
- Cygwin is Unix-like
lib/ExtUtils/Install.pm - Install and rename issues under Cygwin
lib/ExtUtils/MM.pm - OS classifications
lib/ExtUtils/MM_Any.pm - Example for Cygwin
lib/ExtUtils/MakeMaker.pm
- require MM_Cygwin.pm
lib/ExtUtils/MM_Cygwin.pm
- canonpath, cflags, manifypods, perl_archive
lib/File/Fetch.pm - Comment about quotes using a Cygwin example
lib/File/Find.pm - on remote drives stat() always sets
st_nlink to 1
lib/File/Spec/Cygwin.pm - case_tolerant
lib/File/Spec/Unix.pm - preserve //unc
lib/File/Spec/Win32.pm - References a message on cygwin.com
lib/File/Spec.pm - Pulls in lib/File/Spec/Cygwin.pm
lib/File/Temp.pm - no directory sticky bit
lib/Module/CoreList.pm - List of all module files and versions
lib/Net/Domain.pm - No domainname command under Cygwin
lib/Net/Netrc.pm - Bypass using stat() under Cygwin
lib/Net/Ping.pm - ECONREFUSED is EAGAIN under Cygwin
lib/Pod/Find.pm - Set 'pods' dir
lib/Pod/Perldoc/ToMan.pm - '-c' switch for pod2man
lib/Pod/Perldoc.pm - Use 'less' pager, and use .exe extension
lib/Term/ANSIColor.pm - Cygwin terminal info
lib/perl5db.pl - use stdin not /dev/tty
utils/perlbug.PL - Add CYGWIN environment variable to report
```
Perl Module Tests
```
dist/Cwd/t/cwd.t
ext/Compress-Zlib/t/14gzopen.t
ext/DB_File/t/db-btree.t
ext/DB_File/t/db-hash.t
ext/DB_File/t/db-recno.t
ext/DynaLoader/t/DynaLoader.t
ext/File-Glob/t/basic.t
ext/GDBM_File/t/gdbm.t
ext/POSIX/t/sysconf.t
ext/POSIX/t/time.t
ext/SDBM_File/t/sdbm.t
ext/Sys/Syslog/t/syslog.t
ext/Time-HiRes/t/HiRes.t
ext/Win32/t/Unicode.t
ext/Win32API-File/t/file.t
ext/Win32CORE/t/win32core.t
lib/AnyDBM_File.t
lib/Archive/Extract/t/01_Archive-Extract.t
lib/Archive/Tar/t/02_methods.t
lib/ExtUtils/t/Embed.t
lib/ExtUtils/t/eu_command.t
lib/ExtUtils/t/MM_Cygwin.t
lib/ExtUtils/t/MM_Unix.t
lib/File/Compare.t
lib/File/Copy.t
lib/File/Find/t/find.t
lib/File/Path.t
lib/File/Spec/t/crossplatform.t
lib/File/Spec/t/Spec.t
lib/Net/hostent.t
lib/Net/Ping/t/110_icmp_inst.t
lib/Net/Ping/t/500_ping_icmp.t
lib/Net/t/netrc.t
lib/Pod/Simple/t/perlcyg.pod
lib/Pod/Simple/t/perlcygo.txt
lib/Pod/Simple/t/perlfaq.pod
lib/Pod/Simple/t/perlfaqo.txt
lib/User/grent.t
lib/User/pwent.t
```
BUGS ON CYGWIN
---------------
Support for swapping real and effective user and group IDs is incomplete. On WinNT Cygwin provides `setuid()`, `seteuid()`, `setgid()` and `setegid()`. However, additional Cygwin calls for manipulating WinNT access tokens and security contexts are required.
AUTHORS
-------
Charles Wilson <[email protected]>, Eric Fifer <[email protected]>, alexander smishlajev <[email protected]>, Steven Morlock <[email protected]>, Sebastien Barre <[email protected]>, Teun Burgers <[email protected]>, Gerrit P. Haase <[email protected]>, Reini Urban <[email protected]>, Jan Dubois <[email protected]>, Jerry D. Hedden <[email protected]>.
HISTORY
-------
Last updated: 2012-02-08
| programming_docs |
perl perlirix perlirix
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Building 32-bit Perl in Irix](#Building-32-bit-Perl-in-Irix)
+ [Building 64-bit Perl in Irix](#Building-64-bit-Perl-in-Irix)
+ [About Compiler Versions of Irix](#About-Compiler-Versions-of-Irix)
+ [Linker Problems in Irix](#Linker-Problems-in-Irix)
+ [Malloc in Irix](#Malloc-in-Irix)
+ [Building with threads in Irix](#Building-with-threads-in-Irix)
+ [Irix 5.3](#Irix-5.3)
* [AUTHOR](#AUTHOR)
NAME
----
perlirix - Perl version 5 on Irix systems
DESCRIPTION
-----------
This document describes various features of Irix that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
Building 32-bit Perl in Irix
Use
```
sh Configure -Dcc='cc -n32'
```
to compile Perl 32-bit. Don't bother with -n32 unless you have 7.1 or later compilers (use cc -version to check).
(Building 'cc -n32' is the default.)
###
Building 64-bit Perl in Irix
Use
```
sh Configure -Dcc='cc -64' -Duse64bitint
```
This requires require a 64-bit MIPS CPU (R8000, R10000, ...)
You can also use
```
sh Configure -Dcc='cc -64' -Duse64bitall
```
but that makes no difference compared with the -Duse64bitint because of the `cc -64`.
You can also do
```
sh Configure -Dcc='cc -n32' -Duse64bitint
```
to use long longs for the 64-bit integer type, in case you don't have a 64-bit CPU.
If you are using gcc, just
```
sh Configure -Dcc=gcc -Duse64bitint
```
should be enough, the Configure should automatically probe for the correct 64-bit settings.
###
About Compiler Versions of Irix
Some Irix cc versions, e.g. 7.3.1.1m (try cc -version) have been known to have issues (coredumps) when compiling perl.c. If you've used -OPT:fast\_io=ON and this happens, try removing it. If that fails, or you didn't use that, then try adjusting other optimization options (-LNO, -INLINE, -O3 to -O2, et cetera). The compiler bug has been reported to SGI. (Allen Smith <[email protected]>)
###
Linker Problems in Irix
If you get complaints about so\_locations then search in the file hints/irix\_6.sh for "lddflags" and do the suggested adjustments. (David Billinghurst <[email protected]>)
###
Malloc in Irix
Do not try to use Perl's malloc, this will lead into very mysterious errors (especially with -Duse64bitall).
###
Building with threads in Irix
Run Configure with -Duseithreads which will configure Perl with the Perl 5.8.0 "interpreter threads", see <threads>.
For Irix 6.2 with perl threads, you have to have the following patches installed:
```
1404 Irix 6.2 Posix 1003.1b man pages
1645 Irix 6.2 & 6.3 POSIX header file updates
2000 Irix 6.2 Posix 1003.1b support modules
2254 Pthread library fixes
2401 6.2 all platform kernel rollup
```
**IMPORTANT**: Without patch 2401, a kernel bug in Irix 6.2 will cause your machine to panic and crash when running threaded perl. Irix 6.3 and later are okay.
```
Thanks to Hannu Napari <[email protected]> for the IRIX
pthreads patches information.
```
###
Irix 5.3
While running Configure and when building, you are likely to get quite a few of these warnings:
```
ld:
The shared object /usr/lib/libm.so did not resolve any symbols.
You may want to remove it from your link line.
```
Ignore them: in IRIX 5.3 there is no way to quieten ld about this.
During compilation you will see this warning from toke.c:
```
uopt: Warning: Perl_yylex: this procedure not optimized because it
exceeds size threshold; to optimize this procedure, use -Olimit
option with value >= 4252.
```
Ignore the warning.
In IRIX 5.3 and with Perl 5.8.1 (Perl 5.8.0 didn't compile in IRIX 5.3) the following failures are known.
```
Failed Test Stat Wstat Total Fail Failed|Failing List
-----------------------------------------------------------------------
../ext/List/Util/t/shuffle.t 0 139 ?? ?? % ??
../lib/Math/Trig.t 255 65280 29 12 41.38% 24-29
../lib/sort.t 0 138 119 72 60.50% 48-119
56 tests and 474 subtests skipped.
Failed 3/811 test scripts, 99.63% okay. 78/75813 subtests failed,
99.90% okay.
```
They are suspected to be compiler errors (at least the shuffle.t failure is known from some IRIX 6 setups) and math library errors (the Trig.t failure), but since IRIX 5 is long since end-of-lifed, further fixes for the IRIX are unlikely. If you can get gcc for 5.3, you could try that, too, since gcc in IRIX 6 is a known workaround for at least the shuffle.t and sort.t failures.
AUTHOR
------
Jarkko Hietaniemi <[email protected]>
Please report any errors, updates, or suggestions to <https://github.com/Perl/perl5/issues>.
perl Pod::Escapes Pod::Escapes
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [GOODIES](#GOODIES)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [REPOSITORY](#REPOSITORY)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Escapes - for resolving Pod E<...> sequences
SYNOPSIS
--------
```
use Pod::Escapes qw(e2char);
...la la la, parsing POD, la la la...
$text = e2char($e_node->label);
unless(defined $text) {
print "Unknown E sequence \"", $e_node->label, "\"!";
}
...else print/interpolate $text...
```
DESCRIPTION
-----------
This module provides things that are useful in decoding Pod E<...> sequences. Presumably, it should be used only by Pod parsers and/or formatters.
By default, Pod::Escapes exports none of its symbols. But you can request any of them to be exported. Either request them individually, as with `use Pod::Escapes qw(symbolname symbolname2...);`, or you can do `use Pod::Escapes qw(:ALL);` to get all exportable symbols.
GOODIES
-------
e2char($e\_content) Given a name or number that could appear in a `E<name_or_num>` sequence, this returns the string that it stands for. For example, `e2char('sol')`, `e2char('47')`, `e2char('0x2F')`, and `e2char('057')` all return "/", because `E<sol>`, `E<47>`, `E<0x2f>`, and `E<057>`, all mean "/". If the name has no known value (as with a name of "qacute") or is syntactically invalid (as with a name of "1/4"), this returns undef.
e2charnum($e\_content) Given a name or number that could appear in a `E<name_or_num>` sequence, this returns the number of the Unicode character that this stands for. For example, `e2char('sol')`, `e2char('47')`, `e2char('0x2F')`, and `e2char('057')` all return 47, because `E<sol>`, `E<47>`, `E<0x2f>`, and `E<057>`, all mean "/", whose Unicode number is 47. If the name has no known value (as with a name of "qacute") or is syntactically invalid (as with a name of "1/4"), this returns undef.
$Name2character{*name*} Maps from names (as in `E<*name*>`) like "eacute" or "sol" to the string that each stands for. Note that this does not include numerics (like "64" or "x981c"). Under old Perl versions (before 5.7) you get a "?" in place of characters whose Unicode value is over 255.
$Name2character\_number{*name*} Maps from names (as in `E<*name*>`) like "eacute" or "sol" to the Unicode value that each stands for. For example, `$Name2character_number{'eacute'}` is 201, and `$Name2character_number{'eacute'}` is 8364. You get the correct Unicode value, regardless of the version of Perl you're using -- which differs from `%Name2character`'s behavior under pre-5.7 Perls.
Note that this hash does not include numerics (like "64" or "x981c").
$Latin1Code\_to\_fallback{*integer*} For numbers in the range 160 (0x00A0) to 255 (0x00FF), this maps from the character code for a Latin-1 character (like 233 for lowercase e-acute) to the US-ASCII character that best aproximates it (like "e"). You may find this useful if you are rendering POD in a format that you think deals well only with US-ASCII characters.
$Latin1Char\_to\_fallback{*character*} Just as above, but maps from characters (like "\xE9", lowercase e-acute) to characters (like "e").
$Code2USASCII{*integer*} This maps from US-ASCII codes (like 32) to the corresponding character (like space, for 32). Only characters 32 to 126 are defined. This is meant for use by `e2char($x)` when it senses that it's running on a non-ASCII platform (where chr(32) doesn't get you a space -- but $Code2USASCII{32} will). It's documented here just in case you might find it useful.
CAVEATS
-------
On Perl versions before 5.7, Unicode characters with a value over 255 (like lambda or emdash) can't be conveyed. This module does work under such early Perl versions, but in the place of each such character, you get a "?". Latin-1 characters (characters 160-255) are unaffected.
Under EBCDIC platforms, `e2char($n)` may not always be the same as `chr(e2charnum($n))`, and ditto for `$Name2character{$name}` and `chr($Name2character_number{$name})`, because the strings are returned as native, and the numbers are returned as Unicode. However, for Perls starting with v5.8, `e2char($n)` is the same as `chr(utf8::unicode_to_native(e2charnum($n)))`, and ditto for `$Name2character{$name}` and `chr(utf8::unicode_to_native($Name2character_number{$name}))`.
SEE ALSO
---------
<Pod::Browser> - a pod web server based on [Catalyst](catalyst).
<Pod::Checker> - check pod documents for syntax errors.
<Pod::Coverage> - check if the documentation for a module is comprehensive.
<perlpod> - description of pod format (for people documenting with pod).
<perlpodspec> - specification of pod format (for people processing it).
<Text::Unidecode> - ASCII transliteration of Unicode text.
REPOSITORY
----------
<https://github.com/neilbowers/Pod-Escapes>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2001-2004 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
Portions of the data tables in this module are derived from the entity declarations in the W3C XHTML specification.
Currently (October 2001), that's these three:
```
http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent
http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent
http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent
```
AUTHOR
------
Sean M. Burke `[email protected]`
Now being maintained by Neil Bowers <[email protected]>
perl perlport perlport
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [ISSUES](#ISSUES)
+ [Newlines](#Newlines)
+ [Numbers endianness and Width](#Numbers-endianness-and-Width)
+ [Files and Filesystems](#Files-and-Filesystems)
+ [System Interaction](#System-Interaction)
+ [Command names versus file pathnames](#Command-names-versus-file-pathnames)
+ [Networking](#Networking)
+ [Interprocess Communication (IPC)](#Interprocess-Communication-(IPC))
+ [External Subroutines (XS)](#External-Subroutines-(XS))
+ [Standard Modules](#Standard-Modules)
+ [Time and Date](#Time-and-Date)
+ [Character sets and character encoding](#Character-sets-and-character-encoding)
+ [Internationalisation](#Internationalisation)
+ [System Resources](#System-Resources)
+ [Security](#Security)
+ [Style](#Style)
* [CPAN Testers](#CPAN-Testers)
* [PLATFORMS](#PLATFORMS)
+ [Unix](#Unix)
+ [DOS and Derivatives](#DOS-and-Derivatives)
+ [VMS](#VMS)
+ [VOS](#VOS)
+ [EBCDIC Platforms](#EBCDIC-Platforms)
+ [Acorn RISC OS](#Acorn-RISC-OS)
+ [Other perls](#Other-perls)
* [FUNCTION IMPLEMENTATIONS](#FUNCTION-IMPLEMENTATIONS)
+ [Alphabetical Listing of Perl Functions](#Alphabetical-Listing-of-Perl-Functions)
* [Supported Platforms](#Supported-Platforms)
* [EOL Platforms](#EOL-Platforms)
+ [(Perl 5.36)](#(Perl-5.36))
+ [(Perl 5.20)](#(Perl-5.20))
+ [(Perl 5.14)](#(Perl-5.14))
+ [(Perl 5.12)](#(Perl-5.12))
* [Supported Platforms (Perl 5.8)](#Supported-Platforms-(Perl-5.8))
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS / CONTRIBUTORS](#AUTHORS-/-CONTRIBUTORS)
NAME
----
perlport - Writing portable Perl
DESCRIPTION
-----------
Perl runs on numerous operating systems. While most of them share much in common, they also have their own unique features.
This document is meant to help you to find out what constitutes portable Perl code. That way once you make a decision to write portably, you know where the lines are drawn, and you can stay within them.
There is a tradeoff between taking full advantage of one particular type of computer and taking advantage of a full range of them. Naturally, as you broaden your range and become more diverse, the common factors drop, and you are left with an increasingly smaller area of common ground in which you can operate to accomplish a particular task. Thus, when you begin attacking a problem, it is important to consider under which part of the tradeoff curve you want to operate. Specifically, you must decide whether it is important that the task that you are coding has the full generality of being portable, or whether to just get the job done right now. This is the hardest choice to be made. The rest is easy, because Perl provides many choices, whichever way you want to approach your problem.
Looking at it another way, writing portable code is usually about willfully limiting your available choices. Naturally, it takes discipline and sacrifice to do that. The product of portability and convenience may be a constant. You have been warned.
Be aware of two important points:
Not all Perl programs have to be portable There is no reason you should not use Perl as a language to glue Unix tools together, or to prototype a Macintosh application, or to manage the Windows registry. If it makes no sense to aim for portability for one reason or another in a given program, then don't bother.
Nearly all of Perl already *is* portable Don't be fooled into thinking that it is hard to create portable Perl code. It isn't. Perl tries its level-best to bridge the gaps between what's available on different platforms, and all the means available to use those features. Thus almost all Perl code runs on any machine without modification. But there are some significant issues in writing portable code, and this document is entirely about those issues.
Here's the general rule: When you approach a task commonly done using a whole range of platforms, think about writing portable code. That way, you don't sacrifice much by way of the implementation choices you can avail yourself of, and at the same time you can give your users lots of platform choices. On the other hand, when you have to take advantage of some unique feature of a particular platform, as is often the case with systems programming (whether for Unix, Windows, VMS, etc.), consider writing platform-specific code.
When the code will run on only two or three operating systems, you may need to consider only the differences of those particular systems. The important thing is to decide where the code will run and to be deliberate in your decision.
The material below is separated into three main sections: main issues of portability (["ISSUES"](#ISSUES)), platform-specific issues (["PLATFORMS"](#PLATFORMS)), and built-in Perl functions that behave differently on various ports (["FUNCTION IMPLEMENTATIONS"](#FUNCTION-IMPLEMENTATIONS)).
This information should not be considered complete; it includes possibly transient information about idiosyncrasies of some of the ports, almost all of which are in a state of constant evolution. Thus, this material should be considered a perpetual work in progress (`<IMG SRC="yellow_sign.gif" ALT="Under Construction">`).
ISSUES
------
### Newlines
In most operating systems, lines in files are terminated by newlines. Just what is used as a newline may vary from OS to OS. Unix traditionally uses `\012`, one type of DOSish I/O uses `\015\012`, Mac OS uses `\015`, and z/OS uses `\025`.
Perl uses `\n` to represent the "logical" newline, where what is logical may depend on the platform in use. In MacPerl, `\n` always means `\015`. On EBCDIC platforms, `\n` could be `\025` or `\045`. In DOSish perls, `\n` usually means `\012`, but when accessing a file in "text" mode, perl uses the `:crlf` layer that translates it to (or from) `\015\012`, depending on whether you're reading or writing. Unix does the same thing on ttys in canonical mode. `\015\012` is commonly referred to as CRLF.
To trim trailing newlines from text lines use [`chomp`](perlfunc#chomp-VARIABLE). With default settings that function looks for a trailing `\n` character and thus trims in a portable way.
When dealing with binary files (or text files in binary mode) be sure to explicitly set [`$/`](perlvar#%24%2F) to the appropriate value for your file format before using [`chomp`](perlfunc#chomp-VARIABLE).
Because of the "text" mode translation, DOSish perls have limitations in using [`seek`](perlfunc#seek-FILEHANDLE%2CPOSITION%2CWHENCE) and [`tell`](perlfunc#tell-FILEHANDLE) on a file accessed in "text" mode. Stick to [`seek`](perlfunc#seek-FILEHANDLE%2CPOSITION%2CWHENCE)-ing to locations you got from [`tell`](perlfunc#tell-FILEHANDLE) (and no others), and you are usually free to use [`seek`](perlfunc#seek-FILEHANDLE%2CPOSITION%2CWHENCE) and [`tell`](perlfunc#tell-FILEHANDLE) even in "text" mode. Using [`seek`](perlfunc#seek-FILEHANDLE%2CPOSITION%2CWHENCE) or [`tell`](perlfunc#tell-FILEHANDLE) or other file operations may be non-portable. If you use [`binmode`](perlfunc#binmode-FILEHANDLE) on a file, however, you can usually [`seek`](perlfunc#seek-FILEHANDLE%2CPOSITION%2CWHENCE) and [`tell`](perlfunc#tell-FILEHANDLE) with arbitrary values safely.
A common misconception in socket programming is that `\n eq \012` everywhere. When using protocols such as common Internet protocols, `\012` and `\015` are called for specifically, and the values of the logical `\n` and `\r` (carriage return) are not reliable.
```
print $socket "Hi there, client!\r\n"; # WRONG
print $socket "Hi there, client!\015\012"; # RIGHT
```
However, using `\015\012` (or `\cM\cJ`, or `\x0D\x0A`) can be tedious and unsightly, as well as confusing to those maintaining the code. As such, the [`Socket`](socket) module supplies the Right Thing for those who want it.
```
use Socket qw(:DEFAULT :crlf);
print $socket "Hi there, client!$CRLF" # RIGHT
```
When reading from a socket, remember that the default input record separator [`$/`](perlvar#%24%2F) is `\n`, but robust socket code will recognize as either `\012` or `\015\012` as end of line:
```
while (<$socket>) { # NOT ADVISABLE!
# ...
}
```
Because both CRLF and LF end in LF, the input record separator can be set to LF and any CR stripped later. Better to write:
```
use Socket qw(:DEFAULT :crlf);
local($/) = LF; # not needed if $/ is already \012
while (<$socket>) {
s/$CR?$LF/\n/; # not sure if socket uses LF or CRLF, OK
# s/\015?\012/\n/; # same thing
}
```
This example is preferred over the previous one--even for Unix platforms--because now any `\015`'s (`\cM`'s) are stripped out (and there was much rejoicing).
Similarly, functions that return text data--such as a function that fetches a web page--should sometimes translate newlines before returning the data, if they've not yet been translated to the local newline representation. A single line of code will often suffice:
```
$data =~ s/\015?\012/\n/g;
return $data;
```
Some of this may be confusing. Here's a handy reference to the ASCII CR and LF characters. You can print it out and stick it in your wallet.
```
LF eq \012 eq \x0A eq \cJ eq chr(10) eq ASCII 10
CR eq \015 eq \x0D eq \cM eq chr(13) eq ASCII 13
| Unix | DOS | Mac |
---------------------------
\n | LF | LF | CR |
\r | CR | CR | LF |
\n * | LF | CRLF | CR |
\r * | CR | CR | LF |
---------------------------
* text-mode STDIO
```
The Unix column assumes that you are not accessing a serial line (like a tty) in canonical mode. If you are, then CR on input becomes "\n", and "\n" on output becomes CRLF.
These are just the most common definitions of `\n` and `\r` in Perl. There may well be others. For example, on an EBCDIC implementation such as z/OS (OS/390) or OS/400 (using the ILE, the PASE is ASCII-based) the above material is similar to "Unix" but the code numbers change:
```
LF eq \025 eq \x15 eq \cU eq chr(21) eq CP-1047 21
LF eq \045 eq \x25 eq chr(37) eq CP-0037 37
CR eq \015 eq \x0D eq \cM eq chr(13) eq CP-1047 13
CR eq \015 eq \x0D eq \cM eq chr(13) eq CP-0037 13
| z/OS | OS/400 |
----------------------
\n | LF | LF |
\r | CR | CR |
\n * | LF | LF |
\r * | CR | CR |
----------------------
* text-mode STDIO
```
###
Numbers endianness and Width
Different CPUs store integers and floating point numbers in different orders (called *endianness*) and widths (32-bit and 64-bit being the most common today). This affects your programs when they attempt to transfer numbers in binary format from one CPU architecture to another, usually either "live" via network connection, or by storing the numbers to secondary storage such as a disk file or tape.
Conflicting storage orders make an utter mess out of the numbers. If a little-endian host (Intel, VAX) stores 0x12345678 (305419896 in decimal), a big-endian host (Motorola, Sparc, PA) reads it as 0x78563412 (2018915346 in decimal). Alpha and MIPS can be either: Digital/Compaq used/uses them in little-endian mode; SGI/Cray uses them in big-endian mode. To avoid this problem in network (socket) connections use the [`pack`](perlfunc#pack-TEMPLATE%2CLIST) and [`unpack`](perlfunc#unpack-TEMPLATE%2CEXPR) formats `n` and `N`, the "network" orders. These are guaranteed to be portable.
As of Perl 5.10.0, you can also use the `>` and `<` modifiers to force big- or little-endian byte-order. This is useful if you want to store signed integers or 64-bit integers, for example.
You can explore the endianness of your platform by unpacking a data structure packed in native format such as:
```
print unpack("h*", pack("s2", 1, 2)), "\n";
# '10002000' on e.g. Intel x86 or Alpha 21064 in little-endian mode
# '00100020' on e.g. Motorola 68040
```
If you need to distinguish between endian architectures you could use either of the variables set like so:
```
$is_big_endian = unpack("h*", pack("s", 1)) =~ /01/;
$is_little_endian = unpack("h*", pack("s", 1)) =~ /^1/;
```
Differing widths can cause truncation even between platforms of equal endianness. The platform of shorter width loses the upper parts of the number. There is no good solution for this problem except to avoid transferring or storing raw binary numbers.
One can circumnavigate both these problems in two ways. Either transfer and store numbers always in text format, instead of raw binary, or else consider using modules like [`Data::Dumper`](Data::Dumper) and [`Storable`](storable) (included as of Perl 5.8). Keeping all data as text significantly simplifies matters.
###
Files and Filesystems
Most platforms these days structure files in a hierarchical fashion. So, it is reasonably safe to assume that all platforms support the notion of a "path" to uniquely identify a file on the system. How that path is really written, though, differs considerably.
Although similar, file path specifications differ between Unix, Windows, Mac OS, OS/2, VMS, VOS, RISC OS, and probably others. Unix, for example, is one of the few OSes that has the elegant idea of a single root directory.
DOS, OS/2, VMS, VOS, and Windows can work similarly to Unix with `/` as path separator, or in their own idiosyncratic ways (such as having several root directories and various "unrooted" device files such NIL: and LPT:).
Mac OS 9 and earlier used `:` as a path separator instead of `/`.
The filesystem may support neither hard links ([`link`](perlfunc#link-OLDFILE%2CNEWFILE)) nor symbolic links ([`symlink`](perlfunc#symlink-OLDFILE%2CNEWFILE), [`readlink`](perlfunc#readlink-EXPR), [`lstat`](perlfunc#lstat-FILEHANDLE)).
The filesystem may support neither access timestamp nor change timestamp (meaning that about the only portable timestamp is the modification timestamp), or one second granularity of any timestamps (e.g. the FAT filesystem limits the time granularity to two seconds).
The "inode change timestamp" (the [`-C`](perlfunc#-X-FILEHANDLE) filetest) may really be the "creation timestamp" (which it is not in Unix).
VOS perl can emulate Unix filenames with `/` as path separator. The native pathname characters greater-than, less-than, number-sign, and percent-sign are always accepted.
RISC OS perl can emulate Unix filenames with `/` as path separator, or go native and use `.` for path separator and `:` to signal filesystems and disk names.
Don't assume Unix filesystem access semantics: that read, write, and execute are all the permissions there are, and even if they exist, that their semantics (for example what do `r`, `w`, and `x` mean on a directory) are the Unix ones. The various Unix/POSIX compatibility layers usually try to make interfaces like [`chmod`](perlfunc#chmod-LIST) work, but sometimes there simply is no good mapping.
The [`File::Spec`](File::Spec) modules provide methods to manipulate path specifications and return the results in native format for each platform. This is often unnecessary as Unix-style paths are understood by Perl on every supported platform, but if you need to produce native paths for a native utility that does not understand Unix syntax, or if you are operating on paths or path components in unknown (and thus possibly native) syntax, [`File::Spec`](File::Spec) is your friend. Here are two brief examples:
```
use File::Spec::Functions;
chdir(updir()); # go up one directory
# Concatenate a path from its components
my $file = catfile(updir(), 'temp', 'file.txt');
# on Unix: '../temp/file.txt'
# on Win32: '..\temp\file.txt'
# on VMS: '[-.temp]file.txt'
```
In general, production code should not have file paths hardcoded. Making them user-supplied or read from a configuration file is better, keeping in mind that file path syntax varies on different machines.
This is especially noticeable in scripts like Makefiles and test suites, which often assume `/` as a path separator for subdirectories.
Also of use is [`File::Basename`](File::Basename) from the standard distribution, which splits a pathname into pieces (base filename, full path to directory, and file suffix).
Even when on a single platform (if you can call Unix a single platform), remember not to count on the existence or the contents of particular system-specific files or directories, like */etc/passwd*, */etc/sendmail.conf*, */etc/resolv.conf*, or even */tmp/*. For example, */etc/passwd* may exist but not contain the encrypted passwords, because the system is using some form of enhanced security. Or it may not contain all the accounts, because the system is using NIS. If code does need to rely on such a file, include a description of the file and its format in the code's documentation, then make it easy for the user to override the default location of the file.
Don't assume a text file will end with a newline. They should, but people forget.
Do not have two files or directories of the same name with different case, like *test.pl* and *Test.pl*, as many platforms have case-insensitive (or at least case-forgiving) filenames. Also, try not to have non-word characters (except for `.`) in the names, and keep them to the 8.3 convention, for maximum portability, onerous a burden though this may appear.
Likewise, when using the [`AutoSplit`](autosplit) module, try to keep your functions to 8.3 naming and case-insensitive conventions; or, at the least, make it so the resulting files have a unique (case-insensitively) first 8 characters.
Whitespace in filenames is tolerated on most systems, but not all, and even on systems where it might be tolerated, some utilities might become confused by such whitespace.
Many systems (DOS, VMS ODS-2) cannot have more than one `.` in their filenames.
Don't assume `>` won't be the first character of a filename. Always use the three-arg version of [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR):
```
open my $fh, '<', $existing_file) or die $!;
```
Two-arg [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) is magic and can translate characters like `>`, `<`, and `|` in filenames, which is usually the wrong thing to do. [`sysopen`](perlfunc#sysopen-FILEHANDLE%2CFILENAME%2CMODE) and three-arg [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) don't have this problem.
Don't use `:` as a part of a filename since many systems use that for their own semantics (Mac OS Classic for separating pathname components, many networking schemes and utilities for separating the nodename and the pathname, and so on). For the same reasons, avoid `@`, `;` and `|`.
Don't assume that in pathnames you can collapse two leading slashes `//` into one: some networking and clustering filesystems have special semantics for that. Let the operating system sort it out.
The *portable filename characters* as defined by ANSI C are
```
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
. _ -
```
and `-` shouldn't be the first character. If you want to be hypercorrect, stay case-insensitive and within the 8.3 naming convention (all the files and directories have to be unique within one directory if their names are lowercased and truncated to eight characters before the `.`, if any, and to three characters after the `.`, if any). (And do not use `.`s in directory names.)
###
System Interaction
Not all platforms provide a command line. These are usually platforms that rely primarily on a Graphical User Interface (GUI) for user interaction. A program requiring a command line interface might not work everywhere. This is probably for the user of the program to deal with, so don't stay up late worrying about it.
Some platforms can't delete or rename files held open by the system, this limitation may also apply to changing filesystem metainformation like file permissions or owners. Remember to [`close`](perlfunc#close-FILEHANDLE) files when you are done with them. Don't [`unlink`](perlfunc#unlink-LIST) or [`rename`](perlfunc#rename-OLDNAME%2CNEWNAME) an open file. Don't [`tie`](perlfunc#tie-VARIABLE%2CCLASSNAME%2CLIST) or [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) a file already tied or opened; [`untie`](perlfunc#untie-VARIABLE) or [`close`](perlfunc#close-FILEHANDLE) it first.
Don't open the same file more than once at a time for writing, as some operating systems put mandatory locks on such files.
Don't assume that write/modify permission on a directory gives the right to add or delete files/directories in that directory. That is filesystem specific: in some filesystems you need write/modify permission also (or even just) in the file/directory itself. In some filesystems (AFS, DFS) the permission to add/delete directory entries is a completely separate permission.
Don't assume that a single [`unlink`](perlfunc#unlink-LIST) completely gets rid of the file: some filesystems (most notably the ones in VMS) have versioned filesystems, and [`unlink`](perlfunc#unlink-LIST) removes only the most recent one (it doesn't remove all the versions because by default the native tools on those platforms remove just the most recent version, too). The portable idiom to remove all the versions of a file is
```
1 while unlink "file";
```
This will terminate if the file is undeletable for some reason (protected, not there, and so on).
Don't count on a specific environment variable existing in [`%ENV`](perlvar#%25ENV). Don't count on [`%ENV`](perlvar#%25ENV) entries being case-sensitive, or even case-preserving. Don't try to clear [`%ENV`](perlvar#%25ENV) by saying `%ENV = ();`, or, if you really have to, make it conditional on `$^O ne 'VMS'` since in VMS the [`%ENV`](perlvar#%25ENV) table is much more than a per-process key-value string table.
On VMS, some entries in the [`%ENV`](perlvar#%25ENV) hash are dynamically created when their key is used on a read if they did not previously exist. The values for `$ENV{HOME}`, `$ENV{TERM}`, `$ENV{PATH}`, and `$ENV{USER}`, are known to be dynamically generated. The specific names that are dynamically generated may vary with the version of the C library on VMS, and more may exist than are documented.
On VMS by default, changes to the [`%ENV`](perlvar#%25ENV) hash persist after perl exits. Subsequent invocations of perl in the same process can inadvertently inherit environment settings that were meant to be temporary.
Don't count on signals or [`%SIG`](perlvar#%25SIG) for anything.
Don't count on filename globbing. Use [`opendir`](perlfunc#opendir-DIRHANDLE%2CEXPR), [`readdir`](perlfunc#readdir-DIRHANDLE), and [`closedir`](perlfunc#closedir-DIRHANDLE) instead.
Don't count on per-program environment variables, or per-program current directories.
Don't count on specific values of [`$!`](perlvar#%24%21), neither numeric nor especially the string values. Users may switch their locales causing error messages to be translated into their languages. If you can trust a POSIXish environment, you can portably use the symbols defined by the [`Errno`](errno) module, like `ENOENT`. And don't trust on the values of [`$!`](perlvar#%24%21) at all except immediately after a failed system call.
###
Command names versus file pathnames
Don't assume that the name used to invoke a command or program with [`system`](perlfunc#system-LIST) or [`exec`](perlfunc#exec-LIST) can also be used to test for the existence of the file that holds the executable code for that command or program. First, many systems have "internal" commands that are built-in to the shell or OS and while these commands can be invoked, there is no corresponding file. Second, some operating systems (e.g., Cygwin, OS/2, and VOS) have required suffixes for executable files; these suffixes are generally permitted on the command name but are not required. Thus, a command like `perl` might exist in a file named *perl*, *perl.exe*, or *perl.pm*, depending on the operating system. The variable [`$Config{_exe}`](config#_exe) in the [`Config`](config) module holds the executable suffix, if any. Third, the VMS port carefully sets up [`$^X`](perlvar#%24%5EX) and [`$Config{perlpath}`](config#perlpath) so that no further processing is required. This is just as well, because the matching regular expression used below would then have to deal with a possible trailing version number in the VMS file name.
To convert [`$^X`](perlvar#%24%5EX) to a file pathname, taking account of the requirements of the various operating system possibilities, say:
```
use Config;
my $thisperl = $^X;
if ($^O ne 'VMS') {
$thisperl .= $Config{_exe}
unless $thisperl =~ m/\Q$Config{_exe}\E$/i;
}
```
To convert [`$Config{perlpath}`](config#perlpath) to a file pathname, say:
```
use Config;
my $thisperl = $Config{perlpath};
if ($^O ne 'VMS') {
$thisperl .= $Config{_exe}
unless $thisperl =~ m/\Q$Config{_exe}\E$/i;
}
```
### Networking
Don't assume that you can reach the public Internet.
Don't assume that there is only one way to get through firewalls to the public Internet.
Don't assume that you can reach outside world through any other port than 80, or some web proxy. ftp is blocked by many firewalls.
Don't assume that you can send email by connecting to the local SMTP port.
Don't assume that you can reach yourself or any node by the name 'localhost'. The same goes for '127.0.0.1'. You will have to try both.
Don't assume that the host has only one network card, or that it can't bind to many virtual IP addresses.
Don't assume a particular network device name.
Don't assume a particular set of [`ioctl`](perlfunc#ioctl-FILEHANDLE%2CFUNCTION%2CSCALAR)s will work.
Don't assume that you can ping hosts and get replies.
Don't assume that any particular port (service) will respond.
Don't assume that [`Sys::Hostname`](Sys::Hostname) (or any other API or command) returns either a fully qualified hostname or a non-qualified hostname: it all depends on how the system had been configured. Also remember that for things such as DHCP and NAT, the hostname you get back might not be very useful.
All the above *don't*s may look daunting, and they are, but the key is to degrade gracefully if one cannot reach the particular network service one wants. Croaking or hanging do not look very professional.
###
Interprocess Communication (IPC)
In general, don't directly access the system in code meant to be portable. That means, no [`system`](perlfunc#system-LIST), [`exec`](perlfunc#exec-LIST), [`fork`](perlfunc#fork), [`pipe`](perlfunc#pipe-READHANDLE%2CWRITEHANDLE), [```` or `qx//`](perlop#qx%2FSTRING%2F), [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) with a `|`, nor any of the other things that makes being a Perl hacker worth being.
Commands that launch external processes are generally supported on most platforms (though many of them do not support any type of forking). The problem with using them arises from what you invoke them on. External tools are often named differently on different platforms, may not be available in the same location, might accept different arguments, can behave differently, and often present their results in a platform-dependent way. Thus, you should seldom depend on them to produce consistent results. (Then again, if you're calling `netstat -a`, you probably don't expect it to run on both Unix and CP/M.)
One especially common bit of Perl code is opening a pipe to **sendmail**:
```
open(my $mail, '|-', '/usr/lib/sendmail -t')
or die "cannot fork sendmail: $!";
```
This is fine for systems programming when sendmail is known to be available. But it is not fine for many non-Unix systems, and even some Unix systems that may not have sendmail installed. If a portable solution is needed, see the various distributions on CPAN that deal with it. [`Mail::Mailer`](Mail::Mailer) and [`Mail::Send`](Mail::Send) in the `MailTools` distribution are commonly used, and provide several mailing methods, including `mail`, `sendmail`, and direct SMTP (via [`Net::SMTP`](Net::SMTP)) if a mail transfer agent is not available. [`Mail::Sendmail`](Mail::Sendmail) is a standalone module that provides simple, platform-independent mailing.
The Unix System V IPC (`msg*(), sem*(), shm*()`) is not available even on all Unix platforms.
Do not use either the bare result of `pack("N", 10, 20, 30, 40)` or bare v-strings (such as `v10.20.30.40`) to represent IPv4 addresses: both forms just pack the four bytes into network order. That this would be equal to the C language `in_addr` struct (which is what the socket code internally uses) is not guaranteed. To be portable use the routines of the [`Socket`](socket) module, such as [`inet_aton`](socket#%24ip_address-%3D-inet_aton-%24string), [`inet_ntoa`](socket#%24string-%3D-inet_ntoa-%24ip_address), and [`sockaddr_in`](socket#%24sockaddr-%3D-sockaddr_in-%24port%2C-%24ip_address).
The rule of thumb for portable code is: Do it all in portable Perl, or use a module (that may internally implement it with platform-specific code, but exposes a common interface).
###
External Subroutines (XS)
XS code can usually be made to work with any platform, but dependent libraries, header files, etc., might not be readily available or portable, or the XS code itself might be platform-specific, just as Perl code might be. If the libraries and headers are portable, then it is normally reasonable to make sure the XS code is portable, too.
A different type of portability issue arises when writing XS code: availability of a C compiler on the end-user's system. C brings with it its own portability issues, and writing XS code will expose you to some of those. Writing purely in Perl is an easier way to achieve portability.
###
Standard Modules
In general, the standard modules work across platforms. Notable exceptions are the [`CPAN`](cpan) module (which currently makes connections to external programs that may not be available), platform-specific modules (like [`ExtUtils::MM_VMS`](ExtUtils::MM_VMS)), and DBM modules.
There is no one DBM module available on all platforms. [`SDBM_File`](sdbm_file) and the others are generally available on all Unix and DOSish ports, but not in MacPerl, where only [`NDBM_File`](ndbm_file) and [`DB_File`](db_file) are available.
The good news is that at least some DBM module should be available, and [`AnyDBM_File`](anydbm_file) will use whichever module it can find. Of course, then the code needs to be fairly strict, dropping to the greatest common factor (e.g., not exceeding 1K for each record), so that it will work with any DBM module. See [AnyDBM\_File](anydbm_file) for more details.
###
Time and Date
The system's notion of time of day and calendar date is controlled in widely different ways. Don't assume the timezone is stored in `$ENV{TZ}`, and even if it is, don't assume that you can control the timezone through that variable. Don't assume anything about the three-letter timezone abbreviations (for example that MST would be the Mountain Standard Time, it's been known to stand for Moscow Standard Time). If you need to use timezones, express them in some unambiguous format like the exact number of minutes offset from UTC, or the POSIX timezone format.
Don't assume that the epoch starts at 00:00:00, January 1, 1970, because that is OS- and implementation-specific. It is better to store a date in an unambiguous representation. The ISO 8601 standard defines YYYY-MM-DD as the date format, or YYYY-MM-DDTHH:MM:SS (that's a literal "T" separating the date from the time). Please do use the ISO 8601 instead of making us guess what date 02/03/04 might be. ISO 8601 even sorts nicely as-is. A text representation (like "1987-12-18") can be easily converted into an OS-specific value using a module like [`Time::Piece`](Time::Piece) (see ["Date Parsing" in Time::Piece](Time::Piece#Date-Parsing)) or [`Date::Parse`](Date::Parse). An array of values, such as those returned by [`localtime`](perlfunc#localtime-EXPR), can be converted to an OS-specific representation using [`Time::Local`](Time::Local).
When calculating specific times, such as for tests in time or date modules, it may be appropriate to calculate an offset for the epoch.
```
use Time::Local qw(timegm);
my $offset = timegm(0, 0, 0, 1, 0, 1970);
```
The value for `$offset` in Unix will be `0`, but in Mac OS Classic will be some large number. `$offset` can then be added to a Unix time value to get what should be the proper value on any system.
###
Character sets and character encoding
Assume very little about character sets.
Assume nothing about numerical values ([`ord`](perlfunc#ord-EXPR), [`chr`](perlfunc#chr-NUMBER)) of characters. Do not use explicit code point ranges (like `\xHH-\xHH)`. However, starting in Perl v5.22, regular expression pattern bracketed character class ranges specified like `qr/[\N{U+HH}-\N{U+HH}]/` are portable, and starting in Perl v5.24, the same ranges are portable in [`tr///`](perlop#tr%2FSEARCHLIST%2FREPLACEMENTLIST%2Fcdsr). You can portably use symbolic character classes like `[:print:]`.
Do not assume that the alphabetic characters are encoded contiguously (in the numeric sense). There may be gaps. Special coding in Perl, however, guarantees that all subsets of `qr/[A-Z]/`, `qr/[a-z]/`, and `qr/[0-9]/` behave as expected. [`tr///`](perlop#tr%2FSEARCHLIST%2FREPLACEMENTLIST%2Fcdsr) behaves the same for these ranges. In patterns, any ranges specified with end points using the `\N{...}` notations ensures character set portability, but it is a bug in Perl v5.22 that this isn't true of [`tr///`](perlop#tr%2FSEARCHLIST%2FREPLACEMENTLIST%2Fcdsr), fixed in v5.24.
Do not assume anything about the ordering of the characters. The lowercase letters may come before or after the uppercase letters; the lowercase and uppercase may be interlaced so that both "a" and "A" come before "b"; the accented and other international characters may be interlaced so that ä comes before "b". <Unicode::Collate> can be used to sort this all out.
### Internationalisation
If you may assume POSIX (a rather large assumption), you may read more about the POSIX locale system from <perllocale>. The locale system at least attempts to make things a little bit more portable, or at least more convenient and native-friendly for non-English users. The system affects character sets and encoding, and date and time formatting--amongst other things.
If you really want to be international, you should consider Unicode. See <perluniintro> and <perlunicode> for more information.
By default Perl assumes your source code is written in an 8-bit ASCII superset. To embed Unicode characters in your strings and regexes, you can use the [`\x{HH}` or (more portably) `\N{U+HH}` notations](perlop#Quote-and-Quote-like-Operators). You can also use the [`utf8`](utf8) pragma and write your code in UTF-8, which lets you use Unicode characters directly (not just in quoted constructs but also in identifiers).
###
System Resources
If your code is destined for systems with severely constrained (or missing!) virtual memory systems then you want to be *especially* mindful of avoiding wasteful constructs such as:
```
my @lines = <$very_large_file>; # bad
while (<$fh>) {$file .= $_} # sometimes bad
my $file = join('', <$fh>); # better
```
The last two constructs may appear unintuitive to most people. The first repeatedly grows a string, whereas the second allocates a large chunk of memory in one go. On some systems, the second is more efficient than the first.
### Security
Most multi-user platforms provide basic levels of security, usually implemented at the filesystem level. Some, however, unfortunately do not. Thus the notion of user id, or "home" directory, or even the state of being logged-in, may be unrecognizable on many platforms. If you write programs that are security-conscious, it is usually best to know what type of system you will be running under so that you can write code explicitly for that platform (or class of platforms).
Don't assume the Unix filesystem access semantics: the operating system or the filesystem may be using some ACL systems, which are richer languages than the usual `rwx`. Even if the `rwx` exist, their semantics might be different.
(From the security viewpoint, testing for permissions before attempting to do something is silly anyway: if one tries this, there is potential for race conditions. Someone or something might change the permissions between the permissions check and the actual operation. Just try the operation.)
Don't assume the Unix user and group semantics: especially, don't expect [`$<`](perlvar#%24%3C) and [`$>`](perlvar#%24%3E) (or [`$(`](perlvar#%24%28) and [`$)`](perlvar#%24%29)) to work for switching identities (or memberships).
Don't assume set-uid and set-gid semantics. (And even if you do, think twice: set-uid and set-gid are a known can of security worms.)
### Style
For those times when it is necessary to have platform-specific code, consider keeping the platform-specific code in one place, making porting to other platforms easier. Use the [`Config`](config) module and the special variable [`$^O`](perlvar#%24%5EO) to differentiate platforms, as described in ["PLATFORMS"](#PLATFORMS).
Beware of the "else syndrome":
```
if ($^O eq 'MSWin32') {
# code that assumes Windows
} else {
# code that assumes Linux
}
```
The `else` branch should be used for the really ultimate fallback, not for code specific to some platform.
Be careful in the tests you supply with your module or programs. Module code may be fully portable, but its tests might not be. This often happens when tests spawn off other processes or call external programs to aid in the testing, or when (as noted above) the tests assume certain things about the filesystem and paths. Be careful not to depend on a specific output style for errors, such as when checking [`$!`](perlvar#%24%21) after a failed system call. Using [`$!`](perlvar#%24%21) for anything else than displaying it as output is doubtful (though see the [`Errno`](errno) module for testing reasonably portably for error value). Some platforms expect a certain output format, and Perl on those platforms may have been adjusted accordingly. Most specifically, don't anchor a regex when testing an error value.
CPAN Testers
-------------
Modules uploaded to CPAN are tested by a variety of volunteers on different platforms. These CPAN testers are notified by mail of each new upload, and reply to the list with PASS, FAIL, NA (not applicable to this platform), or UNKNOWN (unknown), along with any relevant notations.
The purpose of the testing is twofold: one, to help developers fix any problems in their code that crop up because of lack of testing on other platforms; two, to provide users with information about whether a given module works on a given platform.
Also see:
* Mailing list: [email protected]
* Testing results: <https://www.cpantesters.org/>
PLATFORMS
---------
Perl is built with a [`$^O`](perlvar#%24%5EO) variable that indicates the operating system it was built on. This was implemented to help speed up code that would otherwise have to `use Config` and use the value of [`$Config{osname}`](config#osname). Of course, to get more detailed information about the system, looking into [`%Config`](config#DESCRIPTION) is certainly recommended.
[`%Config`](config#DESCRIPTION) cannot always be trusted, however, because it was built at compile time. If perl was built in one place, then transferred elsewhere, some values may be wrong. The values may even have been edited after the fact.
### Unix
Perl works on a bewildering variety of Unix and Unix-like platforms (see e.g. most of the files in the *hints/* directory in the source code kit). On most of these systems, the value of [`$^O`](perlvar#%24%5EO) (hence [`$Config{osname}`](config#osname), too) is determined either by lowercasing and stripping punctuation from the first field of the string returned by typing `uname -a` (or a similar command) at the shell prompt or by testing the file system for the presence of uniquely named files such as a kernel or header file. Here, for example, are a few of the more popular Unix flavors:
```
uname $^O $Config{archname}
--------------------------------------------
AIX aix aix
BSD/OS bsdos i386-bsdos
Darwin darwin darwin
DYNIX/ptx dynixptx i386-dynixptx
FreeBSD freebsd freebsd-i386
Haiku haiku BePC-haiku
Linux linux arm-linux
Linux linux armv5tel-linux
Linux linux i386-linux
Linux linux i586-linux
Linux linux ppc-linux
HP-UX hpux PA-RISC1.1
IRIX irix irix
Mac OS X darwin darwin
NeXT 3 next next-fat
NeXT 4 next OPENSTEP-Mach
openbsd openbsd i386-openbsd
OSF1 dec_osf alpha-dec_osf
reliantunix-n svr4 RM400-svr4
SCO_SV sco_sv i386-sco_sv
SINIX-N svr4 RM400-svr4
sn4609 unicos CRAY_C90-unicos
sn6521 unicosmk t3e-unicosmk
sn9617 unicos CRAY_J90-unicos
SunOS solaris sun4-solaris
SunOS solaris i86pc-solaris
SunOS4 sunos sun4-sunos
```
Because the value of [`$Config{archname}`](config#archname) may depend on the hardware architecture, it can vary more than the value of [`$^O`](perlvar#%24%5EO).
###
DOS and Derivatives
Perl has long been ported to Intel-style microcomputers running under systems like PC-DOS, MS-DOS, OS/2, and most Windows platforms you can bring yourself to mention (except for Windows CE, if you count that). Users familiar with *COMMAND.COM* or *CMD.EXE* style shells should be aware that each of these file specifications may have subtle differences:
```
my $filespec0 = "c:/foo/bar/file.txt";
my $filespec1 = "c:\\foo\\bar\\file.txt";
my $filespec2 = 'c:\foo\bar\file.txt';
my $filespec3 = 'c:\\foo\\bar\\file.txt';
```
System calls accept either `/` or `\` as the path separator. However, many command-line utilities of DOS vintage treat `/` as the option prefix, so may get confused by filenames containing `/`. Aside from calling any external programs, `/` will work just fine, and probably better, as it is more consistent with popular usage, and avoids the problem of remembering what to backwhack and what not to.
The DOS FAT filesystem can accommodate only "8.3" style filenames. Under the "case-insensitive, but case-preserving" HPFS (OS/2) and NTFS (NT) filesystems you may have to be careful about case returned with functions like [`readdir`](perlfunc#readdir-DIRHANDLE) or used with functions like [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) or [`opendir`](perlfunc#opendir-DIRHANDLE%2CEXPR).
DOS also treats several filenames as special, such as *AUX*, *PRN*, *NUL*, *CON*, *COM1*, *LPT1*, *LPT2*, etc. Unfortunately, sometimes these filenames won't even work if you include an explicit directory prefix. It is best to avoid such filenames, if you want your code to be portable to DOS and its derivatives. It's hard to know what these all are, unfortunately.
Users of these operating systems may also wish to make use of scripts such as *pl2bat.bat* to put wrappers around your scripts.
Newline (`\n`) is translated as `\015\012` by the I/O system when reading from and writing to files (see ["Newlines"](#Newlines)). `binmode($filehandle)` will keep `\n` translated as `\012` for that filehandle. [`binmode`](perlfunc#binmode-FILEHANDLE) should always be used for code that deals with binary data. That's assuming you realize in advance that your data is in binary. General-purpose programs should often assume nothing about their data.
The [`$^O`](perlvar#%24%5EO) variable and the [`$Config{archname}`](config#archname) values for various DOSish perls are as follows:
```
OS $^O $Config{archname} ID Version
---------------------------------------------------------
MS-DOS dos ?
PC-DOS dos ?
OS/2 os2 ?
Windows 3.1 ? ? 0 3 01
Windows 95 MSWin32 MSWin32-x86 1 4 00
Windows 98 MSWin32 MSWin32-x86 1 4 10
Windows ME MSWin32 MSWin32-x86 1 ?
Windows NT MSWin32 MSWin32-x86 2 4 xx
Windows NT MSWin32 MSWin32-ALPHA 2 4 xx
Windows NT MSWin32 MSWin32-ppc 2 4 xx
Windows 2000 MSWin32 MSWin32-x86 2 5 00
Windows XP MSWin32 MSWin32-x86 2 5 01
Windows 2003 MSWin32 MSWin32-x86 2 5 02
Windows Vista MSWin32 MSWin32-x86 2 6 00
Windows 7 MSWin32 MSWin32-x86 2 6 01
Windows 7 MSWin32 MSWin32-x64 2 6 01
Windows 2008 MSWin32 MSWin32-x86 2 6 01
Windows 2008 MSWin32 MSWin32-x64 2 6 01
Windows CE MSWin32 ? 3
Cygwin cygwin cygwin
```
The various MSWin32 Perl's can distinguish the OS they are running on via the value of the fifth element of the list returned from [`Win32::GetOSVersion()`](win32#Win32%3A%3AGetOSVersion%28%29). For example:
```
if ($^O eq 'MSWin32') {
my @os_version_info = Win32::GetOSVersion();
print +('3.1','95','NT')[$os_version_info[4]],"\n";
}
```
There are also `Win32::IsWinNT()|Win32/Win32::IsWinNT()`, `Win32::IsWin95()|Win32/Win32::IsWin95()`, and [`Win32::GetOSName()`](win32#Win32%3A%3AGetOSName%28%29); try [`perldoc Win32`](win32). The very portable [`POSIX::uname()`](posix#uname) will work too:
```
c:\> perl -MPOSIX -we "print join '|', uname"
Windows NT|moonru|5.0|Build 2195 (Service Pack 2)|x86
```
Errors set by Winsock functions are now put directly into `$^E`, and the relevant `WSAE*` error codes are now exported from the [Errno](errno) and [POSIX](posix) modules for testing this against.
The previous behavior of putting the errors (converted to POSIX-style `E*` error codes since Perl 5.20.0) into `$!` was buggy due to the non-equivalence of like-named Winsock and POSIX error constants, a relationship between which has unfortunately been established in one way or another since Perl 5.8.0.
The new behavior provides a much more robust solution for checking Winsock errors in portable software without accidentally matching POSIX tests that were intended for other OSes and may have different meanings for Winsock.
The old behavior is currently retained, warts and all, for backwards compatibility, but users are encouraged to change any code that tests `$!` against `E*` constants for Winsock errors to instead test `$^E` against `WSAE*` constants. After a suitable deprecation period, which started with Perl 5.24, the old behavior may be removed, leaving `$!` unchanged after Winsock function calls, to avoid any possible confusion over which error variable to check.
Also see:
* The EMX environment for DOS, OS/2, etc. [email protected], <ftp://hobbes.nmsu.edu/pub/os2/dev/emx/> Also <perlos2>.
* Build instructions for Win32 in <perlwin32>, or under the Cygnus environment in <perlcygwin>.
* The `Win32::*` modules in [Win32](win32).
* The ActiveState Pages, <https://www.activestate.com/>
* The Cygwin environment for Win32; *README.cygwin* (installed as <perlcygwin>), <https://www.cygwin.com/>
* Build instructions for OS/2, <perlos2>
### VMS
Perl on VMS is discussed in <perlvms> in the Perl distribution.
The official name of VMS as of this writing is OpenVMS.
Interacting with Perl from the Digital Command Language (DCL) shell often requires a different set of quotation marks than Unix shells do. For example:
```
$ perl -e "print ""Hello, world.\n"""
Hello, world.
```
There are several ways to wrap your Perl scripts in DCL *.COM* files, if you are so inclined. For example:
```
$ write sys$output "Hello from DCL!"
$ if p1 .eqs. ""
$ then perl -x 'f$environment("PROCEDURE")
$ else perl -x - 'p1 'p2 'p3 'p4 'p5 'p6 'p7 'p8
$ deck/dollars="__END__"
#!/usr/bin/perl
print "Hello from Perl!\n";
__END__
$ endif
```
Do take care with `$ ASSIGN/nolog/user SYS$COMMAND: SYS$INPUT` if your Perl-in-DCL script expects to do things like `$read = <STDIN>;`.
The VMS operating system has two filesystems, designated by their on-disk structure (ODS) level: ODS-2 and its successor ODS-5. The initial port of Perl to VMS pre-dates ODS-5, but all current testing and development assumes ODS-5 and its capabilities, including case preservation, extended characters in filespecs, and names up to 8192 bytes long.
Perl on VMS can accept either VMS- or Unix-style file specifications as in either of the following:
```
$ perl -ne "print if /perl_setup/i" SYS$LOGIN:LOGIN.COM
$ perl -ne "print if /perl_setup/i" /sys$login/login.com
```
but not a mixture of both as in:
```
$ perl -ne "print if /perl_setup/i" sys$login:/login.com
Can't open sys$login:/login.com: file specification syntax error
```
In general, the easiest path to portability is always to specify filenames in Unix format unless they will need to be processed by native commands or utilities. Because of this latter consideration, the <File::Spec> module by default returns native format specifications regardless of input format. This default may be reversed so that filenames are always reported in Unix format by specifying the `DECC$FILENAME_UNIX_REPORT` feature logical in the environment.
The file type, or extension, is always present in a VMS-format file specification even if it's zero-length. This means that, by default, [`readdir`](perlfunc#readdir-DIRHANDLE) will return a trailing dot on a file with no extension, so where you would see `"a"` on Unix you'll see `"a."` on VMS. However, the trailing dot may be suppressed by enabling the `DECC$READDIR_DROPDOTNOTYPE` feature in the environment (see the CRTL documentation on feature logical names).
What `\n` represents depends on the type of file opened. It usually represents `\012` but it could also be `\015`, `\012`, `\015\012`, `\000`, `\040`, or nothing depending on the file organization and record format. The [`VMS::Stdio`](VMS::Stdio) module provides access to the special `fopen()` requirements of files with unusual attributes on VMS.
The value of [`$^O`](perlvar#%24%5EO) on OpenVMS is "VMS". To determine the architecture that you are running on refer to [`$Config{archname}`](config#archname).
On VMS, perl determines the UTC offset from the `SYS$TIMEZONE_DIFFERENTIAL` logical name. Although the VMS epoch began at 17-NOV-1858 00:00:00.00, calls to [`localtime`](perlfunc#localtime-EXPR) are adjusted to count offsets from 01-JAN-1970 00:00:00.00, just like Unix.
Also see:
* *README.vms* (installed as *README\_vms*), <perlvms>
* vmsperl list, [email protected]
* vmsperl on the web, <http://www.sidhe.org/vmsperl/index.html>
* VMS Software Inc. web site, <http://www.vmssoftware.com>
### VOS
Perl on VOS (also known as OpenVOS) is discussed in *README.vos* in the Perl distribution (installed as <perlvos>). Perl on VOS can accept either VOS- or Unix-style file specifications as in either of the following:
```
$ perl -ne "print if /perl_setup/i" >system>notices
$ perl -ne "print if /perl_setup/i" /system/notices
```
or even a mixture of both as in:
```
$ perl -ne "print if /perl_setup/i" >system/notices
```
Even though VOS allows the slash character to appear in object names, because the VOS port of Perl interprets it as a pathname delimiting character, VOS files, directories, or links whose names contain a slash character cannot be processed. Such files must be renamed before they can be processed by Perl.
Older releases of VOS (prior to OpenVOS Release 17.0) limit file names to 32 or fewer characters, prohibit file names from starting with a `-` character, and prohibit file names from containing (space) or any character from the set `!#%&'()*;<=>?`.
Newer releases of VOS (OpenVOS Release 17.0 or later) support a feature known as extended names. On these releases, file names can contain up to 255 characters, are prohibited from starting with a `-` character, and the set of prohibited characters is reduced to `#%*<>?`. There are restrictions involving spaces and apostrophes: these characters must not begin or end a name, nor can they immediately precede or follow a period. Additionally, a space must not immediately precede another space or hyphen. Specifically, the following character combinations are prohibited: space-space, space-hyphen, period-space, space-period, period-apostrophe, apostrophe-period, leading or trailing space, and leading or trailing apostrophe. Although an extended file name is limited to 255 characters, a path name is still limited to 256 characters.
The value of [`$^O`](perlvar#%24%5EO) on VOS is "vos". To determine the architecture that you are running on refer to [`$Config{archname}`](config#archname).
Also see:
* *README.vos* (installed as <perlvos>)
* The VOS mailing list.
There is no specific mailing list for Perl on VOS. You can contact the Stratus Technologies Customer Assistance Center (CAC) for your region, or you can use the contact information located in the distribution files on the Stratus Anonymous FTP site.
* Stratus Technologies on the web at <http://www.stratus.com>
* VOS Open-Source Software on the web at <http://ftp.stratus.com/pub/vos/vos.html>
###
EBCDIC Platforms
v5.22 core Perl runs on z/OS (formerly OS/390). Theoretically it could run on the successors of OS/400 on AS/400 minicomputers as well as VM/ESA, and BS2000 for S/390 Mainframes. Such computers use EBCDIC character sets internally (usually Character Code Set ID 0037 for OS/400 and either 1047 or POSIX-BC for S/390 systems).
The rest of this section may need updating, but we don't know what it should say. Please submit comments to <https://github.com/Perl/perl5/issues>.
On the mainframe Perl currently works under the "Unix system services for OS/390" (formerly known as OpenEdition), VM/ESA OpenEdition, or the BS200 POSIX-BC system (BS2000 is supported in Perl 5.6 and greater). See <perlos390> for details. Note that for OS/400 there is also a port of Perl 5.8.1/5.10.0 or later to the PASE which is ASCII-based (as opposed to ILE which is EBCDIC-based), see <perlos400>.
As of R2.5 of USS for OS/390 and Version 2.3 of VM/ESA these Unix sub-systems do not support the `#!` shebang trick for script invocation. Hence, on OS/390 and VM/ESA Perl scripts can be executed with a header similar to the following simple script:
```
: # use perl
eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
if 0;
#!/usr/local/bin/perl # just a comment really
print "Hello from perl!\n";
```
OS/390 will support the `#!` shebang trick in release 2.8 and beyond. Calls to [`system`](perlfunc#system-LIST) and backticks can use POSIX shell syntax on all S/390 systems.
On the AS/400, if PERL5 is in your library list, you may need to wrap your Perl scripts in a CL procedure to invoke them like so:
```
BEGIN
CALL PGM(PERL5/PERL) PARM('/QOpenSys/hello.pl')
ENDPGM
```
This will invoke the Perl script *hello.pl* in the root of the QOpenSys file system. On the AS/400 calls to [`system`](perlfunc#system-LIST) or backticks must use CL syntax.
On these platforms, bear in mind that the EBCDIC character set may have an effect on what happens with some Perl functions (such as [`chr`](perlfunc#chr-NUMBER), [`pack`](perlfunc#pack-TEMPLATE%2CLIST), [`print`](perlfunc#print-FILEHANDLE-LIST), [`printf`](perlfunc#printf-FILEHANDLE-FORMAT%2C-LIST), [`ord`](perlfunc#ord-EXPR), [`sort`](perlfunc#sort-SUBNAME-LIST), [`sprintf`](perlfunc#sprintf-FORMAT%2C-LIST), [`unpack`](perlfunc#unpack-TEMPLATE%2CEXPR)), as well as bit-fiddling with ASCII constants using operators like [`^`, `&` and `|`](perlop#Bitwise-String-Operators), not to mention dealing with socket interfaces to ASCII computers (see ["Newlines"](#Newlines)).
Fortunately, most web servers for the mainframe will correctly translate the `\n` in the following statement to its ASCII equivalent (`\r` is the same under both Unix and z/OS):
```
print "Content-type: text/html\r\n\r\n";
```
The values of [`$^O`](perlvar#%24%5EO) on some of these platforms include:
```
uname $^O $Config{archname}
--------------------------------------------
OS/390 os390 os390
OS400 os400 os400
POSIX-BC posix-bc BS2000-posix-bc
```
Some simple tricks for determining if you are running on an EBCDIC platform could include any of the following (perhaps all):
```
if ("\t" eq "\005") { print "EBCDIC may be spoken here!\n"; }
if (ord('A') == 193) { print "EBCDIC may be spoken here!\n"; }
if (chr(169) eq 'z') { print "EBCDIC may be spoken here!\n"; }
```
One thing you may not want to rely on is the EBCDIC encoding of punctuation characters since these may differ from code page to code page (and once your module or script is rumoured to work with EBCDIC, folks will want it to work with all EBCDIC character sets).
Also see:
* <perlos390>, <perlos400>, <perlbs2000>, <perlebcdic>.
* The [email protected] list is for discussion of porting issues as well as general usage issues for all EBCDIC Perls. Send a message body of "subscribe perl-mvs" to [email protected].
* AS/400 Perl information at <http://as400.rochester.ibm.com/> as well as on CPAN in the *ports/* directory.
###
Acorn RISC OS
Because Acorns use ASCII with newlines (`\n`) in text files as `\012` like Unix, and because Unix filename emulation is turned on by default, most simple scripts will probably work "out of the box". The native filesystem is modular, and individual filesystems are free to be case-sensitive or insensitive, and are usually case-preserving. Some native filesystems have name length limits, which file and directory names are silently truncated to fit. Scripts should be aware that the standard filesystem currently has a name length limit of **10** characters, with up to 77 items in a directory, but other filesystems may not impose such limitations.
Native filenames are of the form
```
Filesystem#Special_Field::DiskName.$.Directory.Directory.File
```
where
```
Special_Field is not usually present, but may contain . and $ .
Filesystem =~ m|[A-Za-z0-9_]|
DsicName =~ m|[A-Za-z0-9_/]|
$ represents the root directory
. is the path separator
@ is the current directory (per filesystem but machine global)
^ is the parent directory
Directory and File =~ m|[^\0- "\.\$\%\&:\@\\^\|\177]+|
```
The default filename translation is roughly `tr|/.|./|`, swapping dots and slashes.
Note that `"ADFS::HardDisk.$.File" ne 'ADFS::HardDisk.$.File'` and that the second stage of `$` interpolation in regular expressions will fall foul of the [`$.`](perlvar#%24.) variable if scripts are not careful.
Logical paths specified by system variables containing comma-separated search lists are also allowed; hence `System:Modules` is a valid filename, and the filesystem will prefix `Modules` with each section of `System$Path` until a name is made that points to an object on disk. Writing to a new file `System:Modules` would be allowed only if `System$Path` contains a single item list. The filesystem will also expand system variables in filenames if enclosed in angle brackets, so `<System$Dir>.Modules` would look for the file `$ENV{'System$Dir'} . 'Modules'`. The obvious implication of this is that **fully qualified filenames can start with `<>`** and the three-argument form of [`open`](perlfunc#open-FILEHANDLE%2CMODE%2CEXPR) should always be used.
Because `.` was in use as a directory separator and filenames could not be assumed to be unique after 10 characters, Acorn implemented the C compiler to strip the trailing `.c` `.h` `.s` and `.o` suffix from filenames specified in source code and store the respective files in subdirectories named after the suffix. Hence files are translated:
```
foo.h h.foo
C:foo.h C:h.foo (logical path variable)
sys/os.h sys.h.os (C compiler groks Unix-speak)
10charname.c c.10charname
10charname.o o.10charname
11charname_.c c.11charname (assuming filesystem truncates at 10)
```
The Unix emulation library's translation of filenames to native assumes that this sort of translation is required, and it allows a user-defined list of known suffixes that it will transpose in this fashion. This may seem transparent, but consider that with these rules *foo/bar/baz.h* and *foo/bar/h/baz* both map to *foo.bar.h.baz*, and that [`readdir`](perlfunc#readdir-DIRHANDLE) and [`glob`](perlfunc#glob-EXPR) cannot and do not attempt to emulate the reverse mapping. Other `.`'s in filenames are translated to `/`.
As implied above, the environment accessed through [`%ENV`](perlvar#%25ENV) is global, and the convention is that program specific environment variables are of the form `Program$Name`. Each filesystem maintains a current directory, and the current filesystem's current directory is the **global** current directory. Consequently, sociable programs don't change the current directory but rely on full pathnames, and programs (and Makefiles) cannot assume that they can spawn a child process which can change the current directory without affecting its parent (and everyone else for that matter).
Because native operating system filehandles are global and are currently allocated down from 255, with 0 being a reserved value, the Unix emulation library emulates Unix filehandles. Consequently, you can't rely on passing `STDIN`, `STDOUT`, or `STDERR` to your children.
The desire of users to express filenames of the form `<Foo$Dir>.Bar` on the command line unquoted causes problems, too: [````](perlop#qx%2FSTRING%2F) command output capture has to perform a guessing game. It assumes that a string `<[^<>]+\$[^<>]>` is a reference to an environment variable, whereas anything else involving `<` or `>` is redirection, and generally manages to be 99% right. Of course, the problem remains that scripts cannot rely on any Unix tools being available, or that any tools found have Unix-like command line arguments.
Extensions and XS are, in theory, buildable by anyone using free tools. In practice, many don't, as users of the Acorn platform are used to binary distributions. MakeMaker does run, but no available make currently copes with MakeMaker's makefiles; even if and when this should be fixed, the lack of a Unix-like shell will cause problems with makefile rules, especially lines of the form `cd sdbm && make all`, and anything using quoting.
"RISC OS" is the proper name for the operating system, but the value in [`$^O`](perlvar#%24%5EO) is "riscos" (because we don't like shouting).
###
Other perls
Perl has been ported to many platforms that do not fit into any of the categories listed above. Some, such as AmigaOS, QNX, Plan 9, and VOS, have been well-integrated into the standard Perl source code kit. You may need to see the *ports/* directory on CPAN for information, and possibly binaries, for the likes of: aos, Atari ST, lynxos, riscos, Novell Netware, Tandem Guardian, *etc.* (Yes, we know that some of these OSes may fall under the Unix category, but we are not a standards body.)
Some approximate operating system names and their [`$^O`](perlvar#%24%5EO) values in the "OTHER" category include:
```
OS $^O $Config{archname}
------------------------------------------
Amiga DOS amigaos m68k-amigos
```
See also:
* Amiga, *README.amiga* (installed as <perlamiga>).
* Plan 9, *README.plan9*
FUNCTION IMPLEMENTATIONS
-------------------------
Listed below are functions that are either completely unimplemented or else have been implemented differently on various platforms. Preceding each description will be, in parentheses, a list of platforms that the description applies to.
The list may well be incomplete, or even wrong in some places. When in doubt, consult the platform-specific README files in the Perl source distribution, and any other documentation resources accompanying a given port.
Be aware, moreover, that even among Unix-ish systems there are variations.
For many functions, you can also query [`%Config`](config#DESCRIPTION), exported by default from the [`Config`](config) module. For example, to check whether the platform has the [`lstat`](perlfunc#lstat-FILEHANDLE) call, check [`$Config{d_lstat}`](config#d_lstat). See [Config](config) for a full description of available variables.
###
Alphabetical Listing of Perl Functions
-X (Win32) `-w` only inspects the read-only file attribute (FILE\_ATTRIBUTE\_READONLY), which determines whether the directory can be deleted, not whether it can be written to. Directories always have read and write access unless denied by discretionary access control lists (DACLs).
(VMS) `-r`, `-w`, `-x`, and `-o` tell whether the file is accessible, which may not reflect UIC-based file protections.
(RISC OS) `-s` by name on an open file will return the space reserved on disk, rather than the current extent. `-s` on an open filehandle returns the current size.
(Win32, VMS, RISC OS) `-R`, `-W`, `-X`, `-O` are indistinguishable from `-r`, `-w`, `-x`, `-o`.
(Win32, VMS, RISC OS) `-g`, `-k`, `-l`, `-u`, `-A` are not particularly meaningful.
(Win32) `-l` returns true for both symlinks and directory junctions.
(VMS, RISC OS) `-p` is not particularly meaningful.
(VMS) `-d` is true if passed a device spec without an explicit directory.
(Win32) `-x` (or `-X`) determine if a file ends in one of the executable suffixes. `-S` is meaningless.
(RISC OS) `-x` (or `-X`) determine if a file has an executable file type.
alarm (Win32) Emulated using timers that must be explicitly polled whenever Perl wants to dispatch "safe signals" and therefore cannot interrupt blocking system calls.
atan2 (Tru64, HP-UX 10.20) Due to issues with various CPUs, math libraries, compilers, and standards, results for `atan2` may vary depending on any combination of the above. Perl attempts to conform to the Open Group/IEEE standards for the results returned from `atan2`, but cannot force the issue if the system Perl is run on does not allow it.
The current version of the standards for `atan2` is available at <http://www.opengroup.org/onlinepubs/009695399/functions/atan2.html>.
binmode (RISC OS) Meaningless.
(VMS) Reopens file and restores pointer; if function fails, underlying filehandle may be closed, or pointer may be in a different position.
(Win32) The value returned by [`tell`](perlfunc#tell-FILEHANDLE) may be affected after the call, and the filehandle may be flushed.
chdir (Win32) The current directory reported by the system may include any symbolic links specified to chdir().
chmod (Win32) Only good for changing "owner" read-write access; "group" and "other" bits are meaningless.
(RISC OS) Only good for changing "owner" and "other" read-write access.
(VOS) Access permissions are mapped onto VOS access-control list changes.
(Cygwin) The actual permissions set depend on the value of the `CYGWIN` variable in the SYSTEM environment settings.
(Android) Setting the exec bit on some locations (generally */sdcard*) will return true but not actually set the bit.
(VMS) A mode argument of zero sets permissions to the user's default permission mask rather than disabling all permissions.
chown (Plan 9, RISC OS) Not implemented.
(Win32) Does nothing, but won't fail.
(VOS) A little funky, because VOS's notion of ownership is a little funky.
chroot (Win32, VMS, Plan 9, RISC OS, VOS) Not implemented.
crypt (Win32) May not be available if library or source was not provided when building perl.
(Android) Not implemented.
dbmclose (VMS, Plan 9, VOS) Not implemented.
dbmopen (VMS, Plan 9, VOS) Not implemented.
dump (RISC OS) Not useful.
(Cygwin, Win32) Not supported.
(VMS) Invokes VMS debugger.
exec (Win32) `exec LIST` without the use of indirect object syntax (`exec PROGRAM LIST`) may fall back to trying the shell if the first `spawn()` fails.
Note that the list form of exec() is emulated since the Win32 API CreateProcess() accepts a simple string rather than an array of command-line arguments. This may have security implications for your code.
(SunOS, Solaris, HP-UX) Does not automatically flush output handles on some platforms.
exit (VMS) Emulates Unix `exit` (which considers `exit 1` to indicate an error) by mapping the `1` to `SS$_ABORT` (`44`). This behavior may be overridden with the pragma [`use vmsish 'exit'`](vmsish#vmsish-exit). As with the CRTL's `exit()` function, `exit 0` is also mapped to an exit status of `SS$_NORMAL` (`1`); this mapping cannot be overridden. Any other argument to `exit` is used directly as Perl's exit status. On VMS, unless the future POSIX\_EXIT mode is enabled, the exit code should always be a valid VMS exit code and not a generic number. When the POSIX\_EXIT mode is enabled, a generic number will be encoded in a method compatible with the C library \_POSIX\_EXIT macro so that it can be decoded by other programs, particularly ones written in C, like the GNV package.
(Solaris) `exit` resets file pointers, which is a problem when called from a child process (created by [`fork`](perlfunc#fork)) in [`BEGIN`](perlmod#BEGIN%2C-UNITCHECK%2C-CHECK%2C-INIT-and-END). A workaround is to use [`POSIX::_exit`](posix#_exit).
```
exit unless $Config{archname} =~ /\bsolaris\b/;
require POSIX;
POSIX::_exit(0);
```
fcntl (Win32) Not implemented.
(VMS) Some functions available based on the version of VMS.
flock (VMS, RISC OS, VOS) Not implemented.
fork (AmigaOS, RISC OS, VMS) Not implemented.
(Win32) Emulated using multiple interpreters. See <perlfork>.
(SunOS, Solaris, HP-UX) Does not automatically flush output handles on some platforms.
getlogin (RISC OS) Not implemented.
getpgrp (Win32, VMS, RISC OS) Not implemented.
getppid (Win32, RISC OS) Not implemented.
getpriority (Win32, VMS, RISC OS, VOS) Not implemented.
getpwnam (Win32) Not implemented.
(RISC OS) Not useful.
getgrnam (Win32, VMS, RISC OS) Not implemented.
getnetbyname (Android, Win32, Plan 9) Not implemented.
getpwuid (Win32) Not implemented.
(RISC OS) Not useful.
getgrgid (Win32, VMS, RISC OS) Not implemented.
getnetbyaddr (Android, Win32, Plan 9) Not implemented.
getprotobynumber (Android) Not implemented.
getpwent (Android, Win32) Not implemented.
getgrent (Android, Win32, VMS) Not implemented.
gethostbyname (Irix 5) `gethostbyname('localhost')` does not work everywhere: you may have to use `gethostbyname('127.0.0.1')`.
gethostent (Win32) Not implemented.
getnetent (Android, Win32, Plan 9) Not implemented.
getprotoent (Android, Win32, Plan 9) Not implemented.
getservent (Win32, Plan 9) Not implemented.
seekdir (Android) Not implemented.
sethostent (Android, Win32, Plan 9, RISC OS) Not implemented.
setnetent (Win32, Plan 9, RISC OS) Not implemented.
setprotoent (Android, Win32, Plan 9, RISC OS) Not implemented.
setservent (Plan 9, Win32, RISC OS) Not implemented.
endpwent (Win32) Not implemented.
(Android) Either not implemented or a no-op.
endgrent (Android, RISC OS, VMS, Win32) Not implemented.
endhostent (Android, Win32) Not implemented.
endnetent (Android, Win32, Plan 9) Not implemented.
endprotoent (Android, Win32, Plan 9) Not implemented.
endservent (Plan 9, Win32) Not implemented.
getsockopt (Plan 9) Not implemented.
glob This operator is implemented via the [`File::Glob`](File::Glob) extension on most platforms. See <File::Glob> for portability information.
gmtime In theory, `gmtime` is reliable from -2\*\*63 to 2\*\*63-1. However, because work-arounds in the implementation use floating point numbers, it will become inaccurate as the time gets larger. This is a bug and will be fixed in the future.
(VOS) Time values are 32-bit quantities.
ioctl (VMS) Not implemented.
(Win32) Available only for socket handles, and it does what the `ioctlsocket()` call in the Winsock API does.
(RISC OS) Available only for socket handles.
kill (RISC OS) Not implemented, hence not useful for taint checking.
(Win32) `kill` doesn't send a signal to the identified process like it does on Unix platforms. Instead `kill($sig, $pid)` terminates the process identified by `$pid`, and makes it exit immediately with exit status `$sig`. As in Unix, if `$sig` is 0 and the specified process exists, it returns true without actually terminating it.
(Win32) `kill(-9, $pid)` will terminate the process specified by `$pid` and recursively all child processes owned by it. This is different from the Unix semantics, where the signal will be delivered to all processes in the same process group as the process specified by `$pid`.
(VMS) A pid of -1 indicating all processes on the system is not currently supported.
link (RISC OS, VOS) Not implemented.
(AmigaOS) Link count not updated because hard links are not quite that hard (They are sort of half-way between hard and soft links).
(Win32) Hard links are implemented on Win32 under NTFS only. They are natively supported on Windows 2000 and later. On Windows NT they are implemented using the Windows POSIX subsystem support and the Perl process will need Administrator or Backup Operator privileges to create hard links.
(VMS) Available on 64 bit OpenVMS 8.2 and later.
localtime `localtime` has the same range as ["gmtime"](#gmtime), but because time zone rules change, its accuracy for historical and future times may degrade but usually by no more than an hour.
lstat (RISC OS) Not implemented.
(Win32) Treats directory junctions as symlinks.
msgctl msgget msgsnd msgrcv (Android, Win32, VMS, Plan 9, RISC OS, VOS) Not implemented.
open (RISC OS) Open modes `|-` and `-|` are unsupported.
(SunOS, Solaris, HP-UX) Opening a process does not automatically flush output handles on some platforms.
(Win32) Both of modes `|-` and `-|` are supported, but the list form is emulated since the Win32 API CreateProcess() accepts a simple string rather than an array of arguments. This may have security implications for your code.
readlink (VMS, RISC OS) Not implemented.
(Win32) readlink() on a directory junction returns the object name, not a simple path.
rename (Win32) Can't move directories between directories on different logical volumes.
rewinddir (Win32) Will not cause [`readdir`](perlfunc#readdir-DIRHANDLE) to re-read the directory stream. The entries already read before the `rewinddir` call will just be returned again from a cache buffer.
select (Win32, VMS) Only implemented on sockets.
(RISC OS) Only reliable on sockets.
Note that the [`select FILEHANDLE`](perlfunc#select-FILEHANDLE) form is generally portable.
semctl semget semop (Android, Win32, VMS, RISC OS) Not implemented.
setgrent (Android, VMS, Win32, RISC OS) Not implemented.
setpgrp (Win32, VMS, RISC OS, VOS) Not implemented.
setpriority (Win32, VMS, RISC OS, VOS) Not implemented.
setpwent (Android, Win32, RISC OS) Not implemented.
setsockopt (Plan 9) Not implemented.
shmctl shmget shmread shmwrite (Android, Win32, VMS, RISC OS) Not implemented.
sleep (Win32) Emulated using synchronization functions such that it can be interrupted by [`alarm`](perlfunc#alarm-SECONDS), and limited to a maximum of 4294967 seconds, approximately 49 days.
socketpair (RISC OS) Not implemented.
(VMS) Available on 64 bit OpenVMS 8.2 and later.
stat Platforms that do not have `rdev`, `blksize`, or `blocks` will return these as `''`, so numeric comparison or manipulation of these fields may cause 'not numeric' warnings.
(Mac OS X) `ctime` not supported on UFS.
(Win32) `ctime` is creation time instead of inode change time.
(VMS) `dev` and `ino` are not necessarily reliable.
(RISC OS) `mtime`, `atime` and `ctime` all return the last modification time. `dev` and `ino` are not necessarily reliable.
(OS/2) `dev`, `rdev`, `blksize`, and `blocks` are not available. `ino` is not meaningful and will differ between stat calls on the same file.
(Cygwin) Some versions of cygwin when doing a `stat("foo")` and not finding it may then attempt to `stat("foo.exe")`.
symlink (RISC OS) Not implemented.
(Win32) Requires either elevated permissions or developer mode and a sufficiently recent version of Windows 10. You can check whether the current process has the required privileges using the [Win32::IsSymlinkCreationAllowed()](win32#Win32%3A%3AIsSymlinkCreationAllowed%28%29) function.
Since Windows needs to know whether the target is a directory or not when creating the link the target Perl will only create the link as a directory link when the target exists and is a directory.
(VMS) Implemented on 64 bit VMS 8.3. VMS requires the symbolic link to be in Unix syntax if it is intended to resolve to a valid path.
syscall (Win32, VMS, RISC OS, VOS) Not implemented.
sysopen (Mac OS, OS/390) The traditional `0`, `1`, and `2` MODEs are implemented with different numeric values on some systems. The flags exported by [`Fcntl`](fcntl) (`O_RDONLY`, `O_WRONLY`, `O_RDWR`) should work everywhere though.
system (Win32) As an optimization, may not call the command shell specified in `$ENV{PERL5SHELL}`. `system(1, @args)` spawns an external process and immediately returns its process designator, without waiting for it to terminate. Return value may be used subsequently in [`wait`](perlfunc#wait) or [`waitpid`](perlfunc#waitpid-PID%2CFLAGS). Failure to `spawn()` a subprocess is indicated by setting [`$?`](perlvar#%24%3F) to `255 << 8`. [`$?`](perlvar#%24%3F) is set in a way compatible with Unix (i.e. the exit status of the subprocess is obtained by `$? >> 8`, as described in the documentation).
Note that the list form of system() is emulated since the Win32 API CreateProcess() accepts a simple string rather than an array of command-line arguments. This may have security implications for your code.
(RISC OS) There is no shell to process metacharacters, and the native standard is to pass a command line terminated by "\n" "\r" or "\0" to the spawned program. Redirection such as `> foo` is performed (if at all) by the run time library of the spawned program. `system LIST` will call the Unix emulation library's [`exec`](perlfunc#exec-LIST) emulation, which attempts to provide emulation of the stdin, stdout, stderr in force in the parent, provided the child program uses a compatible version of the emulation library. `system SCALAR` will call the native command line directly and no such emulation of a child Unix program will occur. Mileage **will** vary.
(Win32) `system LIST` without the use of indirect object syntax (`system PROGRAM LIST`) may fall back to trying the shell if the first `spawn()` fails.
(SunOS, Solaris, HP-UX) Does not automatically flush output handles on some platforms.
(VMS) As with Win32, `system(1, @args)` spawns an external process and immediately returns its process designator without waiting for the process to terminate. In this case the return value may be used subsequently in [`wait`](perlfunc#wait) or [`waitpid`](perlfunc#waitpid-PID%2CFLAGS). Otherwise the return value is POSIX-like (shifted up by 8 bits), which only allows room for a made-up value derived from the severity bits of the native 32-bit condition code (unless overridden by [`use vmsish 'status'`](vmsish#vmsish-status)). If the native condition code is one that has a POSIX value encoded, the POSIX value will be decoded to extract the expected exit value. For more details see ["$?" in perlvms](perlvms#%24%3F).
telldir (Android) Not implemented.
times (Win32) "Cumulative" times will be bogus. On anything other than Windows NT or Windows 2000, "system" time will be bogus, and "user" time is actually the time returned by the [`clock()`](http://man.he.net/man3/clock) function in the C runtime library.
(RISC OS) Not useful.
truncate (Older versions of VMS) Not implemented.
(VOS) Truncation to same-or-shorter lengths only.
(Win32) If a FILEHANDLE is supplied, it must be writable and opened in append mode (i.e., use `open(my $fh, '>>', 'filename')` or `sysopen(my $fh, ..., O_APPEND|O_RDWR)`. If a filename is supplied, it should not be held open elsewhere.
umask Returns `undef` where unavailable.
(AmigaOS) `umask` works but the correct permissions are set only when the file is finally closed.
utime (VMS, RISC OS) Only the modification time is updated.
(Win32) May not behave as expected. Behavior depends on the C runtime library's implementation of [`utime()`](http://man.he.net/man2/utime), and the filesystem being used. The FAT filesystem typically does not support an "access time" field, and it may limit timestamps to a granularity of two seconds.
wait waitpid (Win32) Can only be applied to process handles returned for processes spawned using `system(1, ...)` or pseudo processes created with [`fork`](perlfunc#fork).
(RISC OS) Not useful.
Supported Platforms
--------------------
The following platforms are known to build Perl 5.12 (as of April 2010, its release date) from the standard source code distribution available at <http://www.cpan.org/src>
Linux (x86, ARM, IA64)
HP-UX AIX Win32
Windows 2000
Windows XP
Windows Server 2003
Windows Vista
Windows Server 2008
Windows 7 Cygwin Some tests are known to fail:
* *ext/XS-APItest/t/call\_checker.t* - see <https://github.com/Perl/perl5/issues/10750>
* *dist/I18N-Collate/t/I18N-Collate.t*
* *ext/Win32CORE/t/win32core.t* - may fail on recent cygwin installs.
Solaris (x86, SPARC) OpenVMS
Alpha (7.2 and later)
I64 (8.2 and later) NetBSD FreeBSD
Debian GNU/kFreeBSD Haiku
Irix (6.5. What else?) OpenBSD
Dragonfly BSD
Midnight BSD
QNX Neutrino RTOS (6.5.0)
MirOS BSD
Stratus OpenVOS (17.0 or later) Caveats:
time\_t issues that may or may not be fixed
Stratus VOS / OpenVOS AIX Android FreeMINT Perl now builds with FreeMiNT/Atari. It fails a few tests, that needs some investigation.
The FreeMiNT port uses GNU dld for loadable module capabilities. So ensure you have that library installed when building perl.
EOL Platforms
--------------
###
(Perl 5.36)
The following platforms were supported by a previous version of Perl but have been officially removed from Perl's source code as of 5.36:
NetWare
DOS/DJGPP
AT&T UWIN ###
(Perl 5.20)
The following platforms were supported by a previous version of Perl but have been officially removed from Perl's source code as of 5.20:
AT&T 3b1 ###
(Perl 5.14)
The following platforms were supported up to 5.10. They may still have worked in 5.12, but supporting code has been removed for 5.14:
Windows 95
Windows 98
Windows ME
Windows NT4 ###
(Perl 5.12)
The following platforms were supported by a previous version of Perl but have been officially removed from Perl's source code as of 5.12:
Atari MiNT
Apollo Domain/OS
Apple Mac OS 8/9
Tenon Machten
Supported Platforms (Perl 5.8)
-------------------------------
As of July 2002 (the Perl release 5.8.0), the following platforms were able to build Perl from the standard source code distribution available at <http://www.cpan.org/src/>
```
AIX
BeOS
BSD/OS (BSDi)
Cygwin
DG/UX
DOS DJGPP 1)
DYNIX/ptx
EPOC R5
FreeBSD
HI-UXMPP (Hitachi) (5.8.0 worked but we didn't know it)
HP-UX
IRIX
Linux
Mac OS Classic
Mac OS X (Darwin)
MPE/iX
NetBSD
NetWare
NonStop-UX
ReliantUNIX (formerly SINIX)
OpenBSD
OpenVMS (formerly VMS)
Open UNIX (Unixware) (since Perl 5.8.1/5.9.0)
OS/2
OS/400 (using the PASE) (since Perl 5.8.1/5.9.0)
POSIX-BC (formerly BS2000)
QNX
Solaris
SunOS 4
SUPER-UX (NEC)
Tru64 UNIX (formerly DEC OSF/1, Digital UNIX)
UNICOS
UNICOS/mk
UTS
VOS / OpenVOS
Win95/98/ME/2K/XP 2)
WinCE
z/OS (formerly OS/390)
VM/ESA
1) in DOS mode either the DOS or OS/2 ports can be used
2) compilers: Borland, MinGW (GCC), VC6
```
The following platforms worked with the previous releases (5.6 and 5.7), but we did not manage either to fix or to test these in time for the 5.8.0 release. There is a very good chance that many of these will work fine with the 5.8.0.
```
BSD/OS
DomainOS
Hurd
LynxOS
MachTen
PowerMAX
SCO SV
SVR4
Unixware
Windows 3.1
```
Known to be broken for 5.8.0 (but 5.6.1 and 5.7.2 can be used):
```
AmigaOS 3
```
The following platforms have been known to build Perl from source in the past (5.005\_03 and earlier), but we haven't been able to verify their status for the current release, either because the hardware/software platforms are rare or because we don't have an active champion on these platforms--or both. They used to work, though, so go ahead and try compiling them, and let <https://github.com/Perl/perl5/issues> know of any trouble.
```
3b1
A/UX
ConvexOS
CX/UX
DC/OSx
DDE SMES
DOS EMX
Dynix
EP/IX
ESIX
FPS
GENIX
Greenhills
ISC
MachTen 68k
MPC
NEWS-OS
NextSTEP
OpenSTEP
Opus
Plan 9
RISC/os
SCO ODT/OSR
Stellar
SVR2
TI1500
TitanOS
Ultrix
Unisys Dynix
```
The following platforms have their own source code distributions and binaries available via <http://www.cpan.org/ports/>
```
Perl release
OS/400 (ILE) 5.005_02
Tandem Guardian 5.004
```
The following platforms have only binaries available via <http://www.cpan.org/ports/index.html> :
```
Perl release
Acorn RISCOS 5.005_02
AOS 5.002
LynxOS 5.004_02
```
Although we do suggest that you always build your own Perl from the source code, both for maximal configurability and for security, in case you are in a hurry you can check <http://www.cpan.org/ports/index.html> for binary distributions.
SEE ALSO
---------
<perlaix>, <perlamiga>, <perlbs2000>, <perlcygwin>, <perlebcdic>, <perlfreebsd>, <perlhurd>, <perlhpux>, <perlirix>, <perlmacosx>, <perlos2>, <perlos390>, <perlos400>, <perlplan9>, <perlqnx>, <perlsolaris>, <perltru64>, <perlunicode>, <perlvms>, <perlvos>, <perlwin32>, and [Win32](win32).
AUTHORS / CONTRIBUTORS
-----------------------
Abigail <[email protected]>, Charles Bailey <[email protected]>, Graham Barr <[email protected]>, Tom Christiansen <[email protected]>, Nicholas Clark <[email protected]>, Thomas Dorner <[email protected]>, Andy Dougherty <[email protected]>, Dominic Dunlop <[email protected]>, Neale Ferguson <[email protected]>, David J. Fiander <[email protected]>, Paul Green <[email protected]>, M.J.T. Guy <[email protected]>, Jarkko Hietaniemi <[email protected]>, Luther Huffman <[email protected]>, Nick Ing-Simmons <[email protected]>, Andreas J. König <[email protected]>, Markus Laker <[email protected]>, Andrew M. Langmead <[email protected]>, Lukas Mai <[email protected]>, Larry Moore <[email protected]>, Paul Moore <[email protected]>, Chris Nandor <[email protected]>, Matthias Neeracher <[email protected]>, Philip Newton <[email protected]>, Gary Ng <[email protected]>, Tom Phoenix <[email protected]>, André Pirard <[email protected]>, Peter Prymmer <[email protected]>, Hugo van der Sanden <[email protected]>, Gurusamy Sarathy <[email protected]>, Paul J. Schinder <[email protected]>, Michael G Schwern <[email protected]>, Dan Sugalski <[email protected]>, Nathan Torkington <[email protected]>, John Malmberg <[email protected]>
| programming_docs |
perl Test::Tester Test::Tester
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [HOW TO USE (THE EASY WAY)](#HOW-TO-USE-(THE-EASY-WAY))
* [HOW TO USE (THE HARD WAY)](#HOW-TO-USE-(THE-HARD-WAY))
* [TEST RESULTS](#TEST-RESULTS)
* [SPACES AND TABS](#SPACES-AND-TABS)
* [COLOUR](#COLOUR)
* [EXPORTED FUNCTIONS](#EXPORTED-FUNCTIONS)
+ [($premature, @results) = run\_tests(\&test\_sub)](#(%24premature,-@results)-=-run_tests(%5C&test_sub))
+ [cmp\_result(\%result, \%expect, $name)](#cmp_result(%5C%25result,-%5C%25expect,-%24name))
+ [cmp\_results(\@results, \@expects, $name)](#cmp_results(%5C@results,-%5C@expects,-%24name))
+ [($premature, @results) = check\_tests(\&test\_sub, \@expects, $name)](#(%24premature,-@results)-=-check_tests(%5C&test_sub,-%5C@expects,-%24name))
+ [($premature, @results) = check\_test(\&test\_sub, \%expect, $name)](#(%24premature,-@results)-=-check_test(%5C&test_sub,-%5C%25expect,-%24name))
+ [show\_space()](#show_space())
* [HOW IT WORKS](#HOW-IT-WORKS)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
Test::Tester - Ease testing test modules built with Test::Builder
SYNOPSIS
--------
```
use Test::Tester tests => 6;
use Test::MyStyle;
check_test(
sub {
is_mystyle_eq("this", "that", "not eq");
},
{
ok => 0, # expect this to fail
name => "not eq",
diag => "Expected: 'this'\nGot: 'that'",
}
);
```
or
```
use Test::Tester tests => 6;
use Test::MyStyle;
check_test(
sub {
is_mystyle_qr("this", "that", "not matching");
},
{
ok => 0, # expect this to fail
name => "not matching",
diag => qr/Expected: 'this'\s+Got: 'that'/,
}
);
```
or
```
use Test::Tester;
use Test::More tests => 3;
use Test::MyStyle;
my ($premature, @results) = run_tests(
sub {
is_database_alive("dbname");
}
);
# now use Test::More::like to check the diagnostic output
like($results[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag");
```
DESCRIPTION
-----------
If you have written a test module based on Test::Builder then Test::Tester allows you to test it with the minimum of effort.
HOW TO USE (THE EASY WAY)
--------------------------
From version 0.08 Test::Tester no longer requires you to included anything special in your test modules. All you need to do is
```
use Test::Tester;
```
in your test script **before** any other Test::Builder based modules and away you go.
Other modules based on Test::Builder can be used to help with the testing. In fact you can even use functions from your module to test other functions from the same module (while this is possible it is probably not a good idea, if your module has bugs, then using it to test itself may give the wrong answers).
The easiest way to test is to do something like
```
check_test(
sub { is_mystyle_eq("this", "that", "not eq") },
{
ok => 0, # we expect the test to fail
name => "not eq",
diag => "Expected: 'this'\nGot: 'that'",
}
);
```
this will execute the is\_mystyle\_eq test, capturing its results and checking that they are what was expected.
You may need to examine the test results in a more flexible way, for example, the diagnostic output may be quite long or complex or it may involve something that you cannot predict in advance like a timestamp. In this case you can get direct access to the test results:
```
my ($premature, @results) = run_tests(
sub {
is_database_alive("dbname");
}
);
like($result[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag");
```
or
```
check_test(
sub { is_mystyle_qr("this", "that", "not matching") },
{
ok => 0, # we expect the test to fail
name => "not matching",
diag => qr/Expected: 'this'\s+Got: 'that'/,
}
);
```
We cannot predict how long the database ping will take so we use Test::More's like() test to check that the diagnostic string is of the right form.
HOW TO USE (THE HARD WAY)
--------------------------
*This is here for backwards compatibility only*
Make your module use the Test::Tester::Capture object instead of the Test::Builder one. How to do this depends on your module but assuming that your module holds the Test::Builder object in $Test and that all your test routines access it through $Test then providing a function something like this
```
sub set_builder
{
$Test = shift;
}
```
should allow your test scripts to do
```
Test::YourModule::set_builder(Test::Tester->capture);
```
and after that any tests inside your module will captured.
TEST RESULTS
-------------
The result of each test is captured in a hash. These hashes are the same as the hashes returned by Test::Builder->details but with a couple of extra fields.
These fields are documented in <Test::Builder> in the details() function
ok Did the test pass?
actual\_ok Did the test really pass? That is, did the pass come from Test::Builder->ok() or did it pass because it was a TODO test?
name The name supplied for the test.
type What kind of test? Possibilities include, skip, todo etc. See <Test::Builder> for more details.
reason The reason for the skip, todo etc. See <Test::Builder> for more details.
These fields are exclusive to Test::Tester.
diag Any diagnostics that were output for the test. This only includes diagnostics output **after** the test result is declared.
Note that Test::Builder ensures that any diagnostics end in a \n and it in earlier versions of Test::Tester it was essential that you have the final \n in your expected diagnostics. From version 0.10 onward, Test::Tester will add the \n if you forgot it. It will not add a \n if you are expecting no diagnostics. See below for help tracking down hard to find space and tab related problems.
depth This allows you to check that your test module is setting the correct value for $Test::Builder::Level and thus giving the correct file and line number when a test fails. It is calculated by looking at caller() and $Test::Builder::Level. It should count how many subroutines there are before jumping into the function you are testing. So for example in
```
run_tests( sub { my_test_function("a", "b") } );
```
the depth should be 1 and in
```
sub deeper { my_test_function("a", "b") }
run_tests(sub { deeper() });
```
depth should be 2, that is 1 for the sub {} and one for deeper(). This might seem a little complex but if your tests look like the simple examples in this doc then you don't need to worry as the depth will always be 1 and that's what Test::Tester expects by default.
**Note**: if you do not specify a value for depth in check\_test() then it automatically compares it against 1, if you really want to skip the depth test then pass in undef.
**Note**: depth will not be correctly calculated for tests that run from a signal handler or an END block or anywhere else that hides the call stack.
Some of Test::Tester's functions return arrays of these hashes, just like Test::Builder->details. That is, the hash for the first test will be array element 1 (not 0). Element 0 will not be a hash it will be a string which contains any diagnostic output that came before the first test. This should usually be empty, if it's not, it means something output diagnostics before any test results showed up.
SPACES AND TABS
----------------
Appearances can be deceptive, especially when it comes to emptiness. If you are scratching your head trying to work out why Test::Tester is saying that your diagnostics are wrong when they look perfectly right then the answer is probably whitespace. From version 0.10 on, Test::Tester surrounds the expected and got diag values with single quotes to make it easier to spot trailing whitespace. So in this example
```
# Got diag (5 bytes):
# 'abcd '
# Expected diag (4 bytes):
# 'abcd'
```
it is quite clear that there is a space at the end of the first string. Another way to solve this problem is to use colour and inverse video on an ANSI terminal, see below COLOUR below if you want this.
Unfortunately this is sometimes not enough, neither colour nor quotes will help you with problems involving tabs, other non-printing characters and certain kinds of problems inherent in Unicode. To deal with this, you can switch Test::Tester into a mode whereby all "tricky" characters are shown as \{xx}. Tricky characters are those with ASCII code less than 33 or higher than 126. This makes the output more difficult to read but much easier to find subtle differences between strings. To turn on this mode either call `show_space()` in your test script or set the `TESTTESTERSPACE` environment variable to be a true value. The example above would then look like
```
# Got diag (5 bytes):
# abcd\x{20}
# Expected diag (4 bytes):
# abcd
```
COLOUR
------
If you prefer to use colour as a means of finding tricky whitespace characters then you can set the `TESTTESTCOLOUR` environment variable to a comma separated pair of colours, the first for the foreground, the second for the background. For example "white,red" will print white text on a red background. This requires the Term::ANSIColor module. You can specify any colour that would be acceptable to the Term::ANSIColor::color function.
If you spell colour differently, that's no problem. The `TESTTESTERCOLOR` variable also works (if both are set then the British spelling wins out).
EXPORTED FUNCTIONS
-------------------
####
($premature, @results) = run\_tests(\&test\_sub)
\&test\_sub is a reference to a subroutine.
run\_tests runs the subroutine in $test\_sub and captures the results of any tests inside it. You can run more than 1 test inside this subroutine if you like.
$premature is a string containing any diagnostic output from before the first test.
@results is an array of test result hashes.
####
cmp\_result(\%result, \%expect, $name)
\%result is a ref to a test result hash.
\%expect is a ref to a hash of expected values for the test result.
cmp\_result compares the result with the expected values. If any differences are found it outputs diagnostics. You may leave out any field from the expected result and cmp\_result will not do the comparison of that field.
####
cmp\_results(\@results, \@expects, $name)
\@results is a ref to an array of test results.
\@expects is a ref to an array of hash refs.
cmp\_results checks that the results match the expected results and if any differences are found it outputs diagnostics. It first checks that the number of elements in \@results and \@expects is the same. Then it goes through each result checking it against the expected result as in cmp\_result() above.
####
($premature, @results) = check\_tests(\&test\_sub, \@expects, $name)
\&test\_sub is a reference to a subroutine.
\@expect is a ref to an array of hash refs which are expected test results.
check\_tests combines run\_tests and cmp\_tests into a single call. It also checks if the tests died at any stage.
It returns the same values as run\_tests, so you can further examine the test results if you need to.
####
($premature, @results) = check\_test(\&test\_sub, \%expect, $name)
\&test\_sub is a reference to a subroutine.
\%expect is a ref to an hash of expected values for the test result.
check\_test is a wrapper around check\_tests. It combines run\_tests and cmp\_tests into a single call, checking if the test died. It assumes that only a single test is run inside \&test\_sub and include a test to make sure this is true.
It returns the same values as run\_tests, so you can further examine the test results if you need to.
####
show\_space()
Turn on the escaping of characters as described in the SPACES AND TABS section.
HOW IT WORKS
-------------
Normally, a test module (let's call it Test:MyStyle) calls Test::Builder->new to get the Test::Builder object. Test::MyStyle calls methods on this object to record information about test results. When Test::Tester is loaded, it replaces Test::Builder's new() method with one which returns a Test::Tester::Delegate object. Most of the time this object behaves as the real Test::Builder object. Any methods that are called are delegated to the real Test::Builder object so everything works perfectly. However once we go into test mode, the method calls are no longer passed to the real Test::Builder object, instead they go to the Test::Tester::Capture object. This object seems exactly like the real Test::Builder object, except, instead of outputting test results and diagnostics, it just records all the information for later analysis.
CAVEATS
-------
Support for calling Test::Builder->note is minimal. It's implemented as an empty stub, so modules that use it will not crash but the calls are not recorded for testing purposes like the others. Patches welcome.
SEE ALSO
---------
<Test::Builder> the source of testing goodness. <Test::Builder::Tester> for an alternative approach to the problem tackled by Test::Tester - captures the strings output by Test::Builder. This means you cannot get separate access to the individual pieces of information and you must predict **exactly** what your test will output.
AUTHOR
------
This module is copyright 2005 Fergal Daly <[email protected]>, some parts are based on other people's work.
Plan handling lifted from Test::More. written by Michael G Schwern <[email protected]>.
Test::Tester::Capture is a cut down and hacked up version of Test::Builder. Test::Builder was written by chromatic <[email protected]> and Michael G Schwern <[email protected]>.
LICENSE
-------
Under the same license as Perl itself
See http://www.perl.com/perl/misc/Artistic.html
perl O O
=
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONVENTIONS](#CONVENTIONS)
* [IMPLEMENTATION](#IMPLEMENTATION)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
O - Generic interface to Perl Compiler backends
SYNOPSIS
--------
```
perl -MO=[-q,]Backend[,OPTIONS] foo.pl
```
DESCRIPTION
-----------
This is the module that is used as a frontend to the Perl Compiler.
If you pass the `-q` option to the module, then the STDOUT filehandle will be redirected into the variable `$O::BEGIN_output` during compilation. This has the effect that any output printed to STDOUT by BEGIN blocks or use'd modules will be stored in this variable rather than printed. It's useful with those backends which produce output themselves (`Deparse`, `Concise` etc), so that their output is not confused with that generated by the code being compiled.
The `-qq` option behaves like `-q`, except that it also closes STDERR after deparsing has finished. This suppresses the "Syntax OK" message normally produced by perl.
CONVENTIONS
-----------
Most compiler backends use the following conventions: OPTIONS consists of a comma-separated list of words (no white-space). The `-v` option usually puts the backend into verbose mode. The `-ofile` option generates output to **file** instead of stdout. The `-D` option followed by various letters turns on various internal debugging flags. See the documentation for the desired backend (named `B::Backend` for the example above) to find out about that backend.
IMPLEMENTATION
--------------
This section is only necessary for those who want to write a compiler backend module that can be used via this module.
The command-line mentioned in the SYNOPSIS section corresponds to the Perl code
```
use O ("Backend", OPTIONS);
```
The `O::import` function loads the appropriate `B::Backend` module and calls its `compile` function, passing it OPTIONS. That function is expected to return a sub reference which we'll call CALLBACK. Next, the "compile-only" flag is switched on (equivalent to the command-line option `-c`) and a CHECK block is registered which calls CALLBACK. Thus the main Perl program mentioned on the command-line is read in, parsed and compiled into internal syntax tree form. Since the `-c` flag is set, the program does not start running (excepting BEGIN blocks of course) but the CALLBACK function registered by the compiler backend is called.
In summary, a compiler backend module should be called "B::Foo" for some foo and live in the appropriate directory for that name. It should define a function called `compile`. When the user types
```
perl -MO=Foo,OPTIONS foo.pl
```
that function is called and is passed those OPTIONS (split on commas). It should return a sub ref to the main compilation function. After the user's program is loaded and parsed, that returned sub ref is invoked which can then go ahead and do the compilation, usually by making use of the `B` module's functionality.
BUGS
----
The `-q` and `-qq` options don't work correctly if perl isn't compiled with PerlIO support : STDOUT will be closed instead of being redirected to `$O::BEGIN_output`.
AUTHOR
------
Malcolm Beattie, `[email protected]`
perl I18N::Langinfo I18N::Langinfo
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [For systems without nl\_langinfo](#For-systems-without-nl_langinfo)
+ [EXPORT](#EXPORT)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
I18N::Langinfo - query locale information
SYNOPSIS
--------
```
use I18N::Langinfo;
```
DESCRIPTION
-----------
The langinfo() function queries various locale information that can be used to localize output and user interfaces. It uses the current underlying locale, regardless of whether or not it was called from within the scope of `use locale`. The langinfo() function requires one numeric argument that identifies the locale constant to query: if no argument is supplied, `$_` is used. The numeric constants appropriate to be used as arguments are exportable from I18N::Langinfo.
The following example will import the langinfo() function itself and three constants to be used as arguments to langinfo(): a constant for the abbreviated first day of the week (the numbering starts from Sunday = 1) and two more constants for the affirmative and negative answers for a yes/no question in the current locale.
```
use I18N::Langinfo qw(langinfo ABDAY_1 YESSTR NOSTR);
my ($abday_1, $yesstr, $nostr) =
map { langinfo($_) } (ABDAY_1, YESSTR, NOSTR);
print "$abday_1? [$yesstr/$nostr] ";
```
In other words, in the "C" (or English) locale the above will probably print something like:
```
Sun? [yes/no]
```
but under a French locale
```
dim? [oui/non]
```
The usually available constants are as follows.
* For abbreviated and full length days of the week and months of the year:
```
ABDAY_1 ABDAY_2 ABDAY_3 ABDAY_4 ABDAY_5 ABDAY_6 ABDAY_7
ABMON_1 ABMON_2 ABMON_3 ABMON_4 ABMON_5 ABMON_6
ABMON_7 ABMON_8 ABMON_9 ABMON_10 ABMON_11 ABMON_12
DAY_1 DAY_2 DAY_3 DAY_4 DAY_5 DAY_6 DAY_7
MON_1 MON_2 MON_3 MON_4 MON_5 MON_6
MON_7 MON_8 MON_9 MON_10 MON_11 MON_12
```
* For the date-time, date, and time formats used by the strftime() function (see [POSIX](posix)):
```
D_T_FMT D_FMT T_FMT
```
* For the locales for which it makes sense to have ante meridiem and post meridiem time formats:
```
AM_STR PM_STR T_FMT_AMPM
```
* For the character code set being used (such as "ISO8859-1", "cp850", "koi8-r", "sjis", "utf8", etc.), and for the currency string:
```
CODESET CRNCYSTR
```
* For an alternate representation of digits, for the radix character used between the integer and the fractional part of decimal numbers, the group separator string for large-ish floating point numbers (yes, the final two are redundant with [POSIX::localeconv()](posix#localeconv)):
```
ALT_DIGITS RADIXCHAR THOUSEP
```
* For the affirmative and negative responses and expressions:
```
YESSTR YESEXPR NOSTR NOEXPR
```
* For the eras based on typically some ruler, such as the Japanese Emperor (naturally only defined in the appropriate locales):
```
ERA ERA_D_FMT ERA_D_T_FMT ERA_T_FMT
```
###
For systems without `nl_langinfo`
Starting in Perl 5.28, this module is available even on systems that lack a native `nl_langinfo`. On such systems, it uses various methods to construct what that function, if present, would return. But there are potential glitches. These are the items that could be different:
`ERA` Unimplemented, so returns `""`.
`CODESET` Unimplemented, except on Windows, due to the vagaries of vendor locale names, returning `""` on non-Windows.
`YESEXPR` `YESSTR` `NOEXPR` `NOSTR` Only the values for English are returned. `YESSTR` and `NOSTR` have been removed from POSIX 2008, and are retained here for backwards compatibility. Your platform's `nl_langinfo` may not support them.
`D_FMT` Always evaluates to `%x`, the locale's appropriate date representation.
`T_FMT` Always evaluates to `%X`, the locale's appropriate time representation.
`D_T_FMT` Always evaluates to `%c`, the locale's appropriate date and time representation.
`CRNCYSTR` The return may be incorrect for those rare locales where the currency symbol replaces the radix character. If you have examples of it needing to work differently, please file a report at <https://github.com/Perl/perl5/issues>.
`ALT_DIGITS` Currently this gives the same results as Linux does. If you have examples of it needing to work differently, please file a report at <https://github.com/Perl/perl5/issues>.
`ERA_D_FMT` `ERA_T_FMT` `ERA_D_T_FMT` `T_FMT_AMPM` These are derived by using `strftime()`, and not all versions of that function know about them. `""` is returned for these on such systems.
See your [nl\_langinfo(3)](http://man.he.net/man3/nl_langinfo) for more information about the available constants. (Often this means having to look directly at the *langinfo.h* C header file.)
### EXPORT
By default only the `langinfo()` function is exported.
BUGS
----
Before Perl 5.28, the returned values are unreliable for the `RADIXCHAR` and `THOUSEP` locale constants.
Starting in 5.28, changing locales on threaded builds is supported on systems that offer thread-safe locale functions. These include POSIX 2008 systems and Windows starting with Visual Studio 2005, and this module will work properly in such situations. However, on threaded builds on Windows prior to Visual Studio 2015, retrieving the items `CRNCYSTR` and `THOUSEP` can result in a race with a thread that has converted to use the global locale. It is quite uncommon for a thread to have done this. It would be possible to construct a workaround for this; patches welcome: see ["switch\_to\_global\_locale" in perlapi](perlapi#switch_to_global_locale).
SEE ALSO
---------
<perllocale>, ["localeconv" in POSIX](posix#localeconv), ["setlocale" in POSIX](posix#setlocale), [nl\_langinfo(3)](http://man.he.net/man3/nl_langinfo).
The langinfo() function is just a wrapper for the C nl\_langinfo() interface.
AUTHOR
------
Jarkko Hietaniemi, <[email protected]>. Now maintained by Perl 5 porters.
COPYRIGHT AND LICENSE
----------------------
Copyright 2001 by Jarkko Hietaniemi
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Net::POP3 Net::POP3
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Class Methods](#Class-Methods)
+ [Object Methods](#Object-Methods)
+ [Notes](#Notes)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::POP3 - Post Office Protocol 3 Client class (RFC1939)
SYNOPSIS
--------
```
use Net::POP3;
# Constructors
$pop = Net::POP3->new('pop3host');
$pop = Net::POP3->new('pop3host', Timeout => 60);
$pop = Net::POP3->new('pop3host', SSL => 1, Timeout => 60);
if ($pop->login($username, $password) > 0) {
my $msgnums = $pop->list; # hashref of msgnum => size
foreach my $msgnum (keys %$msgnums) {
my $msg = $pop->get($msgnum);
print @$msg;
$pop->delete($msgnum);
}
}
$pop->quit;
```
DESCRIPTION
-----------
This module implements a client interface to the POP3 protocol, enabling a perl5 application to talk to POP3 servers. This documentation assumes that you are familiar with the POP3 protocol described in RFC1939. With <IO::Socket::SSL> installed it also provides support for implicit and explicit TLS encryption, i.e. POP3S or POP3+STARTTLS.
A new Net::POP3 object must be created with the *new* method. Once this has been done, all POP3 commands are accessed via method calls on the object.
The Net::POP3 class is a subclass of Net::Cmd and (depending on avaibility) of IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
###
Class Methods
`new([$host][, %options])`
This is the constructor for a new Net::POP3 object. `$host` is the name of the remote host to which an POP3 connection is required.
`$host` is optional. If `$host` is not given then it may instead be passed as the `Host` option described below. If neither is given then the `POP3_Hosts` specified in `Net::Config` will be used.
`%options` are passed in a hash like fashion, using key and value pairs. Possible options are:
**Host** - POP3 host to connect to. It may be a single scalar, as defined for the `PeerAddr` option in <IO::Socket::INET>, or a reference to an array with hosts to try in turn. The ["host"](#host) method will return the value which was used to connect to the host.
**Port** - port to connect to. Default - 110 for plain POP3 and 995 for POP3s (direct SSL).
**SSL** - If the connection should be done from start with SSL, contrary to later upgrade with `starttls`. You can use SSL arguments as documented in <IO::Socket::SSL>, but it will usually use the right arguments already.
**LocalAddr** and **LocalPort** - These parameters are passed directly to IO::Socket to allow binding the socket to a specific local address and port. For compatibility with older versions **ResvPort** can be used instead of **LocalPort**.
**Domain** - This parameter is passed directly to IO::Socket and makes it possible to enforce IPv4 connections even if <IO::Socket::IP> is used as super class. Alternatively **Family** can be used.
**Timeout** - Maximum time, in seconds, to wait for a response from the POP3 server (default: 120)
**Debug** - Enable debugging information
###
Object Methods
Unless otherwise stated all methods return either a *true* or *false* value, with *true* meaning that the operation was a success. When a method states that it returns a value, failure will be returned as *undef* or an empty list.
`Net::POP3` inherits from `Net::Cmd` so methods defined in `Net::Cmd` may be used to send commands to the remote POP3 server in addition to the methods documented here.
`host()`
Returns the value used by the constructor, and passed to IO::Socket::INET, to connect to the host.
`auth($username, $password)`
Attempt SASL authentication.
`user($user)`
Send the USER command.
`pass($pass)`
Send the PASS command. Returns the number of messages in the mailbox.
`login([$user[, $pass]])`
Send both the USER and PASS commands. If `$pass` is not given the `Net::POP3` uses `Net::Netrc` to lookup the password using the host and username. If the username is not specified then the current user name will be used.
Returns the number of messages in the mailbox. However if there are no messages on the server the string `"0E0"` will be returned. This is will give a true value in a boolean context, but zero in a numeric context.
If there was an error authenticating the user then *undef* will be returned.
`starttls(%sslargs)`
Upgrade existing plain connection to SSL. You can use SSL arguments as documented in <IO::Socket::SSL>, but it will usually use the right arguments already.
`apop([$user[, $pass]])`
Authenticate with the server identifying as `$user` with password `$pass`. Similar to ["login"](#login), but the password is not sent in clear text.
To use this method you must have the Digest::MD5 or the MD5 module installed, otherwise this method will return *undef*.
`banner()`
Return the sever's connection banner
`capa()`
Return a reference to a hash of the capabilities of the server. APOP is added as a pseudo capability. Note that I've been unable to find a list of the standard capability values, and some appear to be multi-word and some are not. We make an attempt at intelligently parsing them, but it may not be correct.
`capabilities()`
Just like capa, but only uses a cache from the last time we asked the server, so as to avoid asking more than once.
`top($msgnum[, $numlines])`
Get the header and the first `$numlines` of the body for the message `$msgnum`. Returns a reference to an array which contains the lines of text read from the server.
`list([$msgnum])`
If called with an argument the `list` returns the size of the message in octets.
If called without arguments a reference to a hash is returned. The keys will be the `$msgnum`'s of all undeleted messages and the values will be their size in octets.
`get($msgnum[, $fh])`
Get the message `$msgnum` from the remote mailbox. If `$fh` is not given then get returns a reference to an array which contains the lines of text read from the server. If `$fh` is given then the lines returned from the server are printed to the filehandle `$fh`.
`getfh($msgnum)`
As per get(), but returns a tied filehandle. Reading from this filehandle returns the requested message. The filehandle will return EOF at the end of the message and should not be reused.
`last()`
Returns the highest `$msgnum` of all the messages accessed.
`popstat()`
Returns a list of two elements. These are the number of undeleted elements and the size of the mbox in octets.
`ping($user)`
Returns a list of two elements. These are the number of new messages and the total number of messages for `$user`.
`uidl([$msgnum])`
Returns a unique identifier for `$msgnum` if given. If `$msgnum` is not given `uidl` returns a reference to a hash where the keys are the message numbers and the values are the unique identifiers.
`delete($msgnum)`
Mark message `$msgnum` to be deleted from the remote mailbox. All messages that are marked to be deleted will be removed from the remote mailbox when the server connection closed.
`reset()`
Reset the status of the remote POP3 server. This includes resetting the status of all messages to not be deleted.
`quit()`
Quit and close the connection to the remote POP3 server. Any messages marked as deleted will be deleted from the remote mailbox.
`can_inet6()`
Returns whether we can use IPv6.
`can_ssl()`
Returns whether we can use SSL.
### Notes
If a `Net::POP3` object goes out of scope before `quit` method is called then the `reset` method will called before the connection is closed. This means that any messages marked to be deleted will not be.
EXPORTS
-------
*None*.
KNOWN BUGS
-----------
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
SEE ALSO
---------
<Net::Netrc>, <Net::Cmd>, <IO::Socket::SSL>.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 1995-2004 Graham Barr. All rights reserved.
Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
perl Perl::OSType Perl::OSType
============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
+ [os\_type()](#os_type())
+ [is\_os\_type()](#is_os_type())
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
+ [Bugs / Feature Requests](#Bugs-/-Feature-Requests)
+ [Source Code](#Source-Code)
* [AUTHOR](#AUTHOR)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Perl::OSType - Map Perl operating system names to generic types
VERSION
-------
version 1.010
SYNOPSIS
--------
```
use Perl::OSType ':all';
$current_type = os_type();
$other_type = os_type('dragonfly'); # gives 'Unix'
```
DESCRIPTION
-----------
Modules that provide OS-specific behaviors often need to know if the current operating system matches a more generic type of operating systems. For example, 'linux' is a type of 'Unix' operating system and so is 'freebsd'.
This module provides a mapping between an operating system name as given by `$^O` and a more generic type. The initial version is based on the OS type mappings provided in <Module::Build> and <ExtUtils::CBuilder>. (Thus, Microsoft operating systems are given the type 'Windows' rather than 'Win32'.)
USAGE
-----
No functions are exported by default. The export tag ":all" will export all functions listed below.
###
os\_type()
```
$os_type = os_type();
$os_type = os_type('MSWin32');
```
Returns a single, generic OS type for a given operating system name. With no arguments, returns the OS type for the current value of `$^O`. If the operating system is not recognized, the function will return the empty string.
###
is\_os\_type()
```
$is_windows = is_os_type('Windows');
$is_unix = is_os_type('Unix', 'dragonfly');
```
Given an OS type and OS name, returns true or false if the OS name is of the given type. As with `os_type`, it will use the current operating system as a default if no OS name is provided.
SEE ALSO
---------
* <Devel::CheckOS>
SUPPORT
-------
###
Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker at <https://github.com/Perl-Toolchain-Gang/Perl-OSType/issues>. You will be notified automatically of any progress on your issue.
###
Source Code
This is open source software. The code repository is available for public review and contribution under the terms of the license.
<https://github.com/Perl-Toolchain-Gang/Perl-OSType>
```
git clone https://github.com/Perl-Toolchain-Gang/Perl-OSType.git
```
AUTHOR
------
David Golden <[email protected]>
CONTRIBUTORS
------------
* Chris 'BinGOs' Williams <[email protected]>
* David Golden <[email protected]>
* Graham Ollis <[email protected]>
* Jonas B. Nielsen <[email protected]>
* Owain G. Ainsworth <[email protected]>
* Paul Green <[email protected]>
* Piotr Roszatycki <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2016 by David Golden.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl ExtUtils::MakeMaker::Locale ExtUtils::MakeMaker::Locale
===========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
+ [Windows](#Windows)
+ [Mac OS X](#Mac-OS-X)
+ [POSIX (Linux and other Unixes)](#POSIX-(Linux-and-other-Unixes))
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::MakeMaker::Locale - bundled Encode::Locale
SYNOPSIS
--------
```
use Encode::Locale;
use Encode;
$string = decode(locale => $bytes);
$bytes = encode(locale => $string);
if (-t) {
binmode(STDIN, ":encoding(console_in)");
binmode(STDOUT, ":encoding(console_out)");
binmode(STDERR, ":encoding(console_out)");
}
# Processing file names passed in as arguments
my $uni_filename = decode(locale => $ARGV[0]);
open(my $fh, "<", encode(locale_fs => $uni_filename))
|| die "Can't open '$uni_filename': $!";
binmode($fh, ":encoding(locale)");
...
```
DESCRIPTION
-----------
In many applications it's wise to let Perl use Unicode for the strings it processes. Most of the interfaces Perl has to the outside world are still byte based. Programs therefore need to decode byte strings that enter the program from the outside and encode them again on the way out.
The POSIX locale system is used to specify both the language conventions requested by the user and the preferred character set to consume and output. The `Encode::Locale` module looks up the charset and encoding (called a CODESET in the locale jargon) and arranges for the [Encode](encode) module to know this encoding under the name "locale". It means bytes obtained from the environment can be converted to Unicode strings by calling `Encode::encode(locale => $bytes)` and converted back again with `Encode::decode(locale => $string)`.
Where file systems interfaces pass file names in and out of the program we also need care. The trend is for operating systems to use a fixed file encoding that don't actually depend on the locale; and this module determines the most appropriate encoding for file names. The [Encode](encode) module will know this encoding under the name "locale\_fs". For traditional Unix systems this will be an alias to the same encoding as "locale".
For programs running in a terminal window (called a "Console" on some systems) the "locale" encoding is usually a good choice for what to expect as input and output. Some systems allows us to query the encoding set for the terminal and `Encode::Locale` will do that if available and make these encodings known under the `Encode` aliases "console\_in" and "console\_out". For systems where we can't determine the terminal encoding these will be aliased as the same encoding as "locale". The advice is to use "console\_in" for input known to come from the terminal and "console\_out" for output to the terminal.
In addition to arranging for various Encode aliases the following functions and variables are provided:
decode\_argv( )
decode\_argv( Encode::FB\_CROAK ) This will decode the command line arguments to perl (the `@ARGV` array) in-place.
The function will by default replace characters that can't be decoded by "\x{FFFD}", the Unicode replacement character.
Any argument provided is passed as CHECK to underlying Encode::decode() call. Pass the value `Encode::FB_CROAK` to have the decoding croak if not all the command line arguments can be decoded. See ["Handling Malformed Data" in Encode](encode#Handling-Malformed-Data) for details on other options for CHECK.
env( $uni\_key )
env( $uni\_key => $uni\_value ) Interface to get/set environment variables. Returns the current value as a Unicode string. The $uni\_key and $uni\_value arguments are expected to be Unicode strings as well. Passing `undef` as $uni\_value deletes the environment variable named $uni\_key.
The returned value will have the characters that can't be decoded replaced by "\x{FFFD}", the Unicode replacement character.
There is no interface to request alternative CHECK behavior as for decode\_argv(). If you need that you need to call encode/decode yourself. For example:
```
my $key = Encode::encode(locale => $uni_key, Encode::FB_CROAK);
my $uni_value = Encode::decode(locale => $ENV{$key}, Encode::FB_CROAK);
```
reinit( )
reinit( $encoding ) Reinitialize the encodings from the locale. You want to call this function if you changed anything in the environment that might influence the locale.
This function will croak if the determined encoding isn't recognized by the Encode module.
With argument force $ENCODING\_... variables to set to the given value.
$ENCODING\_LOCALE The encoding name determined to be suitable for the current locale. [Encode](encode) know this encoding as "locale".
$ENCODING\_LOCALE\_FS The encoding name determined to be suitable for file system interfaces involving file names. [Encode](encode) know this encoding as "locale\_fs".
$ENCODING\_CONSOLE\_IN
$ENCODING\_CONSOLE\_OUT The encodings to be used for reading and writing output to the a console. [Encode](encode) know these encodings as "console\_in" and "console\_out".
NOTES
-----
This table summarizes the mapping of the encodings set up by the `Encode::Locale` module:
```
Encode | | |
Alias | Windows | Mac OS X | POSIX
------------+---------+--------------+------------
locale | ANSI | nl_langinfo | nl_langinfo
locale_fs | ANSI | UTF-8 | nl_langinfo
console_in | OEM | nl_langinfo | nl_langinfo
console_out | OEM | nl_langinfo | nl_langinfo
```
### Windows
Windows has basically 2 sets of APIs. A wide API (based on passing UTF-16 strings) and a byte based API based a character set called ANSI. The regular Perl interfaces to the OS currently only uses the ANSI APIs. Unfortunately ANSI is not a single character set.
The encoding that corresponds to ANSI varies between different editions of Windows. For many western editions of Windows ANSI corresponds to CP-1252 which is a character set similar to ISO-8859-1. Conceptually the ANSI character set is a similar concept to the POSIX locale CODESET so this module figures out what the ANSI code page is and make this available as $ENCODING\_LOCALE and the "locale" Encoding alias.
Windows systems also operate with another byte based character set. It's called the OEM code page. This is the encoding that the Console takes as input and output. It's common for the OEM code page to differ from the ANSI code page.
###
Mac OS X
On Mac OS X the file system encoding is always UTF-8 while the locale can otherwise be set up as normal for POSIX systems.
File names on Mac OS X will at the OS-level be converted to NFD-form. A file created by passing a NFC-filename will come in NFD-form from readdir(). See <Unicode::Normalize> for details of NFD/NFC.
Actually, Apple does not follow the Unicode NFD standard since not all character ranges are decomposed. The claim is that this avoids problems with round trip conversions from old Mac text encodings. See <Encode::UTF8Mac> for details.
###
POSIX (Linux and other Unixes)
File systems might vary in what encoding is to be used for filenames. Since this module has no way to actually figure out what the is correct it goes with the best guess which is to assume filenames are encoding according to the current locale. Users are advised to always specify UTF-8 as the locale charset.
SEE ALSO
---------
<I18N::Langinfo>, [Encode](encode), <Term::Encoding>
AUTHOR
------
Copyright 2010 Gisle Aas <[email protected]>.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Encode::KR Encode::KR
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::KR - Korean Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$euc_kr = encode("euc-kr", $utf8); # loads Encode::KR implicitly
$utf8 = decode("euc-kr", $euc_kr); # ditto
```
DESCRIPTION
-----------
This module implements Korean charset encodings. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
euc-kr /\beuc.*kr$/i EUC (Extended Unix Character)
/\bkr.*euc$/i
ksc5601-raw Korean standard code set (as is)
cp949 /(?:x-)?uhc$/i
/(?:x-)?windows-949$/i
/\bks_c_5601-1987$/i
Code Page 949 (EUC-KR + 8,822
(additional Hangul syllables)
MacKorean EUC-KR + Apple Vendor Mappings
johab JOHAB A supplementary encoding defined in
Annex 3 of KS X 1001:1998
iso-2022-kr iso-2022-kr [RFC1557]
--------------------------------------------------------------------
```
To find how to use this module in detail, see [Encode](encode).
BUGS
----
When you see `charset=ks_c_5601-1987` on mails and web pages, they really mean "cp949" encodings. To fix that, the following aliases are set;
```
qr/(?:x-)?uhc$/i => '"cp949"'
qr/(?:x-)?windows-949$/i => '"cp949"'
qr/ks_c_5601-1987$/i => '"cp949"'
```
The ASCII region (0x00-0x7f) is preserved for all encodings, even though this conflicts with mappings by the Unicode Consortium.
SEE ALSO
---------
[Encode](encode)
| programming_docs |
perl Test2::EventFacet::Plan Test2::EventFacet::Plan
=======================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Plan - Facet for setting the plan
DESCRIPTION
-----------
Events use this facet when they need to set the plan.
FIELDS
------
$string = $plan->{details}
$string = $plan->details() Human readable explanation for the plan being set. This is normally not rendered by most formatters except when the `skip` field is also set.
$positive\_int = $plan->{count}
$positive\_int = $plan->count() Set the number of expected assertions. This should usually be set to `0` when `skip` or `none` are also set.
$bool = $plan->{skip}
$bool = $plan->skip() When true the entire test should be skipped. This is usually paired with an explanation in the `details` field, and a `control` facet that has `terminate` set to `0`.
$bool = $plan->{none}
$bool = $plan->none() This is mainly used by legacy <Test::Builder> tests which set the plan to `no plan`, a construct that predates the much better `done_testing()`.
If you are using this in non-legacy code you may need to reconsider the course of your life, maybe a hermitage would suite you?
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Compress::Zlib Compress::Zlib
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Notes for users of Compress::Zlib version 1](#Notes-for-users-of-Compress::Zlib-version-1)
* [GZIP INTERFACE](#GZIP-INTERFACE)
+ [Examples](#Examples)
+ [Compress::Zlib::memGzip](#Compress::Zlib::memGzip)
+ [Compress::Zlib::memGunzip](#Compress::Zlib::memGunzip)
* [COMPRESS/UNCOMPRESS](#COMPRESS/UNCOMPRESS)
* [Deflate Interface](#Deflate-Interface)
+ [($d, $status) = deflateInit( [OPT] )](#(%24d,-%24status)-=-deflateInit(-%5BOPT%5D-))
+ [($out, $status) = $d->deflate($buffer)](#(%24out,-%24status)-=-%24d-%3Edeflate(%24buffer))
+ [($out, $status) = $d->flush() =head2 ($out, $status) = $d->flush($flush\_type)](#(%24out,-%24status)-=-%24d-%3Eflush()-=head2-(%24out,-%24status)-=-%24d-%3Eflush(%24flush_type))
+ [$status = $d->deflateParams([OPT])](#%24status-=-%24d-%3EdeflateParams(%5BOPT%5D))
+ [$d->dict\_adler()](#%24d-%3Edict_adler())
+ [$d->msg()](#%24d-%3Emsg())
+ [$d->total\_in()](#%24d-%3Etotal_in())
+ [$d->total\_out()](#%24d-%3Etotal_out())
+ [Example](#Example)
* [Inflate Interface](#Inflate-Interface)
+ [($i, $status) = inflateInit()](#(%24i,-%24status)-=-inflateInit())
+ [($out, $status) = $i->inflate($buffer)](#(%24out,-%24status)-=-%24i-%3Einflate(%24buffer))
+ [$status = $i->inflateSync($buffer)](#%24status-=-%24i-%3EinflateSync(%24buffer))
+ [$i->dict\_adler()](#%24i-%3Edict_adler())
+ [$i->msg()](#%24i-%3Emsg())
+ [$i->total\_in()](#%24i-%3Etotal_in())
+ [$i->total\_out()](#%24i-%3Etotal_out())
+ [Example](#Example1)
* [CHECKSUM FUNCTIONS](#CHECKSUM-FUNCTIONS)
* [Misc](#Misc)
+ [my $version = Compress::Zlib::zlib\_version();](#my-%24version-=-Compress::Zlib::zlib_version();)
* [CONSTANTS](#CONSTANTS)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Compress::Zlib - Interface to zlib compression library
SYNOPSIS
--------
```
use Compress::Zlib ;
($d, $status) = deflateInit( [OPT] ) ;
$status = $d->deflate($input, $output) ;
$status = $d->flush([$flush_type]) ;
$d->deflateParams(OPTS) ;
$d->deflateTune(OPTS) ;
$d->dict_adler() ;
$d->crc32() ;
$d->adler32() ;
$d->total_in() ;
$d->total_out() ;
$d->msg() ;
$d->get_Strategy();
$d->get_Level();
$d->get_BufSize();
($i, $status) = inflateInit( [OPT] ) ;
$status = $i->inflate($input, $output [, $eof]) ;
$status = $i->inflateSync($input) ;
$i->dict_adler() ;
$d->crc32() ;
$d->adler32() ;
$i->total_in() ;
$i->total_out() ;
$i->msg() ;
$d->get_BufSize();
$dest = compress($source) ;
$dest = uncompress($source) ;
$gz = gzopen($filename or filehandle, $mode) ;
$bytesread = $gz->gzread($buffer [,$size]) ;
$bytesread = $gz->gzreadline($line) ;
$byteswritten = $gz->gzwrite($buffer) ;
$status = $gz->gzflush($flush) ;
$offset = $gz->gztell() ;
$status = $gz->gzseek($offset, $whence) ;
$status = $gz->gzclose() ;
$status = $gz->gzeof() ;
$status = $gz->gzsetparams($level, $strategy) ;
$errstring = $gz->gzerror() ;
$gzerrno
$dest = Compress::Zlib::memGzip($buffer) ;
$dest = Compress::Zlib::memGunzip($buffer) ;
$crc = adler32($buffer [,$crc]) ;
$crc = crc32($buffer [,$crc]) ;
$crc = crc32_combine($crc1, $crc2, $len2);
$adler = adler32_combine($adler1, $adler2, $len2);
my $version = Compress::Raw::Zlib::zlib_version();
```
DESCRIPTION
-----------
The *Compress::Zlib* module provides a Perl interface to the *zlib* compression library (see ["AUTHOR"](#AUTHOR) for details about where to get *zlib*).
The `Compress::Zlib` module can be split into two general areas of functionality, namely a simple read/write interface to *gzip* files and a low-level in-memory compression/decompression interface.
Each of these areas will be discussed in the following sections.
###
Notes for users of Compress::Zlib version 1
The main change in `Compress::Zlib` version 2.x is that it does not now interface directly to the zlib library. Instead it uses the `IO::Compress::Gzip` and `IO::Uncompress::Gunzip` modules for reading/writing gzip files, and the `Compress::Raw::Zlib` module for some low-level zlib access.
The interface provided by version 2 of this module should be 100% backward compatible with version 1. If you find a difference in the expected behaviour please contact the author (See ["AUTHOR"](#AUTHOR)). See ["GZIP INTERFACE"](#GZIP-INTERFACE)
With the creation of the `IO::Compress` and `IO::Uncompress` modules no new features are planned for `Compress::Zlib` - the new modules do everything that `Compress::Zlib` does and then some. Development on `Compress::Zlib` will be limited to bug fixes only.
If you are writing new code, your first port of call should be one of the new `IO::Compress` or `IO::Uncompress` modules.
GZIP INTERFACE
---------------
A number of functions are supplied in *zlib* for reading and writing *gzip* files that conform to RFC 1952. This module provides an interface to most of them.
If you have previously used `Compress::Zlib` 1.x, the following enhancements/changes have been made to the `gzopen` interface:
1. If you want to open either STDIN or STDOUT with `gzopen`, you can now optionally use the special filename "`-`" as a synonym for `\*STDIN` and `\*STDOUT`.
2. In `Compress::Zlib` version 1.x, `gzopen` used the zlib library to open the underlying file. This made things especially tricky when a Perl filehandle was passed to `gzopen`. Behind the scenes the numeric C file descriptor had to be extracted from the Perl filehandle and this passed to the zlib library.
Apart from being non-portable to some operating systems, this made it difficult to use `gzopen` in situations where you wanted to extract/create a gzip data stream that is embedded in a larger file, without having to resort to opening and closing the file multiple times.
It also made it impossible to pass a perl filehandle that wasn't associated with a real filesystem file, like, say, an `IO::String`.
In `Compress::Zlib` version 2.x, the `gzopen` interface has been completely rewritten to use the <IO::Compress::Gzip> for writing gzip files and <IO::Uncompress::Gunzip> for reading gzip files. None of the limitations mentioned above apply.
3. Addition of `gzseek` to provide a restricted `seek` interface.
4. Added `gztell`.
A more complete and flexible interface for reading/writing gzip files/buffers is included with the module `IO-Compress-Zlib`. See <IO::Compress::Gzip> and <IO::Uncompress::Gunzip> for more details.
**$gz = gzopen($filename, $mode)**
**$gz = gzopen($filehandle, $mode)**
This function opens either the *gzip* file `$filename` for reading or writing or attaches to the opened filehandle, `$filehandle`. It returns an object on success and `undef` on failure.
When writing a gzip file this interface will *always* create the smallest possible gzip header (exactly 10 bytes). If you want greater control over what gets stored in the gzip header (like the original filename or a comment) use <IO::Compress::Gzip> instead. Similarly if you want to read the contents of the gzip header use <IO::Uncompress::Gunzip>.
The second parameter, `$mode`, is used to specify whether the file is opened for reading or writing and to optionally specify a compression level and compression strategy when writing. The format of the `$mode` parameter is similar to the mode parameter to the 'C' function `fopen`, so "rb" is used to open for reading, "wb" for writing and "ab" for appending (writing at the end of the file).
To specify a compression level when writing, append a digit between 0 and 9 to the mode string -- 0 means no compression and 9 means maximum compression. If no compression level is specified Z\_DEFAULT\_COMPRESSION is used.
To specify the compression strategy when writing, append 'f' for filtered data, 'h' for Huffman only compression, or 'R' for run-length encoding. If no strategy is specified Z\_DEFAULT\_STRATEGY is used.
So, for example, "wb9" means open for writing with the maximum compression using the default strategy and "wb4R" means open for writing with compression level 4 and run-length encoding.
Refer to the *zlib* documentation for the exact format of the `$mode` parameter.
**$bytesread = $gz->gzread($buffer [, $size]) ;**
Reads `$size` bytes from the compressed file into `$buffer`. If `$size` is not specified, it will default to 4096. If the scalar `$buffer` is not large enough, it will be extended automatically.
Returns the number of bytes actually read. On EOF it returns 0 and in the case of an error, -1.
**$bytesread = $gz->gzreadline($line) ;**
Reads the next line from the compressed file into `$line`.
Returns the number of bytes actually read. On EOF it returns 0 and in the case of an error, -1.
It is legal to intermix calls to `gzread` and `gzreadline`.
To maintain backward compatibility with version 1.x of this module `gzreadline` ignores the `$/` variable - it *always* uses the string `"\n"` as the line delimiter.
If you want to read a gzip file a line at a time and have it respect the `$/` variable (or `$INPUT_RECORD_SEPARATOR`, or `$RS` when `English` is in use) see <IO::Uncompress::Gunzip>.
**$byteswritten = $gz->gzwrite($buffer) ;**
Writes the contents of `$buffer` to the compressed file. Returns the number of bytes actually written, or 0 on error.
**$status = $gz->gzflush($flush\_type) ;**
Flushes all pending output into the compressed file.
This method takes an optional parameter, `$flush_type`, that controls how the flushing will be carried out. By default the `$flush_type` used is `Z_FINISH`. Other valid values for `$flush_type` are `Z_NO_FLUSH`, `Z_SYNC_FLUSH`, `Z_FULL_FLUSH` and `Z_BLOCK`. It is strongly recommended that you only set the `flush_type` parameter if you fully understand the implications of what it does - overuse of `flush` can seriously degrade the level of compression achieved. See the `zlib` documentation for details.
Returns 0 on success.
**$offset = $gz->gztell() ;**
Returns the uncompressed file offset.
**$status = $gz->gzseek($offset, $whence) ;**
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the compressed file. It is a fatal error to attempt to seek backward.
When opened for writing, empty parts of the file will have NULL (0x00) bytes written to them.
The `$whence` parameter should be one of SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
**$gz->gzclose**
Closes the compressed file. Any pending data is flushed to the file before it is closed.
Returns 0 on success.
**$gz->gzsetparams($level, $strategy**
Change settings for the deflate stream `$gz`.
The list of the valid options is shown below. Options not specified will remain unchanged.
Note: This method is only available if you are running zlib 1.0.6 or better.
**$level**
Defines the compression level. Valid values are 0 through 9, `Z_NO_COMPRESSION`, `Z_BEST_SPEED`, `Z_BEST_COMPRESSION`, and `Z_DEFAULT_COMPRESSION`.
**$strategy**
Defines the strategy used to tune the compression. The valid values are `Z_DEFAULT_STRATEGY`, `Z_FILTERED` and `Z_HUFFMAN_ONLY`.
**$gz->gzerror**
Returns the *zlib* error message or number for the last operation associated with `$gz`. The return value will be the *zlib* error number when used in a numeric context and the *zlib* error message when used in a string context. The *zlib* error number constants, shown below, are available for use.
```
Z_OK
Z_STREAM_END
Z_ERRNO
Z_STREAM_ERROR
Z_DATA_ERROR
Z_MEM_ERROR
Z_BUF_ERROR
```
**$gzerrno**
The `$gzerrno` scalar holds the error code associated with the most recent *gzip* routine. Note that unlike `gzerror()`, the error is *not* associated with a particular file.
As with `gzerror()` it returns an error number in numeric context and an error message in string context. Unlike `gzerror()` though, the error message will correspond to the *zlib* message when the error is associated with *zlib* itself, or the UNIX error message when it is not (i.e. *zlib* returned `Z_ERRORNO`).
As there is an overlap between the error numbers used by *zlib* and UNIX, `$gzerrno` should only be used to check for the presence of *an* error in numeric context. Use `gzerror()` to check for specific *zlib* errors. The *gzcat* example below shows how the variable can be used safely.
### Examples
Here is an example script which uses the interface. It implements a *gzcat* function.
```
use strict ;
use warnings ;
use Compress::Zlib ;
# use stdin if no files supplied
@ARGV = '-' unless @ARGV ;
foreach my $file (@ARGV) {
my $buffer ;
my $gz = gzopen($file, "rb")
or die "Cannot open $file: $gzerrno\n" ;
print $buffer while $gz->gzread($buffer) > 0 ;
die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
if $gzerrno != Z_STREAM_END ;
$gz->gzclose() ;
}
```
Below is a script which makes use of `gzreadline`. It implements a very simple *grep* like script.
```
use strict ;
use warnings ;
use Compress::Zlib ;
die "Usage: gzgrep pattern [file...]\n"
unless @ARGV >= 1;
my $pattern = shift ;
# use stdin if no files supplied
@ARGV = '-' unless @ARGV ;
foreach my $file (@ARGV) {
my $gz = gzopen($file, "rb")
or die "Cannot open $file: $gzerrno\n" ;
while ($gz->gzreadline($_) > 0) {
print if /$pattern/ ;
}
die "Error reading from $file: $gzerrno\n"
if $gzerrno != Z_STREAM_END ;
$gz->gzclose() ;
}
```
This script, *gzstream*, does the opposite of the *gzcat* script above. It reads from standard input and writes a gzip data stream to standard output.
```
use strict ;
use warnings ;
use Compress::Zlib ;
binmode STDOUT; # gzopen only sets it on the fd
my $gz = gzopen(\*STDOUT, "wb")
or die "Cannot open stdout: $gzerrno\n" ;
while (<>) {
$gz->gzwrite($_)
or die "error writing: $gzerrno\n" ;
}
$gz->gzclose ;
```
###
Compress::Zlib::memGzip
This function is used to create an in-memory gzip file with the minimum possible gzip header (exactly 10 bytes).
```
$dest = Compress::Zlib::memGzip($buffer)
or die "Cannot compress: $gzerrno\n";
```
If successful, it returns the in-memory gzip file. Otherwise it returns `undef` and the `$gzerrno` variable will store the zlib error code.
The `$buffer` parameter can either be a scalar or a scalar reference.
See <IO::Compress::Gzip> for an alternative way to carry out in-memory gzip compression.
###
Compress::Zlib::memGunzip
This function is used to uncompress an in-memory gzip file.
```
$dest = Compress::Zlib::memGunzip($buffer)
or die "Cannot uncompress: $gzerrno\n";
```
If successful, it returns the uncompressed gzip file. Otherwise it returns `undef` and the `$gzerrno` variable will store the zlib error code.
The `$buffer` parameter can either be a scalar or a scalar reference. The contents of the `$buffer` parameter are destroyed after calling this function.
If `$buffer` consists of multiple concatenated gzip data streams only the first will be uncompressed. Use `gunzip` with the `MultiStream` option in the `IO::Uncompress::Gunzip` module if you need to deal with concatenated data streams.
See <IO::Uncompress::Gunzip> for an alternative way to carry out in-memory gzip uncompression.
COMPRESS/UNCOMPRESS
--------------------
Two functions are provided to perform in-memory compression/uncompression of RFC 1950 data streams. They are called `compress` and `uncompress`.
**$dest = compress($source [, $level] ) ;**
Compresses `$source`. If successful it returns the compressed data. Otherwise it returns *undef*.
The source buffer, `$source`, can either be a scalar or a scalar reference.
The `$level` parameter defines the compression level. Valid values are 0 through 9, `Z_NO_COMPRESSION`, `Z_BEST_SPEED`, `Z_BEST_COMPRESSION`, and `Z_DEFAULT_COMPRESSION`. If `$level` is not specified `Z_DEFAULT_COMPRESSION` will be used.
**$dest = uncompress($source) ;**
Uncompresses `$source`. If successful it returns the uncompressed data. Otherwise it returns *undef*.
The source buffer can either be a scalar or a scalar reference.
Please note: the two functions defined above are *not* compatible with the Unix commands of the same name.
See <IO::Deflate> and <IO::Inflate> included with this distribution for an alternative interface for reading/writing RFC 1950 files/buffers.
Deflate Interface
------------------
This section defines an interface that allows in-memory compression using the *deflate* interface provided by zlib.
Here is a definition of the interface available:
###
**($d, $status) = deflateInit( [OPT] )**
Initialises a deflation stream.
It combines the features of the *zlib* functions `deflateInit`, `deflateInit2` and `deflateSetDictionary`.
If successful, it will return the initialised deflation stream, `$d` and `$status` of `Z_OK` in a list context. In scalar context it returns the deflation stream, `$d`, only.
If not successful, the returned deflation stream (`$d`) will be *undef* and `$status` will hold the exact *zlib* error code.
The function optionally takes a number of named options specified as `-Name=>value` pairs. This allows individual options to be tailored without having to specify them all in the parameter list.
For backward compatibility, it is also possible to pass the parameters as a reference to a hash containing the name=>value pairs.
The function takes one optional parameter, a reference to a hash. The contents of the hash allow the deflation interface to be tailored.
Here is a list of the valid options:
**-Level**
Defines the compression level. Valid values are 0 through 9, `Z_NO_COMPRESSION`, `Z_BEST_SPEED`, `Z_BEST_COMPRESSION`, and `Z_DEFAULT_COMPRESSION`.
The default is Z\_DEFAULT\_COMPRESSION.
**-Method**
Defines the compression method. The only valid value at present (and the default) is Z\_DEFLATED.
**-WindowBits**
To create an RFC 1950 data stream, set `WindowBits` to a positive number.
To create an RFC 1951 data stream, set `WindowBits` to `-MAX_WBITS`.
For a full definition of the meaning and valid values for `WindowBits` refer to the *zlib* documentation for *deflateInit2*.
Defaults to MAX\_WBITS.
**-MemLevel**
For a definition of the meaning and valid values for `MemLevel` refer to the *zlib* documentation for *deflateInit2*.
Defaults to MAX\_MEM\_LEVEL.
**-Strategy**
Defines the strategy used to tune the compression. The valid values are `Z_DEFAULT_STRATEGY`, `Z_FILTERED` and `Z_HUFFMAN_ONLY`.
The default is Z\_DEFAULT\_STRATEGY.
**-Dictionary**
When a dictionary is specified *Compress::Zlib* will automatically call `deflateSetDictionary` directly after calling `deflateInit`. The Adler32 value for the dictionary can be obtained by calling the method `$d->dict_adler()`.
The default is no dictionary.
**-Bufsize**
Sets the initial size for the deflation buffer. If the buffer has to be reallocated to increase the size, it will grow in increments of `Bufsize`.
The default is 4096.
Here is an example of using the `deflateInit` optional parameter list to override the default buffer size and compression level. All other options will take their default values.
```
deflateInit( -Bufsize => 300,
-Level => Z_BEST_SPEED ) ;
```
###
**($out, $status) = $d->deflate($buffer)**
Deflates the contents of `$buffer`. The buffer can either be a scalar or a scalar reference. When finished, `$buffer` will be completely processed (assuming there were no errors). If the deflation was successful it returns the deflated output, `$out`, and a status value, `$status`, of `Z_OK`.
On error, `$out` will be *undef* and `$status` will contain the *zlib* error code.
In a scalar context `deflate` will return `$out` only.
As with the *deflate* function in *zlib*, it is not necessarily the case that any output will be produced by this method. So don't rely on the fact that `$out` is empty for an error test.
###
**($out, $status) = $d->flush()** =head2 **($out, $status) = $d->flush($flush\_type)**
Typically used to finish the deflation. Any pending output will be returned via `$out`. `$status` will have a value `Z_OK` if successful.
In a scalar context `flush` will return `$out` only.
Note that flushing can seriously degrade the compression ratio, so it should only be used to terminate a decompression (using `Z_FINISH`) or when you want to create a *full flush point* (using `Z_FULL_FLUSH`).
By default the `flush_type` used is `Z_FINISH`. Other valid values for `flush_type` are `Z_NO_FLUSH`, `Z_PARTIAL_FLUSH`, `Z_SYNC_FLUSH` and `Z_FULL_FLUSH`. It is strongly recommended that you only set the `flush_type` parameter if you fully understand the implications of what it does. See the `zlib` documentation for details.
###
**$status = $d->deflateParams([OPT])**
Change settings for the deflate stream `$d`.
The list of the valid options is shown below. Options not specified will remain unchanged.
**-Level**
Defines the compression level. Valid values are 0 through 9, `Z_NO_COMPRESSION`, `Z_BEST_SPEED`, `Z_BEST_COMPRESSION`, and `Z_DEFAULT_COMPRESSION`.
**-Strategy**
Defines the strategy used to tune the compression. The valid values are `Z_DEFAULT_STRATEGY`, `Z_FILTERED` and `Z_HUFFMAN_ONLY`.
###
**$d->dict\_adler()**
Returns the adler32 value for the dictionary.
###
**$d->msg()**
Returns the last error message generated by zlib.
###
**$d->total\_in()**
Returns the total number of bytes uncompressed bytes input to deflate.
###
**$d->total\_out()**
Returns the total number of compressed bytes output from deflate.
### Example
Here is a trivial example of using `deflate`. It simply reads standard input, deflates it and writes it to standard output.
```
use strict ;
use warnings ;
use Compress::Zlib ;
binmode STDIN;
binmode STDOUT;
my $x = deflateInit()
or die "Cannot create a deflation stream\n" ;
my ($output, $status) ;
while (<>)
{
($output, $status) = $x->deflate($_) ;
$status == Z_OK
or die "deflation failed\n" ;
print $output ;
}
($output, $status) = $x->flush() ;
$status == Z_OK
or die "deflation failed\n" ;
print $output ;
```
Inflate Interface
------------------
This section defines the interface available that allows in-memory uncompression using the *deflate* interface provided by zlib.
Here is a definition of the interface:
###
**($i, $status) = inflateInit()**
Initialises an inflation stream.
In a list context it returns the inflation stream, `$i`, and the *zlib* status code in `$status`. In a scalar context it returns the inflation stream only.
If successful, `$i` will hold the inflation stream and `$status` will be `Z_OK`.
If not successful, `$i` will be *undef* and `$status` will hold the *zlib* error code.
The function optionally takes a number of named options specified as `-Name=>value` pairs. This allows individual options to be tailored without having to specify them all in the parameter list.
For backward compatibility, it is also possible to pass the parameters as a reference to a hash containing the name=>value pairs.
The function takes one optional parameter, a reference to a hash. The contents of the hash allow the deflation interface to be tailored.
Here is a list of the valid options:
**-WindowBits**
To uncompress an RFC 1950 data stream, set `WindowBits` to a positive number.
To uncompress an RFC 1951 data stream, set `WindowBits` to `-MAX_WBITS`.
For a full definition of the meaning and valid values for `WindowBits` refer to the *zlib* documentation for *inflateInit2*.
Defaults to MAX\_WBITS.
**-Bufsize**
Sets the initial size for the inflation buffer. If the buffer has to be reallocated to increase the size, it will grow in increments of `Bufsize`.
Default is 4096.
**-Dictionary**
The default is no dictionary.
Here is an example of using the `inflateInit` optional parameter to override the default buffer size.
```
inflateInit( -Bufsize => 300 ) ;
```
###
**($out, $status) = $i->inflate($buffer)**
Inflates the complete contents of `$buffer`. The buffer can either be a scalar or a scalar reference.
Returns `Z_OK` if successful and `Z_STREAM_END` if the end of the compressed data has been successfully reached. If not successful, `$out` will be *undef* and `$status` will hold the *zlib* error code.
The `$buffer` parameter is modified by `inflate`. On completion it will contain what remains of the input buffer after inflation. This means that `$buffer` will be an empty string when the return status is `Z_OK`. When the return status is `Z_STREAM_END` the `$buffer` parameter will contains what (if anything) was stored in the input buffer after the deflated data stream.
This feature is useful when processing a file format that encapsulates a compressed data stream (e.g. gzip, zip).
###
**$status = $i->inflateSync($buffer)**
Scans `$buffer` until it reaches either a *full flush point* or the end of the buffer.
If a *full flush point* is found, `Z_OK` is returned and `$buffer` will be have all data up to the flush point removed. This can then be passed to the `deflate` method.
Any other return code means that a flush point was not found. If more data is available, `inflateSync` can be called repeatedly with more compressed data until the flush point is found.
###
**$i->dict\_adler()**
Returns the adler32 value for the dictionary.
###
**$i->msg()**
Returns the last error message generated by zlib.
###
**$i->total\_in()**
Returns the total number of bytes compressed bytes input to inflate.
###
**$i->total\_out()**
Returns the total number of uncompressed bytes output from inflate.
### Example
Here is an example of using `inflate`.
```
use strict ;
use warnings ;
use Compress::Zlib ;
my $x = inflateInit()
or die "Cannot create a inflation stream\n" ;
my $input = '' ;
binmode STDIN;
binmode STDOUT;
my ($output, $status) ;
while (read(STDIN, $input, 4096))
{
($output, $status) = $x->inflate(\$input) ;
print $output
if $status == Z_OK or $status == Z_STREAM_END ;
last if $status != Z_OK ;
}
die "inflation failed\n"
unless $status == Z_STREAM_END ;
```
CHECKSUM FUNCTIONS
-------------------
Two functions are provided by *zlib* to calculate checksums. For the Perl interface, the order of the two parameters in both functions has been reversed. This allows both running checksums and one off calculations to be done.
```
$crc = adler32($buffer [,$crc]) ;
$crc = crc32($buffer [,$crc]) ;
```
The buffer parameters can either be a scalar or a scalar reference.
If the $crc parameters is `undef`, the crc value will be reset.
If you have built this module with zlib 1.2.3 or better, two more CRC-related functions are available.
```
$crc = crc32_combine($crc1, $crc2, $len2);
$adler = adler32_combine($adler1, $adler2, $len2);
```
These functions allow checksums to be merged. Refer to the *zlib* documentation for more details.
Misc
----
###
my $version = Compress::Zlib::zlib\_version();
Returns the version of the zlib library.
CONSTANTS
---------
All the *zlib* constants are automatically imported when you make use of *Compress::Zlib*.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
For RFC 1950, 1951 and 1952 see <https://datatracker.ietf.org/doc/html/rfc1950>, <https://datatracker.ietf.org/doc/html/rfc1951> and <https://datatracker.ietf.org/doc/html/rfc1952>
The *zlib* compression library was written by Jean-loup Gailly `[email protected]` and Mark Adler `[email protected]`.
The primary site for the *zlib* compression library is <http://www.zlib.org>.
The primary site for gzip is <http://www.gzip.org>.
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 1995-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Pod::Perldoc::ToText Pod::Perldoc::ToText
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToText - let Perldoc render Pod as plaintext
SYNOPSIS
--------
```
perldoc -o text Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Text as a formatter class.
It supports the following options, which are explained in <Pod::Text>: alt, indent, loose, quotes, sentence, width
For example:
```
perldoc -o text -w indent:5 Some::Modulename
```
CAVEAT
------
This module may change to use a different text formatter class in the future, and this may change what options are supported.
SEE ALSO
---------
<Pod::Text>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl perl perl
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [GETTING HELP](#GETTING-HELP)
+ [Overview](#Overview)
+ [Tutorials](#Tutorials)
+ [Reference Manual](#Reference-Manual)
+ [Internals and C Language Interface](#Internals-and-C-Language-Interface)
+ [History](#History)
+ [Miscellaneous](#Miscellaneous)
+ [Language-Specific](#Language-Specific)
+ [Platform-Specific](#Platform-Specific)
+ [Stubs for Deleted Documents](#Stubs-for-Deleted-Documents)
* [DESCRIPTION](#DESCRIPTION)
* [AVAILABILITY](#AVAILABILITY)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [FILES](#FILES)
* [SEE ALSO](#SEE-ALSO)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [BUGS](#BUGS)
* [NOTES](#NOTES)
NAME
----
perl - The Perl 5 language interpreter
SYNOPSIS
--------
**perl** [ **-sTtuUWX** ] [ **-hv** ] [ **-V**[:*configvar*] ] [ **-cw** ] [ **-d**[**t**][:*debugger*] ] [ **-D**[*number/list*] ] [ **-pna** ] [ **-F***pattern* ] [ **-l**[*octal*] ] [ **-0**[*octal/hexadecimal*] ] [ **-I***dir* ] [ **-m**[**-**]*module* ] [ **-M**[**-**]*'module...'* ] [ **-f** ] [ **-C [*number/list*]** ] [ **-S** ] [ **-x**[*dir*] ] [ **-i**[*extension*] ] [ [**-e**|**-E**] *'command'* ] [ **--** ] [ *programfile* ] [ *argument* ]...
For more information on these options, you can run [`perldoc perlrun`](perlrun).
GETTING HELP
-------------
The *perldoc* program gives you access to all the documentation that comes with Perl. You can get more documentation, tutorials and community support online at <https://www.perl.org/>.
If you're new to Perl, you should start by running [`perldoc perlintro`](perlintro), which is a general intro for beginners and provides some background to help you navigate the rest of Perl's extensive documentation. Run [`perldoc perldoc`](perldoc) to learn more things you can do with *perldoc*.
For ease of access, the Perl manual has been split up into several sections.
### Overview
```
perl Perl overview (this section)
perlintro Perl introduction for beginners
perlrun Perl execution and options
perltoc Perl documentation table of contents
```
### Tutorials
```
perlreftut Perl references short introduction
perldsc Perl data structures intro
perllol Perl data structures: arrays of arrays
perlrequick Perl regular expressions quick start
perlretut Perl regular expressions tutorial
perlootut Perl OO tutorial for beginners
perlperf Perl Performance and Optimization Techniques
perlstyle Perl style guide
perlcheat Perl cheat sheet
perltrap Perl traps for the unwary
perldebtut Perl debugging tutorial
perlfaq Perl frequently asked questions
perlfaq1 General Questions About Perl
perlfaq2 Obtaining and Learning about Perl
perlfaq3 Programming Tools
perlfaq4 Data Manipulation
perlfaq5 Files and Formats
perlfaq6 Regexes
perlfaq7 Perl Language Issues
perlfaq8 System Interaction
perlfaq9 Networking
```
###
Reference Manual
```
perlsyn Perl syntax
perldata Perl data structures
perlop Perl operators and precedence
perlsub Perl subroutines
perlfunc Perl built-in functions
perlopentut Perl open() tutorial
perlpacktut Perl pack() and unpack() tutorial
perlpod Perl plain old documentation
perlpodspec Perl plain old documentation format specification
perldocstyle Perl style guide for core docs
perlpodstyle Perl POD style guide
perldiag Perl diagnostic messages
perldeprecation Perl deprecations
perllexwarn Perl warnings and their control
perldebug Perl debugging
perlvar Perl predefined variables
perlre Perl regular expressions, the rest of the story
perlrebackslash Perl regular expression backslash sequences
perlrecharclass Perl regular expression character classes
perlreref Perl regular expressions quick reference
perlref Perl references, the rest of the story
perlform Perl formats
perlobj Perl objects
perltie Perl objects hidden behind simple variables
perldbmfilter Perl DBM filters
perlipc Perl interprocess communication
perlfork Perl fork() information
perlnumber Perl number semantics
perlthrtut Perl threads tutorial
perlport Perl portability guide
perllocale Perl locale support
perluniintro Perl Unicode introduction
perlunicode Perl Unicode support
perlunicook Perl Unicode cookbook
perlunifaq Perl Unicode FAQ
perluniprops Index of Unicode properties in Perl
perlunitut Perl Unicode tutorial
perlebcdic Considerations for running Perl on EBCDIC platforms
perlsec Perl security
perlsecpolicy Perl security report handling policy
perlmod Perl modules: how they work
perlmodlib Perl modules: how to write and use
perlmodstyle Perl modules: how to write modules with style
perlmodinstall Perl modules: how to install from CPAN
perlnewmod Perl modules: preparing a new module for distribution
perlpragma Perl modules: writing a user pragma
perlutil utilities packaged with the Perl distribution
perlfilter Perl source filters
perldtrace Perl's support for DTrace
perlglossary Perl Glossary
```
###
Internals and C Language Interface
```
perlembed Perl ways to embed perl in your C or C++ application
perldebguts Perl debugging guts and tips
perlxstut Perl XS tutorial
perlxs Perl XS application programming interface
perlxstypemap Perl XS C/Perl type conversion tools
perlclib Internal replacements for standard C library functions
perlguts Perl internal functions for those doing extensions
perlcall Perl calling conventions from C
perlmroapi Perl method resolution plugin interface
perlreapi Perl regular expression plugin interface
perlreguts Perl regular expression engine internals
perlapi Perl API listing (autogenerated)
perlintern Perl internal functions (autogenerated)
perliol C API for Perl's implementation of IO in Layers
perlapio Perl internal IO abstraction interface
perlhack Perl hackers guide
perlsource Guide to the Perl source tree
perlinterp Overview of the Perl interpreter source and how it works
perlhacktut Walk through the creation of a simple C code patch
perlhacktips Tips for Perl core C code hacking
perlpolicy Perl development policies
perlgov Perl Rules of Governance
perlgit Using git with the Perl repository
```
### History
```
perlhist Perl history records
perldelta Perl changes since previous version
perl5341delta Perl changes in version 5.34.1
perl5340delta Perl changes in version 5.34.0
perl5321delta Perl changes in version 5.32.1
perl5320delta Perl changes in version 5.32.0
perl5303delta Perl changes in version 5.30.3
perl5302delta Perl changes in version 5.30.2
perl5301delta Perl changes in version 5.30.1
perl5300delta Perl changes in version 5.30.0
perl5283delta Perl changes in version 5.28.3
perl5282delta Perl changes in version 5.28.2
perl5281delta Perl changes in version 5.28.1
perl5280delta Perl changes in version 5.28.0
perl5263delta Perl changes in version 5.26.3
perl5262delta Perl changes in version 5.26.2
perl5261delta Perl changes in version 5.26.1
perl5260delta Perl changes in version 5.26.0
perl5244delta Perl changes in version 5.24.4
perl5243delta Perl changes in version 5.24.3
perl5242delta Perl changes in version 5.24.2
perl5241delta Perl changes in version 5.24.1
perl5240delta Perl changes in version 5.24.0
perl5224delta Perl changes in version 5.22.4
perl5223delta Perl changes in version 5.22.3
perl5222delta Perl changes in version 5.22.2
perl5221delta Perl changes in version 5.22.1
perl5220delta Perl changes in version 5.22.0
perl5203delta Perl changes in version 5.20.3
perl5202delta Perl changes in version 5.20.2
perl5201delta Perl changes in version 5.20.1
perl5200delta Perl changes in version 5.20.0
perl5184delta Perl changes in version 5.18.4
perl5182delta Perl changes in version 5.18.2
perl5181delta Perl changes in version 5.18.1
perl5180delta Perl changes in version 5.18.0
perl5163delta Perl changes in version 5.16.3
perl5162delta Perl changes in version 5.16.2
perl5161delta Perl changes in version 5.16.1
perl5160delta Perl changes in version 5.16.0
perl5144delta Perl changes in version 5.14.4
perl5143delta Perl changes in version 5.14.3
perl5142delta Perl changes in version 5.14.2
perl5141delta Perl changes in version 5.14.1
perl5140delta Perl changes in version 5.14.0
perl5125delta Perl changes in version 5.12.5
perl5124delta Perl changes in version 5.12.4
perl5123delta Perl changes in version 5.12.3
perl5122delta Perl changes in version 5.12.2
perl5121delta Perl changes in version 5.12.1
perl5120delta Perl changes in version 5.12.0
perl5101delta Perl changes in version 5.10.1
perl5100delta Perl changes in version 5.10.0
perl589delta Perl changes in version 5.8.9
perl588delta Perl changes in version 5.8.8
perl587delta Perl changes in version 5.8.7
perl586delta Perl changes in version 5.8.6
perl585delta Perl changes in version 5.8.5
perl584delta Perl changes in version 5.8.4
perl583delta Perl changes in version 5.8.3
perl582delta Perl changes in version 5.8.2
perl581delta Perl changes in version 5.8.1
perl58delta Perl changes in version 5.8.0
perl561delta Perl changes in version 5.6.1
perl56delta Perl changes in version 5.6
perl5005delta Perl changes in version 5.005
perl5004delta Perl changes in version 5.004
```
### Miscellaneous
```
perlbook Perl book information
perlcommunity Perl community information
perldoc Look up Perl documentation in Pod format
perlexperiment A listing of experimental features in Perl
perlartistic Perl Artistic License
perlgpl GNU General Public License
```
###
Language-Specific
```
perlcn Perl for Simplified Chinese (in UTF-8)
perljp Perl for Japanese (in EUC-JP)
perlko Perl for Korean (in EUC-KR)
perltw Perl for Traditional Chinese (in Big5)
```
###
Platform-Specific
```
perlaix Perl notes for AIX
perlamiga Perl notes for AmigaOS
perlandroid Perl notes for Android
perlbs2000 Perl notes for POSIX-BC BS2000
perlcygwin Perl notes for Cygwin
perlfreebsd Perl notes for FreeBSD
perlhaiku Perl notes for Haiku
perlhpux Perl notes for HP-UX
perlhurd Perl notes for Hurd
perlirix Perl notes for Irix
perllinux Perl notes for Linux
perlmacosx Perl notes for Mac OS X
perlopenbsd Perl notes for OpenBSD
perlos2 Perl notes for OS/2
perlos390 Perl notes for OS/390
perlos400 Perl notes for OS/400
perlplan9 Perl notes for Plan 9
perlqnx Perl notes for QNX
perlriscos Perl notes for RISC OS
perlsolaris Perl notes for Solaris
perlsynology Perl notes for Synology
perltru64 Perl notes for Tru64
perlvms Perl notes for VMS
perlvos Perl notes for Stratus VOS
perlwin32 Perl notes for Windows
```
###
Stubs for Deleted Documents
```
perlboot
perlbot
perlrepository
perltodo
perltooc
perltoot
```
On a Unix-like system, these documentation files will usually also be available as manpages for use with the *man* program.
Some documentation is not available as man pages, so if a cross-reference is not found by man, try it with <perldoc>. Perldoc can also take you directly to documentation for functions (with the **-f** switch). See `perldoc --help` (or [`perldoc perldoc`](perldoc) or `man perldoc`) for other helpful options <perldoc> has to offer.
In general, if something strange has gone wrong with your program and you're not sure where you should look for help, try making your code comply with **use <strict>** and **use <warnings>**. These will often point out exactly where the trouble is.
DESCRIPTION
-----------
Perl officially stands for Practical Extraction and Report Language, except when it doesn't.
Perl was originally a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It quickly became a good language for many system management tasks. Over the years, Perl has grown into a general-purpose programming language. It's widely used for everything from quick "one-liners" to full-scale application development.
The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). It combines (in the author's opinion, anyway) some of the best features of **sed**, **awk**, and **sh**, making it familiar and easy to use for Unix users to whip up quick solutions to annoying problems. Its general-purpose programming facilities support procedural, functional, and object-oriented programming paradigms, making Perl a comfortable language for the long haul on major projects, whatever your bent.
Perl's roots in text processing haven't been forgotten over the years. It still boasts some of the most powerful regular expressions to be found anywhere, and its support for Unicode text is world-class. It handles all kinds of structured text, too, through an extensive collection of extensions. Those libraries, collected in the CPAN, provide ready-made solutions to an astounding array of problems. When they haven't set the standard themselves, they steal from the best -- just like Perl itself.
AVAILABILITY
------------
Perl is available for most operating systems, including virtually all Unix-like platforms. See ["Supported Platforms" in perlport](perlport#Supported-Platforms) for a listing.
ENVIRONMENT
-----------
See ["ENVIRONMENT" in perlrun](perlrun#ENVIRONMENT).
AUTHOR
------
Larry Wall <[email protected]>, with the help of oodles of other folks.
If your Perl success stories and testimonials may be of help to others who wish to advocate the use of Perl in their applications, or if you wish to simply express your gratitude to Larry and the Perl developers, please write to [email protected] .
FILES
-----
```
"@INC" locations of perl libraries
```
"@INC" above is a reference to the built-in variable of the same name; see <perlvar> for more information.
SEE ALSO
---------
```
https://www.perl.org/ the Perl homepage
https://www.perl.com/ Perl articles
https://www.cpan.org/ the Comprehensive Perl Archive
https://www.pm.org/ the Perl Mongers
```
DIAGNOSTICS
-----------
Using the `use <strict>` pragma ensures that all variables are properly declared and prevents other misuses of legacy Perl features. These are enabled by default within the scope of `[use v5.12](perlfunc#use-VERSION)` (or higher).
The `use <warnings>` pragma produces some lovely diagnostics. It is enabled by default when you say `use v5.35` (or higher). One can also use the **-w** flag, but its use is normally discouraged, because it gets applied to all executed Perl code, including that not under your control.
See <perldiag> for explanations of all Perl's diagnostics. The `use <diagnostics>` pragma automatically turns Perl's normally terse warnings and errors into these longer forms.
Compilation errors will tell you the line number of the error, with an indication of the next token or token type that was to be examined. (In a script passed to Perl via **-e** switches, each **-e** is counted as one line.)
Setuid scripts have additional constraints that can produce error messages such as "Insecure dependency". See <perlsec>.
Did we mention that you should definitely consider using the **use <warnings>** pragma?
BUGS
----
The behavior implied by the **use <warnings>** pragma is not mandatory.
Perl is at the mercy of your machine's definitions of various operations such as type casting, atof(), and floating-point output with sprintf().
If your stdio requires a seek or eof between reads and writes on a particular stream, so does Perl. (This doesn't apply to sysread() and syswrite().)
While none of the built-in data types have any arbitrary size limits (apart from memory size), there are still a few arbitrary limits: a given variable name may not be longer than 251 characters. Line numbers displayed by diagnostics are internally stored as short integers, so they are limited to a maximum of 65535 (higher numbers usually being affected by wraparound).
You may submit your bug reports (be sure to include full configuration information as output by the myconfig program in the perl source tree, or by `perl -V`) to <https://github.com/Perl/perl5/issues>.
Perl actually stands for Pathologically Eclectic Rubbish Lister, but don't tell anyone I said that.
NOTES
-----
The Perl motto is "There's more than one way to do it." Divining how many more is left as an exercise to the reader.
The three principal virtues of a programmer are Laziness, Impatience, and Hubris. See the Camel Book for why.
perl IO::Uncompress::AnyUncompress IO::Uncompress::AnyUncompress
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [anyuncompress $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#anyuncompress-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [read](#read)
+ [read](#read1)
+ [getline](#getline)
+ [getc](#getc)
+ [ungetc](#ungetc)
+ [getHeaderInfo](#getHeaderInfo)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [nextStream](#nextStream)
+ [trailingData](#trailingData)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::AnyUncompress - Uncompress gzip, zip, bzip2, zstd, xz, lzma, lzip, lzf or lzop file/buffer
SYNOPSIS
--------
```
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
my $status = anyuncompress $input => $output [,OPTS]
or die "anyuncompress failed: $AnyUncompressError\n";
my $z = IO::Uncompress::AnyUncompress->new( $input [OPTS] )
or die "anyuncompress failed: $AnyUncompressError\n";
$status = $z->read($buffer)
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$line = $z->getline()
$char = $z->getc()
$char = $z->ungetc()
$char = $z->opened()
$data = $z->trailingData()
$status = $z->nextStream()
$data = $z->getHeaderInfo()
$z->tell()
$z->seek($position, $whence)
$z->binmode()
$z->fileno()
$z->eof()
$z->close()
$AnyUncompressError ;
# IO::File mode
<$z>
read($z, $buffer);
read($z, $buffer, $length);
read($z, $buffer, $length, $offset);
tell($z)
seek($z, $position, $whence)
binmode($z)
fileno($z)
eof($z)
close($z)
```
DESCRIPTION
-----------
This module provides a Perl interface that allows the reading of files/buffers that have been compressed with a variety of compression libraries.
The formats supported are:
RFC 1950
RFC 1951 (optionally)
gzip (RFC 1952) zip
zstd (Zstandard) bzip2 lzop lzf lzma lzip xz The module will auto-detect which, if any, of the supported compression formats is being used.
Functional Interface
---------------------
A top-level function, `anyuncompress`, is provided to carry out "one-shot" uncompression between buffers and/or files. For finer control over the uncompression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
anyuncompress $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "anyuncompress failed: $AnyUncompressError\n";
```
The functional interface needs Perl5.005 or better.
###
anyuncompress $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`anyuncompress` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the compressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is uncompressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `anyuncompress` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the uncompressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the uncompressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the uncompressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the uncompressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the uncompressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `anyuncompress` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple compressed files/buffers and `$output_filename_or_reference` is a single file/buffer, after uncompression `$output_filename_or_reference` will contain a concatenation of all the uncompressed data from each of the input files/buffers.
###
Optional Parameters
The optional parameters for the one-shot function `anyuncompress` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `anyuncompress` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `anyuncompress` has completed.
This parameter defaults to 0.
`BinModeOut => 0|1`
This option is now a no-op. All files will be written in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all uncompressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any uncompressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any uncompressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any uncompressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all uncompressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any uncompressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all uncompressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any uncompressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any uncompressed data is output.
Defaults to 0.
`MultiStream => 0|1`
If the input file/buffer contains multiple compressed data streams, this option will uncompress the whole lot as a single data stream.
Defaults to 0.
`TrailingData => $scalar`
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option.
### Examples
To read the contents of the file `file1.txt.Compressed` and write the uncompressed data to the file `file1.txt`.
```
use strict ;
use warnings ;
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
my $input = "file1.txt.Compressed";
my $output = "file1.txt";
anyuncompress $input => $output
or die "anyuncompress failed: $AnyUncompressError\n";
```
To read from an existing Perl filehandle, `$input`, and write the uncompressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.Compressed" )
or die "Cannot open 'file1.txt.Compressed': $!\n" ;
my $buffer ;
anyuncompress $input => \$buffer
or die "anyuncompress failed: $AnyUncompressError\n";
```
To uncompress all files in the directory "/my/home" that match "\*.txt.Compressed" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
anyuncompress '</my/home/*.txt.Compressed>' => '</my/home/#1.txt>'
or die "anyuncompress failed: $AnyUncompressError\n";
```
and if you want to compress each file one at a time, this will do the trick
```
use strict ;
use warnings ;
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
for my $input ( glob "/my/home/*.txt.Compressed" )
{
my $output = $input;
$output =~ s/.Compressed// ;
anyuncompress $input => $output
or die "Error compressing '$input': $AnyUncompressError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::AnyUncompress is shown below
```
my $z = IO::Uncompress::AnyUncompress->new( $input [OPTS] )
or die "IO::Uncompress::AnyUncompress failed: $AnyUncompressError\n";
```
Returns an `IO::Uncompress::AnyUncompress` object on success and undef on failure. The variable `$AnyUncompressError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::AnyUncompress can be used exactly like an <IO::File> filehandle. This means that all normal input file operations can be carried out with `$z`. For example, to read a line from a compressed file/buffer you can use either of these forms
```
$line = $z->getline();
$line = <$z>;
```
The mandatory parameter `$input` is used to determine the source of the compressed data. This parameter can take one of three forms.
A filename If the `$input` parameter is a scalar, it is assumed to be a filename. This file will be opened for reading and the compressed data will be read from it.
A filehandle If the `$input` parameter is a filehandle, the compressed data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input` is a scalar reference, the compressed data will be read from `$$input`.
###
Constructor Options
The option names defined below are case insensitive and can be optionally prefixed by a '-'. So all of the following are valid
```
-AutoClose
-autoclose
AUTOCLOSE
autoclose
```
OPTS is a combination of the following options:
`AutoClose => 0|1`
This option is only valid when the `$input` parameter is a filehandle. If specified, and the value is true, it will result in the file being closed once either the `close` method is called or the IO::Uncompress::AnyUncompress object is destroyed.
This parameter defaults to 0.
`MultiStream => 0|1`
Allows multiple concatenated compressed streams to be treated as a single compressed stream. Decompression will stop once either the end of the file/buffer is reached, an error is encountered (premature eof, corrupt compressed data) or the end of a stream is not immediately followed by the start of another stream.
This parameter defaults to 0.
`Prime => $string`
This option will uncompress the contents of `$string` before processing the input file/buffer.
This option can be useful when the compressed data is embedded in another file/data structure and it is not possible to work out where the compressed data begins without having to read the first few bytes. If this is the case, the uncompression can be *primed* with these bytes using this option.
`Transparent => 0|1`
If this option is set and the input file/buffer is not compressed data, the module will allow reading of it anyway.
In addition, if the input file/buffer does contain compressed data and there is non-compressed data immediately following it, setting this option will make this module treat the whole file/buffer as a single data stream.
This option defaults to 1.
`BlockSize => $num`
When reading the compressed input data, IO::Uncompress::AnyUncompress will read it in blocks of `$num` bytes.
This option defaults to 4096.
`InputLength => $size`
When present this option will limit the number of compressed bytes read from the input file/buffer to `$size`. This option can be used in the situation where there is useful data directly after the compressed data stream and you know beforehand the exact length of the compressed data stream.
This option is mostly used when reading from a filehandle, in which case the file pointer will be left pointing to the first byte directly after the compressed data stream.
This option defaults to off.
`Append => 0|1`
This option controls what the `read` method does with uncompressed data.
If set to 1, all uncompressed data will be appended to the output parameter of the `read` method.
If set to 0, the contents of the output parameter of the `read` method will be overwritten by the uncompressed data.
Defaults to 0.
`Strict => 0|1`
This option controls whether the extra checks defined below are used when carrying out the decompression. When Strict is on, the extra tests are carried out, when Strict is off they are not.
The default for this option is off.
`RawInflate => 0|1`
When auto-detecting the compressed format, try to test for raw-deflate (RFC 1951) content using the `IO::Uncompress::RawInflate` module.
The reason this is not default behaviour is because RFC 1951 content can only be detected by attempting to uncompress it. This process is error prone and can result is false positives.
Defaults to 0.
`UnLzma => 0|1`
When auto-detecting the compressed format, try to test for lzma\_alone content using the `IO::Uncompress::UnLzma` module.
The reason this is not default behaviour is because lzma\_alone content can only be detected by attempting to uncompress it. This process is error prone and can result is false positives.
Defaults to 0.
### Examples
TODO
Methods
-------
### read
Usage is
```
$status = $z->read($buffer)
```
Reads a block of compressed data (the size of the compressed block is determined by the `Buffer` option in the constructor), uncompresses it and writes any uncompressed data into `$buffer`. If the `Append` parameter is set in the constructor, the uncompressed data will be appended to the `$buffer` parameter. Otherwise `$buffer` will be overwritten.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### read
Usage is
```
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$status = read($z, $buffer, $length)
$status = read($z, $buffer, $length, $offset)
```
Attempt to read `$length` bytes of uncompressed data into `$buffer`.
The main difference between this form of the `read` method and the previous one, is that this one will attempt to return *exactly* `$length` bytes. The only circumstances that this function will not is if end-of-file or an IO error is encountered.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### getline
Usage is
```
$line = $z->getline()
$line = <$z>
```
Reads a single line.
This method fully supports the use of the variable `$/` (or `$INPUT_RECORD_SEPARATOR` or `$RS` when `English` is in use) to determine what constitutes an end of line. Paragraph mode, record mode and file slurp mode are all supported.
### getc
Usage is
```
$char = $z->getc()
```
Read a single character.
### ungetc
Usage is
```
$char = $z->ungetc($string)
```
### getHeaderInfo
Usage is
```
$hdr = $z->getHeaderInfo();
@hdrs = $z->getHeaderInfo();
```
This method returns either a hash reference (in scalar context) or a list or hash references (in array context) that contains information about each of the header fields in the compressed data stream(s).
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the end of the compressed input stream has been reached.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the input file/buffer. It is a fatal error to attempt to seek backward.
Note that the implementation of `seek` in this module does not provide true random access to a compressed file/buffer. It works by uncompressing data from the current offset in the file/buffer until it reaches the uncompressed offset specified in the parameters to `seek`. For very small files this may be acceptable behaviour. For large files it may cause an unacceptable delay.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
Returns the current uncompressed line number. If `EXPR` is present it has the effect of setting the line number. Note that setting the line number does not change the current position within the file/buffer being read.
The contents of `$/` are used to determine what constitutes a line terminator.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Uncompress::AnyUncompress object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Uncompress::AnyUncompress object was created, and the object is associated with a file, the underlying file will also be closed.
### nextStream
Usage is
```
my $status = $z->nextStream();
```
Skips to the next compressed data stream in the input file/buffer. If a new compressed data stream is found, the eof marker will be cleared and `$.` will be reset to 0.
Returns 1 if a new stream was found, 0 if none was found, and -1 if an error was encountered.
### trailingData
Usage is
```
my $data = $z->trailingData();
```
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete. It only makes sense to call this method once the end of the compressed data stream has been encountered.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option in the constructor.
Importing
---------
No symbolic constants are required by IO::Uncompress::AnyUncompress at present.
:all Imports `anyuncompress` and `$AnyUncompressError`. Same as doing this
```
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError) ;
```
EXAMPLES
--------
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Test2::Util::ExternalMeta Test2::Util::ExternalMeta
=========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [WHERE IS THE DATA STORED?](#WHERE-IS-THE-DATA-STORED?)
* [EXPORTS](#EXPORTS)
* [META-KEY RESTRICTIONS](#META-KEY-RESTRICTIONS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Util::ExternalMeta - Allow third party tools to safely attach meta-data to your instances.
DESCRIPTION
-----------
This package lets you define a clear, and consistent way to allow third party tools to attach meta-data to your instances. If your object consumes this package, and imports its methods, then third party meta-data has a safe place to live.
SYNOPSIS
--------
```
package My::Object;
use strict;
use warnings;
use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/;
...
```
Now to use it:
```
my $inst = My::Object->new;
$inst->set_meta(foo => 'bar');
my $val = $inst->get_meta('foo');
```
WHERE IS THE DATA STORED?
--------------------------
This package assumes your instances are blessed hashrefs, it will not work if that is not true. It will store all meta-data in the `_meta` key on your objects hash. If your object makes use of the `_meta` key in its underlying hash, then there is a conflict and you cannot use this package.
EXPORTS
-------
$val = $obj->meta($key)
$val = $obj->meta($key, $default) This will get the value for a specified meta `$key`. Normally this will return `undef` when there is no value for the `$key`, however you can specify a `$default` value to set when no value is already set.
$val = $obj->get\_meta($key) This will get the value for a specified meta `$key`. This does not have the `$default` overhead that `meta()` does.
$val = $obj->delete\_meta($key) This will remove the value of a specified meta `$key`. The old `$val` will be returned.
$obj->set\_meta($key, $val) Set the value of a specified meta `$key`.
META-KEY RESTRICTIONS
----------------------
Meta keys must be defined, and must be true when used as a boolean. Keys may not be references. You are free to stringify a reference `"$ref"` for use as a key, but this package will not stringify it for you.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl perlunicook perlunicook
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
+ [℞ 0: Standard preamble](#%E2%84%9E-0:-Standard-preamble)
+ [℞ 1: Generic Unicode-savvy filter](#%E2%84%9E-1:-Generic-Unicode-savvy-filter)
+ [℞ 2: Fine-tuning Unicode warnings](#%E2%84%9E-2:-Fine-tuning-Unicode-warnings)
+ [℞ 3: Declare source in utf8 for identifiers and literals](#%E2%84%9E-3:-Declare-source-in-utf8-for-identifiers-and-literals)
+ [℞ 4: Characters and their numbers](#%E2%84%9E-4:-Characters-and-their-numbers)
+ [℞ 5: Unicode literals by character number](#%E2%84%9E-5:-Unicode-literals-by-character-number)
+ [℞ 6: Get character name by number](#%E2%84%9E-6:-Get-character-name-by-number)
+ [℞ 7: Get character number by name](#%E2%84%9E-7:-Get-character-number-by-name)
+ [℞ 8: Unicode named characters](#%E2%84%9E-8:-Unicode-named-characters)
+ [℞ 9: Unicode named sequences](#%E2%84%9E-9:-Unicode-named-sequences)
+ [℞ 10: Custom named characters](#%E2%84%9E-10:-Custom-named-characters)
+ [℞ 11: Names of CJK codepoints](#%E2%84%9E-11:-Names-of-CJK-codepoints)
+ [℞ 12: Explicit encode/decode](#%E2%84%9E-12:-Explicit-encode/decode)
+ [℞ 13: Decode program arguments as utf8](#%E2%84%9E-13:-Decode-program-arguments-as-utf8)
+ [℞ 14: Decode program arguments as locale encoding](#%E2%84%9E-14:-Decode-program-arguments-as-locale-encoding)
+ [℞ 15: Declare STD{IN,OUT,ERR} to be utf8](#%E2%84%9E-15:-Declare-STD%7BIN,OUT,ERR%7D-to-be-utf8)
+ [℞ 16: Declare STD{IN,OUT,ERR} to be in locale encoding](#%E2%84%9E-16:-Declare-STD%7BIN,OUT,ERR%7D-to-be-in-locale-encoding)
+ [℞ 17: Make file I/O default to utf8](#%E2%84%9E-17:-Make-file-I/O-default-to-utf8)
+ [℞ 18: Make all I/O and args default to utf8](#%E2%84%9E-18:-Make-all-I/O-and-args-default-to-utf8)
+ [℞ 19: Open file with specific encoding](#%E2%84%9E-19:-Open-file-with-specific-encoding)
+ [℞ 20: Unicode casing](#%E2%84%9E-20:-Unicode-casing)
+ [℞ 21: Unicode case-insensitive comparisons](#%E2%84%9E-21:-Unicode-case-insensitive-comparisons)
+ [℞ 22: Match Unicode linebreak sequence in regex](#%E2%84%9E-22:-Match-Unicode-linebreak-sequence-in-regex)
+ [℞ 23: Get character category](#%E2%84%9E-23:-Get-character-category)
+ [℞ 24: Disabling Unicode-awareness in builtin charclasses](#%E2%84%9E-24:-Disabling-Unicode-awareness-in-builtin-charclasses)
+ [℞ 25: Match Unicode properties in regex with \p, \P](#%E2%84%9E-25:-Match-Unicode-properties-in-regex-with-%5Cp,-%5CP)
+ [℞ 26: Custom character properties](#%E2%84%9E-26:-Custom-character-properties)
+ [℞ 27: Unicode normalization](#%E2%84%9E-27:-Unicode-normalization)
+ [℞ 28: Convert non-ASCII Unicode numerics](#%E2%84%9E-28:-Convert-non-ASCII-Unicode-numerics)
+ [℞ 29: Match Unicode grapheme cluster in regex](#%E2%84%9E-29:-Match-Unicode-grapheme-cluster-in-regex)
+ [℞ 30: Extract by grapheme instead of by codepoint (regex)](#%E2%84%9E-30:-Extract-by-grapheme-instead-of-by-codepoint-(regex))
+ [℞ 31: Extract by grapheme instead of by codepoint (substr)](#%E2%84%9E-31:-Extract-by-grapheme-instead-of-by-codepoint-(substr))
+ [℞ 32: Reverse string by grapheme](#%E2%84%9E-32:-Reverse-string-by-grapheme)
+ [℞ 33: String length in graphemes](#%E2%84%9E-33:-String-length-in-graphemes)
+ [℞ 34: Unicode column-width for printing](#%E2%84%9E-34:-Unicode-column-width-for-printing)
+ [℞ 35: Unicode collation](#%E2%84%9E-35:-Unicode-collation)
+ [℞ 36: Case- and accent-insensitive Unicode sort](#%E2%84%9E-36:-Case-and-accent-insensitive-Unicode-sort)
+ [℞ 37: Unicode locale collation](#%E2%84%9E-37:-Unicode-locale-collation)
+ [℞ 38: Making cmp work on text instead of codepoints](#%E2%84%9E-38:-Making-cmp-work-on-text-instead-of-codepoints)
+ [℞ 39: Case- and accent-insensitive comparisons](#%E2%84%9E-39:-Case-and-accent-insensitive-comparisons)
+ [℞ 40: Case- and accent-insensitive locale comparisons](#%E2%84%9E-40:-Case-and-accent-insensitive-locale-comparisons)
+ [℞ 41: Unicode linebreaking](#%E2%84%9E-41:-Unicode-linebreaking)
+ [℞ 42: Unicode text in DBM hashes, the tedious way](#%E2%84%9E-42:-Unicode-text-in-DBM-hashes,-the-tedious-way)
+ [℞ 43: Unicode text in DBM hashes, the easy way](#%E2%84%9E-43:-Unicode-text-in-DBM-hashes,-the-easy-way)
+ [℞ 44: PROGRAM: Demo of Unicode collation and printing](#%E2%84%9E-44:-PROGRAM:-Demo-of-Unicode-collation-and-printing)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENCE](#COPYRIGHT-AND-LICENCE)
* [REVISION HISTORY](#REVISION-HISTORY)
NAME
----
perlunicook - cookbookish examples of handling Unicode in Perl
DESCRIPTION
-----------
This manpage contains short recipes demonstrating how to handle common Unicode operations in Perl, plus one complete program at the end. Any undeclared variables in individual recipes are assumed to have a previous appropriate value in them.
EXAMPLES
--------
###
℞ 0: Standard preamble
Unless otherwise notes, all examples below require this standard preamble to work correctly, with the `#!` adjusted to work on your system:
```
#!/usr/bin/env perl
use v5.36; # or later to get "unicode_strings" feature,
# plus strict, warnings
use utf8; # so literals and identifiers can be in UTF-8
use warnings qw(FATAL utf8); # fatalize encoding glitches
use open qw(:std :encoding(UTF-8)); # undeclared streams in UTF-8
use charnames qw(:full :short); # unneeded in v5.16
```
This *does* make even Unix programmers `binmode` your binary streams, or open them with `:raw`, but that's the only way to get at them portably anyway.
**WARNING**: `use autodie` (pre 2.26) and `use open` do not get along with each other.
###
℞ 1: Generic Unicode-savvy filter
Always decompose on the way in, then recompose on the way out.
```
use Unicode::Normalize;
while (<>) {
$_ = NFD($_); # decompose + reorder canonically
...
} continue {
print NFC($_); # recompose (where possible) + reorder canonically
}
```
###
℞ 2: Fine-tuning Unicode warnings
As of v5.14, Perl distinguishes three subclasses of UTF‑8 warnings.
```
use v5.14; # subwarnings unavailable any earlier
no warnings "nonchar"; # the 66 forbidden non-characters
no warnings "surrogate"; # UTF-16/CESU-8 nonsense
no warnings "non_unicode"; # for codepoints over 0x10_FFFF
```
###
℞ 3: Declare source in utf8 for identifiers and literals
Without the all-critical `use utf8` declaration, putting UTF‑8 in your literals and identifiers won’t work right. If you used the standard preamble just given above, this already happened. If you did, you can do things like this:
```
use utf8;
my $measure = "Ångström";
my @μsoft = qw( cp852 cp1251 cp1252 );
my @ὑπέρμεγας = qw( ὑπέρ μεγας );
my @鯉 = qw( koi8-f koi8-u koi8-r );
my $motto = "👪 💗 🐪"; # FAMILY, GROWING HEART, DROMEDARY CAMEL
```
If you forget `use utf8`, high bytes will be misunderstood as separate characters, and nothing will work right.
###
℞ 4: Characters and their numbers
The `ord` and `chr` functions work transparently on all codepoints, not just on ASCII alone — nor in fact, not even just on Unicode alone.
```
# ASCII characters
ord("A")
chr(65)
# characters from the Basic Multilingual Plane
ord("Σ")
chr(0x3A3)
# beyond the BMP
ord("𝑛") # MATHEMATICAL ITALIC SMALL N
chr(0x1D45B)
# beyond Unicode! (up to MAXINT)
ord("\x{20_0000}")
chr(0x20_0000)
```
###
℞ 5: Unicode literals by character number
In an interpolated literal, whether a double-quoted string or a regex, you may specify a character by its number using the `\x{*HHHHHH*}` escape.
```
String: "\x{3a3}"
Regex: /\x{3a3}/
String: "\x{1d45b}"
Regex: /\x{1d45b}/
# even non-BMP ranges in regex work fine
/[\x{1D434}-\x{1D467}]/
```
###
℞ 6: Get character name by number
```
use charnames ();
my $name = charnames::viacode(0x03A3);
```
###
℞ 7: Get character number by name
```
use charnames ();
my $number = charnames::vianame("GREEK CAPITAL LETTER SIGMA");
```
###
℞ 8: Unicode named characters
Use the `\N{*charname*}` notation to get the character by that name for use in interpolated literals (double-quoted strings and regexes). In v5.16, there is an implicit
```
use charnames qw(:full :short);
```
But prior to v5.16, you must be explicit about which set of charnames you want. The `:full` names are the official Unicode character name, alias, or sequence, which all share a namespace.
```
use charnames qw(:full :short latin greek);
"\N{MATHEMATICAL ITALIC SMALL N}" # :full
"\N{GREEK CAPITAL LETTER SIGMA}" # :full
```
Anything else is a Perl-specific convenience abbreviation. Specify one or more scripts by names if you want short names that are script-specific.
```
"\N{Greek:Sigma}" # :short
"\N{ae}" # latin
"\N{epsilon}" # greek
```
The v5.16 release also supports a `:loose` import for loose matching of character names, which works just like loose matching of property names: that is, it disregards case, whitespace, and underscores:
```
"\N{euro sign}" # :loose (from v5.16)
```
Starting in v5.32, you can also use
```
qr/\p{name=euro sign}/
```
to get official Unicode named characters in regular expressions. Loose matching is always done for these.
###
℞ 9: Unicode named sequences
These look just like character names but return multiple codepoints. Notice the `%vx` vector-print functionality in `printf`.
```
use charnames qw(:full);
my $seq = "\N{LATIN CAPITAL LETTER A WITH MACRON AND GRAVE}";
printf "U+%v04X\n", $seq;
U+0100.0300
```
###
℞ 10: Custom named characters
Use `:alias` to give your own lexically scoped nicknames to existing characters, or even to give unnamed private-use characters useful names.
```
use charnames ":full", ":alias" => {
ecute => "LATIN SMALL LETTER E WITH ACUTE",
"APPLE LOGO" => 0xF8FF, # private use character
};
"\N{ecute}"
"\N{APPLE LOGO}"
```
###
℞ 11: Names of CJK codepoints
Sinograms like “東京” come back with character names of `CJK UNIFIED IDEOGRAPH-6771` and `CJK UNIFIED IDEOGRAPH-4EAC`, because their “names” vary. The CPAN `Unicode::Unihan` module has a large database for decoding these (and a whole lot more), provided you know how to understand its output.
```
# cpan -i Unicode::Unihan
use Unicode::Unihan;
my $str = "東京";
my $unhan = Unicode::Unihan->new;
for my $lang (qw(Mandarin Cantonese Korean JapaneseOn JapaneseKun)) {
printf "CJK $str in %-12s is ", $lang;
say $unhan->$lang($str);
}
```
prints:
```
CJK 東京 in Mandarin is DONG1JING1
CJK 東京 in Cantonese is dung1ging1
CJK 東京 in Korean is TONGKYENG
CJK 東京 in JapaneseOn is TOUKYOU KEI KIN
CJK 東京 in JapaneseKun is HIGASHI AZUMAMIYAKO
```
If you have a specific romanization scheme in mind, use the specific module:
```
# cpan -i Lingua::JA::Romanize::Japanese
use Lingua::JA::Romanize::Japanese;
my $k2r = Lingua::JA::Romanize::Japanese->new;
my $str = "東京";
say "Japanese for $str is ", $k2r->chars($str);
```
prints
```
Japanese for 東京 is toukyou
```
###
℞ 12: Explicit encode/decode
On rare occasion, such as a database read, you may be given encoded text you need to decode.
```
use Encode qw(encode decode);
my $chars = decode("shiftjis", $bytes, 1);
# OR
my $bytes = encode("MIME-Header-ISO_2022_JP", $chars, 1);
```
For streams all in the same encoding, don't use encode/decode; instead set the file encoding when you open the file or immediately after with `binmode` as described later below.
###
℞ 13: Decode program arguments as utf8
```
$ perl -CA ...
or
$ export PERL_UNICODE=A
or
use Encode qw(decode);
@ARGV = map { decode('UTF-8', $_, 1) } @ARGV;
```
###
℞ 14: Decode program arguments as locale encoding
```
# cpan -i Encode::Locale
use Encode qw(locale);
use Encode::Locale;
# use "locale" as an arg to encode/decode
@ARGV = map { decode(locale => $_, 1) } @ARGV;
```
###
℞ 15: Declare STD{IN,OUT,ERR} to be utf8
Use a command-line option, an environment variable, or else call `binmode` explicitly:
```
$ perl -CS ...
or
$ export PERL_UNICODE=S
or
use open qw(:std :encoding(UTF-8));
or
binmode(STDIN, ":encoding(UTF-8)");
binmode(STDOUT, ":utf8");
binmode(STDERR, ":utf8");
```
###
℞ 16: Declare STD{IN,OUT,ERR} to be in locale encoding
```
# cpan -i Encode::Locale
use Encode;
use Encode::Locale;
# or as a stream for binmode or open
binmode STDIN, ":encoding(console_in)" if -t STDIN;
binmode STDOUT, ":encoding(console_out)" if -t STDOUT;
binmode STDERR, ":encoding(console_out)" if -t STDERR;
```
###
℞ 17: Make file I/O default to utf8
Files opened without an encoding argument will be in UTF-8:
```
$ perl -CD ...
or
$ export PERL_UNICODE=D
or
use open qw(:encoding(UTF-8));
```
###
℞ 18: Make all I/O and args default to utf8
```
$ perl -CSDA ...
or
$ export PERL_UNICODE=SDA
or
use open qw(:std :encoding(UTF-8));
use Encode qw(decode);
@ARGV = map { decode('UTF-8', $_, 1) } @ARGV;
```
###
℞ 19: Open file with specific encoding
Specify stream encoding. This is the normal way to deal with encoded text, not by calling low-level functions.
```
# input file
open(my $in_file, "< :encoding(UTF-16)", "wintext");
OR
open(my $in_file, "<", "wintext");
binmode($in_file, ":encoding(UTF-16)");
THEN
my $line = <$in_file>;
# output file
open($out_file, "> :encoding(cp1252)", "wintext");
OR
open(my $out_file, ">", "wintext");
binmode($out_file, ":encoding(cp1252)");
THEN
print $out_file "some text\n";
```
More layers than just the encoding can be specified here. For example, the incantation `":raw :encoding(UTF-16LE) :crlf"` includes implicit CRLF handling.
###
℞ 20: Unicode casing
Unicode casing is very different from ASCII casing.
```
uc("henry ⅷ") # "HENRY Ⅷ"
uc("tschüß") # "TSCHÜSS" notice ß => SS
# both are true:
"tschüß" =~ /TSCHÜSS/i # notice ß => SS
"Σίσυφος" =~ /ΣΊΣΥΦΟΣ/i # notice Σ,σ,ς sameness
```
###
℞ 21: Unicode case-insensitive comparisons
Also available in the CPAN <Unicode::CaseFold> module, the new `fc` “foldcase” function from v5.16 grants access to the same Unicode casefolding as the `/i` pattern modifier has always used:
```
use feature "fc"; # fc() function is from v5.16
# sort case-insensitively
my @sorted = sort { fc($a) cmp fc($b) } @list;
# both are true:
fc("tschüß") eq fc("TSCHÜSS")
fc("Σίσυφος") eq fc("ΣΊΣΥΦΟΣ")
```
###
℞ 22: Match Unicode linebreak sequence in regex
A Unicode linebreak matches the two-character CRLF grapheme or any of seven vertical whitespace characters. Good for dealing with textfiles coming from different operating systems.
```
\R
s/\R/\n/g; # normalize all linebreaks to \n
```
###
℞ 23: Get character category
Find the general category of a numeric codepoint.
```
use Unicode::UCD qw(charinfo);
my $cat = charinfo(0x3A3)->{category}; # "Lu"
```
###
℞ 24: Disabling Unicode-awareness in builtin charclasses
Disable `\w`, `\b`, `\s`, `\d`, and the POSIX classes from working correctly on Unicode either in this scope, or in just one regex.
```
use v5.14;
use re "/a";
# OR
my($num) = $str =~ /(\d+)/a;
```
Or use specific un-Unicode properties, like `\p{ahex}` and `\p{POSIX_Digit`}. Properties still work normally no matter what charset modifiers (`/d /u /l /a /aa`) should be effect.
###
℞ 25: Match Unicode properties in regex with \p, \P
These all match a single codepoint with the given property. Use `\P` in place of `\p` to match one codepoint lacking that property.
```
\pL, \pN, \pS, \pP, \pM, \pZ, \pC
\p{Sk}, \p{Ps}, \p{Lt}
\p{alpha}, \p{upper}, \p{lower}
\p{Latin}, \p{Greek}
\p{script_extensions=Latin}, \p{scx=Greek}
\p{East_Asian_Width=Wide}, \p{EA=W}
\p{Line_Break=Hyphen}, \p{LB=HY}
\p{Numeric_Value=4}, \p{NV=4}
```
###
℞ 26: Custom character properties
Define at compile-time your own custom character properties for use in regexes.
```
# using private-use characters
sub In_Tengwar { "E000\tE07F\n" }
if (/\p{In_Tengwar}/) { ... }
# blending existing properties
sub Is_GraecoRoman_Title {<<'END_OF_SET'}
+utf8::IsLatin
+utf8::IsGreek
&utf8::IsTitle
END_OF_SET
if (/\p{Is_GraecoRoman_Title}/ { ... }
```
###
℞ 27: Unicode normalization
Typically render into NFD on input and NFC on output. Using NFKC or NFKD functions improves recall on searches, assuming you've already done to the same text to be searched. Note that this is about much more than just pre- combined compatibility glyphs; it also reorders marks according to their canonical combining classes and weeds out singletons.
```
use Unicode::Normalize;
my $nfd = NFD($orig);
my $nfc = NFC($orig);
my $nfkd = NFKD($orig);
my $nfkc = NFKC($orig);
```
###
℞ 28: Convert non-ASCII Unicode numerics
Unless you’ve used `/a` or `/aa`, `\d` matches more than ASCII digits only, but Perl’s implicit string-to-number conversion does not current recognize these. Here’s how to convert such strings manually.
```
use v5.14; # needed for num() function
use Unicode::UCD qw(num);
my $str = "got Ⅻ and ४५६७ and ⅞ and here";
my @nums = ();
while ($str =~ /(\d+|\N)/g) { # not just ASCII!
push @nums, num($1);
}
say "@nums"; # 12 4567 0.875
use charnames qw(:full);
my $nv = num("\N{RUMI DIGIT ONE}\N{RUMI DIGIT TWO}");
```
###
℞ 29: Match Unicode grapheme cluster in regex
Programmer-visible “characters” are codepoints matched by `/./s`, but user-visible “characters” are graphemes matched by `/\X/`.
```
# Find vowel *plus* any combining diacritics,underlining,etc.
my $nfd = NFD($orig);
$nfd =~ / (?=[aeiou]) \X /xi
```
###
℞ 30: Extract by grapheme instead of by codepoint (regex)
```
# match and grab five first graphemes
my($first_five) = $str =~ /^ ( \X{5} ) /x;
```
###
℞ 31: Extract by grapheme instead of by codepoint (substr)
```
# cpan -i Unicode::GCString
use Unicode::GCString;
my $gcs = Unicode::GCString->new($str);
my $first_five = $gcs->substr(0, 5);
```
###
℞ 32: Reverse string by grapheme
Reversing by codepoint messes up diacritics, mistakenly converting `crème brûlée` into `éel̂urb em̀erc` instead of into `eélûrb emèrc`; so reverse by grapheme instead. Both these approaches work right no matter what normalization the string is in:
```
$str = join("", reverse $str =~ /\X/g);
# OR: cpan -i Unicode::GCString
use Unicode::GCString;
$str = reverse Unicode::GCString->new($str);
```
###
℞ 33: String length in graphemes
The string `brûlée` has six graphemes but up to eight codepoints. This counts by grapheme, not by codepoint:
```
my $str = "brûlée";
my $count = 0;
while ($str =~ /\X/g) { $count++ }
# OR: cpan -i Unicode::GCString
use Unicode::GCString;
my $gcs = Unicode::GCString->new($str);
my $count = $gcs->length;
```
###
℞ 34: Unicode column-width for printing
Perl’s `printf`, `sprintf`, and `format` think all codepoints take up 1 print column, but many take 0 or 2. Here to show that normalization makes no difference, we print out both forms:
```
use Unicode::GCString;
use Unicode::Normalize;
my @words = qw/crème brûlée/;
@words = map { NFC($_), NFD($_) } @words;
for my $str (@words) {
my $gcs = Unicode::GCString->new($str);
my $cols = $gcs->columns;
my $pad = " " x (10 - $cols);
say str, $pad, " |";
}
```
generates this to show that it pads correctly no matter the normalization:
```
crème |
crème |
brûlée |
brûlée |
```
###
℞ 35: Unicode collation
Text sorted by numeric codepoint follows no reasonable alphabetic order; use the UCA for sorting text.
```
use Unicode::Collate;
my $col = Unicode::Collate->new();
my @list = $col->sort(@old_list);
```
See the *ucsort* program from the <Unicode::Tussle> CPAN module for a convenient command-line interface to this module.
###
℞ 36: Case- *and* accent-insensitive Unicode sort
Specify a collation strength of level 1 to ignore case and diacritics, only looking at the basic character.
```
use Unicode::Collate;
my $col = Unicode::Collate->new(level => 1);
my @list = $col->sort(@old_list);
```
###
℞ 37: Unicode locale collation
Some locales have special sorting rules.
```
# either use v5.12, OR: cpan -i Unicode::Collate::Locale
use Unicode::Collate::Locale;
my $col = Unicode::Collate::Locale->new(locale => "de__phonebook");
my @list = $col->sort(@old_list);
```
The *ucsort* program mentioned above accepts a `--locale` parameter.
###
℞ 38: Making `cmp` work on text instead of codepoints
Instead of this:
```
@srecs = sort {
$b->{AGE} <=> $a->{AGE}
||
$a->{NAME} cmp $b->{NAME}
} @recs;
```
Use this:
```
my $coll = Unicode::Collate->new();
for my $rec (@recs) {
$rec->{NAME_key} = $coll->getSortKey( $rec->{NAME} );
}
@srecs = sort {
$b->{AGE} <=> $a->{AGE}
||
$a->{NAME_key} cmp $b->{NAME_key}
} @recs;
```
###
℞ 39: Case- *and* accent-insensitive comparisons
Use a collator object to compare Unicode text by character instead of by codepoint.
```
use Unicode::Collate;
my $es = Unicode::Collate->new(
level => 1,
normalization => undef
);
# now both are true:
$es->eq("García", "GARCIA" );
$es->eq("Márquez", "MARQUEZ");
```
###
℞ 40: Case- *and* accent-insensitive locale comparisons
Same, but in a specific locale.
```
my $de = Unicode::Collate::Locale->new(
locale => "de__phonebook",
);
# now this is true:
$de->eq("tschüß", "TSCHUESS"); # notice ü => UE, ß => SS
```
###
℞ 41: Unicode linebreaking
Break up text into lines according to Unicode rules.
```
# cpan -i Unicode::LineBreak
use Unicode::LineBreak;
use charnames qw(:full);
my $para = "This is a super\N{HYPHEN}long string. " x 20;
my $fmt = Unicode::LineBreak->new;
print $fmt->break($para), "\n";
```
###
℞ 42: Unicode text in DBM hashes, the tedious way
Using a regular Perl string as a key or value for a DBM hash will trigger a wide character exception if any codepoints won’t fit into a byte. Here’s how to manually manage the translation:
```
use DB_File;
use Encode qw(encode decode);
tie %dbhash, "DB_File", "pathname";
# STORE
# assume $uni_key and $uni_value are abstract Unicode strings
my $enc_key = encode("UTF-8", $uni_key, 1);
my $enc_value = encode("UTF-8", $uni_value, 1);
$dbhash{$enc_key} = $enc_value;
# FETCH
# assume $uni_key holds a normal Perl string (abstract Unicode)
my $enc_key = encode("UTF-8", $uni_key, 1);
my $enc_value = $dbhash{$enc_key};
my $uni_value = decode("UTF-8", $enc_value, 1);
```
###
℞ 43: Unicode text in DBM hashes, the easy way
Here’s how to implicitly manage the translation; all encoding and decoding is done automatically, just as with streams that have a particular encoding attached to them:
```
use DB_File;
use DBM_Filter;
my $dbobj = tie %dbhash, "DB_File", "pathname";
$dbobj->Filter_Value("utf8"); # this is the magic bit
# STORE
# assume $uni_key and $uni_value are abstract Unicode strings
$dbhash{$uni_key} = $uni_value;
# FETCH
# $uni_key holds a normal Perl string (abstract Unicode)
my $uni_value = $dbhash{$uni_key};
```
###
℞ 44: PROGRAM: Demo of Unicode collation and printing
Here’s a full program showing how to make use of locale-sensitive sorting, Unicode casing, and managing print widths when some of the characters take up zero or two columns, not just one column each time. When run, the following program produces this nicely aligned output:
```
Crème Brûlée....... €2.00
Éclair............. €1.60
Fideuà............. €4.20
Hamburger.......... €6.00
Jamón Serrano...... €4.45
Linguiça........... €7.00
Pâté............... €4.15
Pears.............. €2.00
Pêches............. €2.25
Smørbrød........... €5.75
Spätzle............ €5.50
Xoriço............. €3.00
Γύρος.............. €6.50
막걸리............. €4.00
おもち............. €2.65
お好み焼き......... €8.00
シュークリーム..... €1.85
寿司............... €9.99
包子............... €7.50
```
Here's that program.
```
#!/usr/bin/env perl
# umenu - demo sorting and printing of Unicode food
#
# (obligatory and increasingly long preamble)
#
use v5.36;
use utf8;
use warnings qw(FATAL utf8); # fatalize encoding faults
use open qw(:std :encoding(UTF-8)); # undeclared streams in UTF-8
use charnames qw(:full :short); # unneeded in v5.16
# std modules
use Unicode::Normalize; # std perl distro as of v5.8
use List::Util qw(max); # std perl distro as of v5.10
use Unicode::Collate::Locale; # std perl distro as of v5.14
# cpan modules
use Unicode::GCString; # from CPAN
my %price = (
"γύρος" => 6.50, # gyros
"pears" => 2.00, # like um, pears
"linguiça" => 7.00, # spicy sausage, Portuguese
"xoriço" => 3.00, # chorizo sausage, Catalan
"hamburger" => 6.00, # burgermeister meisterburger
"éclair" => 1.60, # dessert, French
"smørbrød" => 5.75, # sandwiches, Norwegian
"spätzle" => 5.50, # Bayerisch noodles, little sparrows
"包子" => 7.50, # bao1 zi5, steamed pork buns, Mandarin
"jamón serrano" => 4.45, # country ham, Spanish
"pêches" => 2.25, # peaches, French
"シュークリーム" => 1.85, # cream-filled pastry like eclair
"막걸리" => 4.00, # makgeolli, Korean rice wine
"寿司" => 9.99, # sushi, Japanese
"おもち" => 2.65, # omochi, rice cakes, Japanese
"crème brûlée" => 2.00, # crema catalana
"fideuà" => 4.20, # more noodles, Valencian
# (Catalan=fideuada)
"pâté" => 4.15, # gooseliver paste, French
"お好み焼き" => 8.00, # okonomiyaki, Japanese
);
my $width = 5 + max map { colwidth($_) } keys %price;
# So the Asian stuff comes out in an order that someone
# who reads those scripts won't freak out over; the
# CJK stuff will be in JIS X 0208 order that way.
my $coll = Unicode::Collate::Locale->new(locale => "ja");
for my $item ($coll->sort(keys %price)) {
print pad(entitle($item), $width, ".");
printf " €%.2f\n", $price{$item};
}
sub pad ($str, $width, $padchar) {
return $str . ($padchar x ($width - colwidth($str)));
}
sub colwidth ($str) {
return Unicode::GCString->new($str)->columns;
}
sub entitle ($str) {
$str =~ s{ (?=\pL)(\S) (\S*) }
{ ucfirst($1) . lc($2) }xge;
return $str;
}
```
SEE ALSO
---------
See these manpages, some of which are CPAN modules: <perlunicode>, <perluniprops>, <perlre>, <perlrecharclass>, <perluniintro>, <perlunitut>, <perlunifaq>, [PerlIO](perlio), [DB\_File](db_file), [DBM\_Filter](dbm_filter), <DBM_Filter::utf8>, [Encode](encode), <Encode::Locale>, <Unicode::UCD>, <Unicode::Normalize>, <Unicode::GCString>, <Unicode::LineBreak>, <Unicode::Collate>, <Unicode::Collate::Locale>, <Unicode::Unihan>, <Unicode::CaseFold>, <Unicode::Tussle>, <Lingua::JA::Romanize::Japanese>, <Lingua::ZH::Romanize::Pinyin>, <Lingua::KO::Romanize::Hangul>.
The <Unicode::Tussle> CPAN module includes many programs to help with working with Unicode, including these programs to fully or partly replace standard utilities: *tcgrep* instead of *egrep*, *uniquote* instead of *cat -v* or *hexdump*, *uniwc* instead of *wc*, *unilook* instead of *look*, *unifmt* instead of *fmt*, and *ucsort* instead of *sort*. For exploring Unicode character names and character properties, see its *uniprops*, *unichars*, and *uninames* programs. It also supplies these programs, all of which are general filters that do Unicode-y things: *unititle* and *unicaps*; *uniwide* and *uninarrow*; *unisupers* and *unisubs*; *nfd*, *nfc*, *nfkd*, and *nfkc*; and *uc*, *lc*, and *tc*.
Finally, see the published Unicode Standard (page numbers are from version 6.0.0), including these specific annexes and technical reports:
§3.13 Default Case Algorithms, page 113; §4.2 Case, pages 120–122; Case Mappings, page 166–172, especially Caseless Matching starting on page 170.
UAX #44: Unicode Character Database
UTS #18: Unicode Regular Expressions
UAX #15: Unicode Normalization Forms
UTS #10: Unicode Collation Algorithm
UAX #29: Unicode Text Segmentation
UAX #14: Unicode Line Breaking Algorithm
UAX #11: East Asian Width AUTHOR
------
Tom Christiansen <[email protected]> wrote this, with occasional kibbitzing from Larry Wall and Jeffrey Friedl in the background.
COPYRIGHT AND LICENCE
----------------------
Copyright © 2012 Tom Christiansen.
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
Most of these examples taken from the current edition of the “Camel Book”; that is, from the 4ᵗʰ Edition of *Programming Perl*, Copyright © 2012 Tom Christiansen <et al.>, 2012-02-13 by O’Reilly Media. The code itself is freely redistributable, and you are encouraged to transplant, fold, spindle, and mutilate any of the examples in this manpage however you please for inclusion into your own programs without any encumbrance whatsoever. Acknowledgement via code comment is polite but not required.
REVISION HISTORY
-----------------
v1.0.0 – first public release, 2012-02-27
| programming_docs |
perl PerlIO::via::QuotedPrint PerlIO::via::QuotedPrint
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [FEEDBACK](#FEEDBACK)
* [SEE ALSO](#SEE-ALSO)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AVAILABILITY](#AVAILABILITY)
* [INSTALLATION](#INSTALLATION)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
PerlIO::via::QuotedPrint - PerlIO layer for quoted-printable strings
SYNOPSIS
--------
```
use PerlIO::via::QuotedPrint;
open(my $in, '<:via(QuotedPrint)', 'file.qp') or
die "Can't open file.qp for reading: $!\n";
open(my $out, '>:via(QuotedPrint)', 'file.qp') or
die "Can't open file.qp for writing: $!\n";
```
DESCRIPTION
-----------
This module implements a PerlIO layer that works on files encoded in the quoted-printable format. It will decode from quoted-printable while reading from a handle, and it will encode as quoted-printable while writing to a handle.
EXPORTS
-------
*None*.
KNOWN BUGS
-----------
*None*.
FEEDBACK
--------
Patches, bug reports, suggestions or any other feedback is welcome.
Patches can be sent as GitHub pull requests at <https://github.com/steve-m-hay/PerlIO-via-QuotedPrint/pulls>.
Bug reports and suggestions can be made on the CPAN Request Tracker at <https://rt.cpan.org/Public/Bug/Report.html?Queue=PerlIO-via-QuotedPrint>.
Currently active requests on the CPAN Request Tracker can be viewed at <https://rt.cpan.org/Public/Dist/Display.html?Status=Active;Queue=PerlIO-via-QuotedPrint>.
Please test this distribution. See CPAN Testers Reports at <https://www.cpantesters.org/> for details of how to get involved.
Previous test results on CPAN Testers Reports can be viewed at <https://www.cpantesters.org/distro/P/PerlIO-via-QuotedPrint.html>.
Please rate this distribution on CPAN Ratings at <https://cpanratings.perl.org/rate/?distribution=PerlIO-via-QuotedPrint>.
SEE ALSO
---------
<PerlIO::via>, <MIME::QuotedPrint>.
ACKNOWLEDGEMENTS
----------------
Based on an example in the standard library module MIME::QuotedPrint in Perl (version 5.8.0).
AVAILABILITY
------------
The latest version of this module is available from CPAN (see ["CPAN" in perlmodlib](perlmodlib#CPAN) for details) at
<https://metacpan.org/release/PerlIO-via-QuotedPrint> or
<https://www.cpan.org/authors/id/S/SH/SHAY/> or
<https://www.cpan.org/modules/by-module/PerlIO/>.
The latest source code is available from GitHub at <https://github.com/steve-m-hay/PerlIO-via-QuotedPrint>.
INSTALLATION
------------
See the *INSTALL* file.
AUTHOR
------
Elizabeth Mattijsen <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining PerlIO::via::QuotedPrint as of version 0.08.
COPYRIGHT
---------
Copyright (C) 2002-2004, 2012 Elizabeth Mattijsen. All rights reserved.
Copyright (C) 2015, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 0.09
DATE
----
08 Dec 2020
HISTORY
-------
See the *Changes* file.
perl TAP::Parser::Multiplexer TAP::Parser::Multiplexer
========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [add](#add)
- [parsers](#parsers)
- [next](#next)
* [See Also](#See-Also)
NAME
----
TAP::Parser::Multiplexer - Multiplex multiple TAP::Parsers
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Multiplexer;
my $mux = TAP::Parser::Multiplexer->new;
$mux->add( $parser1, $stash1 );
$mux->add( $parser2, $stash2 );
while ( my ( $parser, $stash, $result ) = $mux->next ) {
# do stuff
}
```
DESCRIPTION
-----------
`TAP::Parser::Multiplexer` gathers input from multiple TAP::Parsers. Internally it calls select on the input file handles for those parsers to wait for one or more of them to have input available.
See <TAP::Harness> for an example of its use.
METHODS
-------
###
Class Methods
#### `new`
```
my $mux = TAP::Parser::Multiplexer->new;
```
Returns a new `TAP::Parser::Multiplexer` object.
###
Instance Methods
#### `add`
```
$mux->add( $parser, $stash );
```
Add a TAP::Parser to the multiplexer. `$stash` is an optional opaque reference that will be returned from `next` along with the parser and the next result.
#### `parsers`
```
my $count = $mux->parsers;
```
Returns the number of parsers. Parsers are removed from the multiplexer when their input is exhausted.
#### `next`
Return a result from the next available parser. Returns a list containing the parser from which the result came, the stash that corresponds with that parser and the result.
```
my ( $parser, $stash, $result ) = $mux->next;
```
If `$result` is undefined the corresponding parser has reached the end of its input (and will automatically be removed from the multiplexer).
When all parsers are exhausted an empty list will be returned.
```
if ( my ( $parser, $stash, $result ) = $mux->next ) {
if ( ! defined $result ) {
# End of this parser
}
else {
# Process result
}
}
else {
# All parsers finished
}
```
See Also
---------
<TAP::Parser>
<TAP::Harness>
perl File::Spec::AmigaOS File::Spec::AmigaOS
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
NAME
----
File::Spec::AmigaOS - File::Spec for AmigaOS
SYNOPSIS
--------
```
require File::Spec::AmigaOS; # Done automatically by File::Spec
# if needed
```
DESCRIPTION
-----------
Methods for manipulating file specifications.
METHODS
-------
tmpdir Returns $ENV{TMPDIR} or if that is unset, "/t".
file\_name\_is\_absolute Returns true if there's a colon in the file name, or if it begins with a slash.
All the other methods are from <File::Spec::Unix>.
perl perlop perlop
======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Operator Precedence and Associativity](#Operator-Precedence-and-Associativity)
+ [Terms and List Operators (Leftward)](#Terms-and-List-Operators-(Leftward))
+ [The Arrow Operator](#The-Arrow-Operator)
+ [Auto-increment and Auto-decrement](#Auto-increment-and-Auto-decrement)
+ [Exponentiation](#Exponentiation)
+ [Symbolic Unary Operators](#Symbolic-Unary-Operators)
+ [Binding Operators](#Binding-Operators)
+ [Multiplicative Operators](#Multiplicative-Operators)
+ [Additive Operators](#Additive-Operators)
+ [Shift Operators](#Shift-Operators)
+ [Named Unary Operators](#Named-Unary-Operators)
+ [Relational Operators](#Relational-Operators)
+ [Equality Operators](#Equality-Operators)
+ [Class Instance Operator](#Class-Instance-Operator)
+ [Smartmatch Operator](#Smartmatch-Operator)
- [Smartmatching of Objects](#Smartmatching-of-Objects)
+ [Bitwise And](#Bitwise-And)
+ [Bitwise Or and Exclusive Or](#Bitwise-Or-and-Exclusive-Or)
+ [C-style Logical And](#C-style-Logical-And)
+ [C-style Logical Or](#C-style-Logical-Or)
+ [Logical Defined-Or](#Logical-Defined-Or)
+ [Range Operators](#Range-Operators)
+ [Conditional Operator](#Conditional-Operator)
+ [Assignment Operators](#Assignment-Operators)
+ [Comma Operator](#Comma-Operator)
+ [List Operators (Rightward)](#List-Operators-(Rightward))
+ [Logical Not](#Logical-Not)
+ [Logical And](#Logical-And)
+ [Logical or and Exclusive Or](#Logical-or-and-Exclusive-Or)
+ [C Operators Missing From Perl](#C-Operators-Missing-From-Perl)
+ [Quote and Quote-like Operators](#Quote-and-Quote-like-Operators)
+ [Regexp Quote-Like Operators](#Regexp-Quote-Like-Operators)
+ [Quote-Like Operators](#Quote-Like-Operators)
+ [Gory details of parsing quoted constructs](#Gory-details-of-parsing-quoted-constructs)
+ [I/O Operators](#I/O-Operators)
+ [Constant Folding](#Constant-Folding)
+ [No-ops](#No-ops)
+ [Bitwise String Operators](#Bitwise-String-Operators)
+ [Integer Arithmetic](#Integer-Arithmetic)
+ [Floating-point Arithmetic](#Floating-point-Arithmetic)
+ [Bigger Numbers](#Bigger-Numbers)
NAME
----
perlop - Perl operators and precedence
DESCRIPTION
-----------
In Perl, the operator determines what operation is performed, independent of the type of the operands. For example `$x + $y` is always a numeric addition, and if `$x` or `$y` do not contain numbers, an attempt is made to convert them to numbers first.
This is in contrast to many other dynamic languages, where the operation is determined by the type of the first argument. It also means that Perl has two versions of some operators, one for numeric and one for string comparison. For example `$x == $y` compares two numbers for equality, and `$x eq $y` compares two strings.
There are a few exceptions though: `x` can be either string repetition or list repetition, depending on the type of the left operand, and `&`, `|`, `^` and `~` can be either string or numeric bit operations.
###
Operator Precedence and Associativity
Operator precedence and associativity work in Perl more or less like they do in mathematics.
*Operator precedence* means some operators group more tightly than others. For example, in `2 + 4 * 5`, the multiplication has higher precedence, so `4 * 5` is grouped together as the right-hand operand of the addition, rather than `2 + 4` being grouped together as the left-hand operand of the multiplication. It is as if the expression were written `2 + (4 * 5)`, not `(2 + 4) * 5`. So the expression yields `2 + 20 == 22`, rather than `6 * 5 == 30`.
*Operator associativity* defines what happens if a sequence of the same operators is used one after another: usually that they will be grouped at the left or the right. For example, in `9 - 3 - 2`, subtraction is left associative, so `9 - 3` is grouped together as the left-hand operand of the second subtraction, rather than `3 - 2` being grouped together as the right-hand operand of the first subtraction. It is as if the expression were written `(9 - 3) - 2`, not `9 - (3 - 2)`. So the expression yields `6 - 2 == 4`, rather than `9 - 1 == 8`.
For simple operators that evaluate all their operands and then combine the values in some way, precedence and associativity (and parentheses) imply some ordering requirements on those combining operations. For example, in `2 + 4 * 5`, the grouping implied by precedence means that the multiplication of 4 and 5 must be performed before the addition of 2 and 20, simply because the result of that multiplication is required as one of the operands of the addition. But the order of operations is not fully determined by this: in `2 * 2 + 4 * 5` both multiplications must be performed before the addition, but the grouping does not say anything about the order in which the two multiplications are performed. In fact Perl has a general rule that the operands of an operator are evaluated in left-to-right order. A few operators such as `&&=` have special evaluation rules that can result in an operand not being evaluated at all; in general, the top-level operator in an expression has control of operand evaluation.
Some comparison operators, as their associativity, *chain* with some operators of the same precedence (but never with operators of different precedence). This chaining means that each comparison is performed on the two arguments surrounding it, with each interior argument taking part in two comparisons, and the comparison results are implicitly ANDed. Thus `"$x < $y <= $z"` behaves exactly like `"$x < $y && $y <= $z"`, assuming that `"$y"` is as simple a scalar as it looks. The ANDing short-circuits just like `"&&"` does, stopping the sequence of comparisons as soon as one yields false.
In a chained comparison, each argument expression is evaluated at most once, even if it takes part in two comparisons, but the result of the evaluation is fetched for each comparison. (It is not evaluated at all if the short-circuiting means that it's not required for any comparisons.) This matters if the computation of an interior argument is expensive or non-deterministic. For example,
```
if($x < expensive_sub() <= $z) { ...
```
is not entirely like
```
if($x < expensive_sub() && expensive_sub() <= $z) { ...
```
but instead closer to
```
my $tmp = expensive_sub();
if($x < $tmp && $tmp <= $z) { ...
```
in that the subroutine is only called once. However, it's not exactly like this latter code either, because the chained comparison doesn't actually involve any temporary variable (named or otherwise): there is no assignment. This doesn't make much difference where the expression is a call to an ordinary subroutine, but matters more with an lvalue subroutine, or if the argument expression yields some unusual kind of scalar by other means. For example, if the argument expression yields a tied scalar, then the expression is evaluated to produce that scalar at most once, but the value of that scalar may be fetched up to twice, once for each comparison in which it is actually used.
In this example, the expression is evaluated only once, and the tied scalar (the result of the expression) is fetched for each comparison that uses it.
```
if ($x < $tied_scalar < $z) { ...
```
In the next example, the expression is evaluated only once, and the tied scalar is fetched once as part of the operation within the expression. The result of that operation is fetched for each comparison, which normally doesn't matter unless that expression result is also magical due to operator overloading.
```
if ($x < $tied_scalar + 42 < $z) { ...
```
Some operators are instead non-associative, meaning that it is a syntax error to use a sequence of those operators of the same precedence. For example, `"$x .. $y .. $z"` is an error.
Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Operators borrowed from C keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for C folks.) With very few exceptions, these all operate on scalar values only, not array values.
```
left terms and list operators (leftward)
left ->
nonassoc ++ --
right **
right ! ~ ~. \ and unary + and -
left =~ !~
left * / % x
left + - .
left << >>
nonassoc named unary operators
nonassoc isa
chained < > <= >= lt gt le ge
chain/na == != eq ne <=> cmp ~~
left & &.
left | |. ^ ^.
left &&
left || //
nonassoc .. ...
right ?:
right = += -= *= etc. goto last next redo dump
left , =>
nonassoc list operators (rightward)
right not
left and
left or xor
```
In the following sections, these operators are covered in detail, in the same order in which they appear in the table above.
Many operators can be overloaded for objects. See <overload>.
###
Terms and List Operators (Leftward)
A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any function whose arguments are parenthesized. Actually, there aren't really functions in this sense, just list operators and unary operators behaving as functions because you put parentheses around the arguments. These are all documented in <perlfunc>.
If any list operator (`print()`, etc.) or any unary operator (`chdir()`, etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call.
In the absence of parentheses, the precedence of list operators such as `print`, `sort`, or `chmod` is either very high or very low depending on whether you are looking at the left side or the right side of the operator. For example, in
```
@ary = (1, 3, sort 4, 2);
print @ary; # prints 1324
```
the commas on the right of the `sort` are evaluated before the `sort`, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all arguments that follow, and then act like a simple TERM with regard to the preceding expression. Be careful with parentheses:
```
# These evaluate exit before doing the print:
print($foo, exit); # Obviously not what you want.
print $foo, exit; # Nor is this.
# These do the print before evaluating exit:
(print $foo), exit; # This is what you want.
print($foo), exit; # Or this.
print ($foo), exit; # Or even this.
```
Also note that
```
print ($foo & 255) + 1, "\n";
```
probably doesn't do what you expect at first glance. The parentheses enclose the argument list for `print` which is evaluated (printing the result of `$foo & 255`). Then one is added to the return value of `print` (usually 1). The result is something like this:
```
1 + 1, "\n"; # Obviously not what you meant.
```
To do what you meant properly, you must write:
```
print(($foo & 255) + 1, "\n");
```
See ["Named Unary Operators"](#Named-Unary-Operators) for more discussion of this.
Also parsed as terms are the `do {}` and `eval {}` constructs, as well as subroutine and method calls, and the anonymous constructors `[]` and `{}`.
See also ["Quote and Quote-like Operators"](#Quote-and-Quote-like-Operators) toward the end of this section, as well as ["I/O Operators"](#I%2FO-Operators).
###
The Arrow Operator
"`->`" is an infix dereference operator, just as it is in C and C++. If the right side is either a `[...]`, `{...}`, or a `(...)` subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively. (Or technically speaking, a location capable of holding a hard reference, if it's an array or hash reference being used for assignment.) See <perlreftut> and <perlref>.
Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and (if it is a method name) the left side must be either an object (a blessed reference) or a class name (that is, a package name). See <perlobj>.
The dereferencing cases (as opposed to method-calling cases) are somewhat extended by the `postderef` feature. For the details of that feature, consult ["Postfix Dereference Syntax" in perlref](perlref#Postfix-Dereference-Syntax).
###
Auto-increment and Auto-decrement
`"++"` and `"--"` work as in C. That is, if placed before a variable, they increment or decrement the variable by one before returning the value, and if placed after, increment or decrement after returning the value.
```
$i = 0; $j = 0;
print $i++; # prints 0
print ++$j; # prints 1
```
Note that just as in C, Perl doesn't define **when** the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:
```
$i = $i ++;
print ++ $i + $i ++;
```
Perl will not guarantee what the result of the above statements is.
The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern `/^[a-zA-Z]*[0-9]*\z/`, the increment is done as a string, preserving each character within its range, with carry:
```
print ++($foo = "99"); # prints "100"
print ++($foo = "a0"); # prints "a1"
print ++($foo = "Az"); # prints "Ba"
print ++($foo = "zz"); # prints "aaa"
```
`undef` is always treated as numeric, and in particular is changed to `0` before incrementing (so that a post-increment of an undef value will return `0` rather than `undef`).
The auto-decrement operator is not magical.
### Exponentiation
Binary `"**"` is the exponentiation operator. It binds even more tightly than unary minus, so `-2**4` is `-(2**4)`, not `(-2)**4`. (This is implemented using C's `pow(3)` function, which actually works on doubles internally.)
Note that certain exponentiation expressions are ill-defined: these include `0**0`, `1**Inf`, and `Inf**0`. Do not expect any particular results from these special cases, the results are platform-dependent.
###
Symbolic Unary Operators
Unary `"!"` performs logical negation, that is, "not". See also [`not`](#Logical-Not) for a lower precedence version of this.
Unary `"-"` performs arithmetic negation if the operand is numeric, including any string that looks like a number. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that `-bareword` is equivalent to the string `"-bareword"`. If, however, the string begins with a non-alphabetic character (excluding `"+"` or `"-"`), Perl will attempt to convert the string to a numeric, and the arithmetic negation is performed. If the string cannot be cleanly converted to a numeric, Perl will give the warning **Argument "the string" isn't numeric in negation (-) at ...**.
Unary `"~"` performs bitwise negation, that is, 1's complement. For example, `0666 & ~027` is 0640. (See also ["Integer Arithmetic"](#Integer-Arithmetic) and ["Bitwise String Operators"](#Bitwise-String-Operators).) Note that the width of the result is platform-dependent: `~0` is 32 bits wide on a 32-bit platform, but 64 bits wide on a 64-bit platform, so if you are expecting a certain bit width, remember to use the `"&"` operator to mask off the excess bits.
Starting in Perl 5.28, it is a fatal error to try to complement a string containing a character with an ordinal value above 255.
If the "bitwise" feature is enabled via `use feature 'bitwise'` or `use v5.28`, then unary `"~"` always treats its argument as a number, and an alternate form of the operator, `"~."`, always treats its argument as a string. So `~0` and `~"0"` will both give 2\*\*32-1 on 32-bit platforms, whereas `~.0` and `~."0"` will both yield `"\xff"`. Until Perl 5.28, this feature produced a warning in the `"experimental::bitwise"` category.
Unary `"+"` has no effect whatsoever, even on strings. It is useful syntactically for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments. (See examples above under ["Terms and List Operators (Leftward)"](#Terms-and-List-Operators-%28Leftward%29).)
Unary `"\"` creates references. If its operand is a single sigilled thing, it creates a reference to that object. If its operand is a parenthesised list, then it creates references to the things mentioned in the list. Otherwise it puts its operand in list context, and creates a list of references to the scalars in the list provided by the operand. See <perlreftut> and <perlref>. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the notion of protecting the next thing from interpolation.
###
Binding Operators
Binary `"=~"` binds a scalar expression to a pattern match. Certain operations search or modify the string `$_` by default. This operator makes that kind of operation work on some other string. The right argument is a search pattern, substitution, or transliteration. The left argument is what is supposed to be searched, substituted, or transliterated instead of the default `$_`. When used in scalar context, the return value generally indicates the success of the operation. The exceptions are substitution (`s///`) and transliteration (`y///`) with the `/r` (non-destructive) option, which cause the **r**eturn value to be the result of the substitution. Behavior in list context depends on the particular operator. See ["Regexp Quote-Like Operators"](#Regexp-Quote-Like-Operators) for details and <perlretut> for examples using these operators.
If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. Note that this means that its contents will be interpolated twice, so
```
'\\' =~ q'\\';
```
is not ok, as the regex engine will end up trying to compile the pattern `\`, which it will consider a syntax error.
Binary `"!~"` is just like `"=~"` except the return value is negated in the logical sense.
Binary `"!~"` with a non-destructive substitution (`s///r`) or transliteration (`y///r`) is a syntax error.
###
Multiplicative Operators
Binary `"*"` multiplies two numbers.
Binary `"/"` divides two numbers.
Binary `"%"` is the modulo operator, which computes the division remainder of its first argument with respect to its second argument. Given integer operands `$m` and `$n`: If `$n` is positive, then `$m % $n` is `$m` minus the largest multiple of `$n` less than or equal to `$m`. If `$n` is negative, then `$m % $n` is `$m` minus the smallest multiple of `$n` that is not less than `$m` (that is, the result will be less than or equal to zero). If the operands `$m` and `$n` are floating point values and the absolute value of `$n` (that is `abs($n)`) is less than `(UV_MAX + 1)`, only the integer portion of `$m` and `$n` will be used in the operation (Note: here `UV_MAX` means the maximum of the unsigned integer type). If the absolute value of the right operand (`abs($n)`) is greater than or equal to `(UV_MAX + 1)`, `"%"` computes the floating-point remainder `$r` in the equation `($r = $m - $i*$n)` where `$i` is a certain integer that makes `$r` have the same sign as the right operand `$n` (**not** as the left operand `$m` like C function `fmod()`) and the absolute value less than that of `$n`. Note that when `use integer` is in scope, `"%"` gives you direct access to the modulo operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.
Binary `x` is the repetition operator. In scalar context, or if the left operand is neither enclosed in parentheses nor a `qw//` list, it performs a string repetition. In that case it supplies scalar context to the left operand, and returns a string consisting of the left operand string repeated the number of times specified by the right operand. If the `x` is in list context, and the left operand is either enclosed in parentheses or a `qw//` list, it performs a list repetition. In that case it supplies list context to the left operand, and returns a list consisting of the left operand list repeated the number of times specified by the right operand. If the right operand is zero or negative (raising a warning on negative), it returns an empty string or an empty list, depending on the context.
```
print '-' x 80; # print row of dashes
print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
@ones = (1) x 80; # a list of 80 1's
@ones = (5) x @ones; # set all elements to 5
```
###
Additive Operators
Binary `"+"` returns the sum of two numbers.
Binary `"-"` returns the difference of two numbers.
Binary `"."` concatenates two strings.
###
Shift Operators
Binary `"<<"` returns the value of its left argument shifted left by the number of bits specified by the right argument. Arguments should be integers. (See also ["Integer Arithmetic"](#Integer-Arithmetic).)
Binary `">>"` returns the value of its left argument shifted right by the number of bits specified by the right argument. Arguments should be integers. (See also ["Integer Arithmetic"](#Integer-Arithmetic).)
If `use integer` (see ["Integer Arithmetic"](#Integer-Arithmetic)) is in force then signed C integers are used (*arithmetic shift*), otherwise unsigned C integers are used (*logical shift*), even for negative shiftees. In arithmetic right shift the sign bit is replicated on the left, in logical shift zero bits come in from the left.
Either way, the implementation isn't going to generate results larger than the size of the integer type Perl was built with (32 bits or 64 bits).
Shifting by negative number of bits means the reverse shift: left shift becomes right shift, right shift becomes left shift. This is unlike in C, where negative shift is undefined.
Shifting by more bits than the size of the integers means most of the time zero (all bits fall off), except that under `use integer` right overshifting a negative shiftee results in -1. This is unlike in C, where shifting by too many bits is undefined. A common C behavior is "shift by modulo wordbits", so that for example
```
1 >> 64 == 1 >> (64 % 64) == 1 >> 0 == 1 # Common C behavior.
```
but that is completely accidental.
If you get tired of being subject to your platform's native integers, the `use bigint` pragma neatly sidesteps the issue altogether:
```
print 20 << 20; # 20971520
print 20 << 40; # 5120 on 32-bit machines,
# 21990232555520 on 64-bit machines
use bigint;
print 20 << 100; # 25353012004564588029934064107520
```
###
Named Unary Operators
The various named unary operators are treated as functions with one argument, with optional parentheses.
If any list operator (`print()`, etc.) or any unary operator (`chdir()`, etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. For example, because named unary operators are higher precedence than `||`:
```
chdir $foo || die; # (chdir $foo) || die
chdir($foo) || die; # (chdir $foo) || die
chdir ($foo) || die; # (chdir $foo) || die
chdir +($foo) || die; # (chdir $foo) || die
```
but, because `"*"` is higher precedence than named operators:
```
chdir $foo * 20; # chdir ($foo * 20)
chdir($foo) * 20; # (chdir $foo) * 20
chdir ($foo) * 20; # (chdir $foo) * 20
chdir +($foo) * 20; # chdir ($foo * 20)
rand 10 * 20; # rand (10 * 20)
rand(10) * 20; # (rand 10) * 20
rand (10) * 20; # (rand 10) * 20
rand +(10) * 20; # rand (10 * 20)
```
Regarding precedence, the filetest operators, like `-f`, `-M`, etc. are treated like named unary operators, but they don't follow this functional parenthesis rule. That means, for example, that `-f($file).".bak"` is equivalent to `-f "$file.bak"`.
See also ["Terms and List Operators (Leftward)"](#Terms-and-List-Operators-%28Leftward%29).
###
Relational Operators
Perl operators that return true or false generally return values that can be safely used as numbers. For example, the relational operators in this section and the equality operators in the next one return `1` for true and a special version of the defined empty string, `""`, which counts as a zero but is exempt from warnings about improper numeric conversions, just as `"0 but true"` is.
Binary `"<"` returns true if the left argument is numerically less than the right argument.
Binary `">"` returns true if the left argument is numerically greater than the right argument.
Binary `"<="` returns true if the left argument is numerically less than or equal to the right argument.
Binary `">="` returns true if the left argument is numerically greater than or equal to the right argument.
Binary `"lt"` returns true if the left argument is stringwise less than the right argument.
Binary `"gt"` returns true if the left argument is stringwise greater than the right argument.
Binary `"le"` returns true if the left argument is stringwise less than or equal to the right argument.
Binary `"ge"` returns true if the left argument is stringwise greater than or equal to the right argument.
A sequence of relational operators, such as `"$x < $y <= $z"`, performs chained comparisons, in the manner described above in the section ["Operator Precedence and Associativity"](#Operator-Precedence-and-Associativity). Beware that they do not chain with equality operators, which have lower precedence.
###
Equality Operators
Binary `"=="` returns true if the left argument is numerically equal to the right argument.
Binary `"!="` returns true if the left argument is numerically not equal to the right argument.
Binary `"eq"` returns true if the left argument is stringwise equal to the right argument.
Binary `"ne"` returns true if the left argument is stringwise not equal to the right argument.
A sequence of the above equality operators, such as `"$x == $y == $z"`, performs chained comparisons, in the manner described above in the section ["Operator Precedence and Associativity"](#Operator-Precedence-and-Associativity). Beware that they do not chain with relational operators, which have higher precedence.
Binary `"<=>"` returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. If your platform supports `NaN`'s (not-a-numbers) as numeric values, using them with `"<=>"` returns undef. `NaN` is not `"<"`, `"=="`, `">"`, `"<="` or `">="` anything (even `NaN`), so those 5 return false. `NaN != NaN` returns true, as does `NaN !=` *anything else*. If your platform doesn't support `NaN`'s then `NaN` is just a string with numeric value 0.
```
$ perl -le '$x = "NaN"; print "No NaN support here" if $x == $x'
$ perl -le '$x = "NaN"; print "NaN support here" if $x != $x'
```
(Note that the <bigint>, <bigrat>, and <bignum> pragmas all support `"NaN"`.)
Binary `"cmp"` returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.
Here we can see the difference between <=> and cmp,
```
print 10 <=> 2 #prints 1
print 10 cmp 2 #prints -1
```
(likewise between gt and >, lt and <, etc.)
Binary `"~~"` does a smartmatch between its arguments. Smart matching is described in the next section.
The two-sided ordering operators `"<=>"` and `"cmp"`, and the smartmatch operator `"~~"`, are non-associative with respect to each other and with respect to the equality operators of the same precedence.
`"lt"`, `"le"`, `"ge"`, `"gt"` and `"cmp"` use the collation (sort) order specified by the current `LC_COLLATE` locale if a `use locale` form that includes collation is in effect. See <perllocale>. Do not mix these with Unicode, only use them with legacy 8-bit locale encodings. The standard `<Unicode::Collate>` and `<Unicode::Collate::Locale>` modules offer much more powerful solutions to collation issues.
For case-insensitive comparisons, look at the ["fc" in perlfunc](perlfunc#fc) case-folding function, available in Perl v5.16 or later:
```
if ( fc($x) eq fc($y) ) { ... }
```
###
Class Instance Operator
Binary `isa` evaluates to true when the left argument is an object instance of the class (or a subclass derived from that class) given by the right argument. If the left argument is not defined, not a blessed object instance, nor does not derive from the class given by the right argument, the operator evaluates as false. The right argument may give the class either as a bareword or a scalar expression that yields a string class name:
```
if( $obj isa Some::Class ) { ... }
if( $obj isa "Different::Class" ) { ... }
if( $obj isa $name_of_class ) { ... }
```
This feature is available from Perl 5.31.6 onwards when enabled by `use feature 'isa'`. This feature is enabled automatically by a `use v5.36` (or higher) declaration in the current scope.
###
Smartmatch Operator
First available in Perl 5.10.1 (the 5.10.0 version behaved differently), binary `~~` does a "smartmatch" between its arguments. This is mostly used implicitly in the `when` construct described in <perlsyn>, although not all `when` clauses call the smartmatch operator. Unique among all of Perl's operators, the smartmatch operator can recurse. The smartmatch operator is [experimental](perlpolicy#experimental) and its behavior is subject to change.
It is also unique in that all other Perl operators impose a context (usually string or numeric context) on their operands, autoconverting those operands to those imposed contexts. In contrast, smartmatch *infers* contexts from the actual types of its operands and uses that type information to select a suitable comparison mechanism.
The `~~` operator compares its operands "polymorphically", determining how to compare them according to their actual types (numeric, string, array, hash, etc.). Like the equality operators with which it shares the same precedence, `~~` returns 1 for true and `""` for false. It is often best read aloud as "in", "inside of", or "is contained in", because the left operand is often looked for *inside* the right operand. That makes the order of the operands to the smartmatch operand often opposite that of the regular match operator. In other words, the "smaller" thing is usually placed in the left operand and the larger one in the right.
The behavior of a smartmatch depends on what type of things its arguments are, as determined by the following table. The first row of the table whose types apply determines the smartmatch behavior. Because what actually happens is mostly determined by the type of the second operand, the table is sorted on the right operand instead of on the left.
```
Left Right Description and pseudocode
===============================================================
Any undef check whether Any is undefined
like: !defined Any
Any Object invoke ~~ overloading on Object, or die
Right operand is an ARRAY:
Left Right Description and pseudocode
===============================================================
ARRAY1 ARRAY2 recurse on paired elements of ARRAY1 and ARRAY2[2]
like: (ARRAY1[0] ~~ ARRAY2[0])
&& (ARRAY1[1] ~~ ARRAY2[1]) && ...
HASH ARRAY any ARRAY elements exist as HASH keys
like: grep { exists HASH->{$_} } ARRAY
Regexp ARRAY any ARRAY elements pattern match Regexp
like: grep { /Regexp/ } ARRAY
undef ARRAY undef in ARRAY
like: grep { !defined } ARRAY
Any ARRAY smartmatch each ARRAY element[3]
like: grep { Any ~~ $_ } ARRAY
Right operand is a HASH:
Left Right Description and pseudocode
===============================================================
HASH1 HASH2 all same keys in both HASHes
like: keys HASH1 ==
grep { exists HASH2->{$_} } keys HASH1
ARRAY HASH any ARRAY elements exist as HASH keys
like: grep { exists HASH->{$_} } ARRAY
Regexp HASH any HASH keys pattern match Regexp
like: grep { /Regexp/ } keys HASH
undef HASH always false (undef cannot be a key)
like: 0 == 1
Any HASH HASH key existence
like: exists HASH->{Any}
Right operand is CODE:
Left Right Description and pseudocode
===============================================================
ARRAY CODE sub returns true on all ARRAY elements[1]
like: !grep { !CODE->($_) } ARRAY
HASH CODE sub returns true on all HASH keys[1]
like: !grep { !CODE->($_) } keys HASH
Any CODE sub passed Any returns true
like: CODE->(Any)
Right operand is a Regexp:
Left Right Description and pseudocode
===============================================================
ARRAY Regexp any ARRAY elements match Regexp
like: grep { /Regexp/ } ARRAY
HASH Regexp any HASH keys match Regexp
like: grep { /Regexp/ } keys HASH
Any Regexp pattern match
like: Any =~ /Regexp/
Other:
Left Right Description and pseudocode
===============================================================
Object Any invoke ~~ overloading on Object,
or fall back to...
Any Num numeric equality
like: Any == Num
Num nummy[4] numeric equality
like: Num == nummy
undef Any check whether undefined
like: !defined(Any)
Any Any string equality
like: Any eq Any
```
Notes:
1. Empty hashes or arrays match.
2. That is, each element smartmatches the element of the same index in the other array.[3]
3. If a circular reference is found, fall back to referential equality.
4. Either an actual number, or a string that looks like one. The smartmatch implicitly dereferences any non-blessed hash or array reference, so the `*HASH*` and `*ARRAY*` entries apply in those cases. For blessed references, the `*Object*` entries apply. Smartmatches involving hashes only consider hash keys, never hash values.
The "like" code entry is not always an exact rendition. For example, the smartmatch operator short-circuits whenever possible, but `grep` does not. Also, `grep` in scalar context returns the number of matches, but `~~` returns only true or false.
Unlike most operators, the smartmatch operator knows to treat `undef` specially:
```
use v5.10.1;
@array = (1, 2, 3, undef, 4, 5);
say "some elements undefined" if undef ~~ @array;
```
Each operand is considered in a modified scalar context, the modification being that array and hash variables are passed by reference to the operator, which implicitly dereferences them. Both elements of each pair are the same:
```
use v5.10.1;
my %hash = (red => 1, blue => 2, green => 3,
orange => 4, yellow => 5, purple => 6,
black => 7, grey => 8, white => 9);
my @array = qw(red blue green);
say "some array elements in hash keys" if @array ~~ %hash;
say "some array elements in hash keys" if \@array ~~ \%hash;
say "red in array" if "red" ~~ @array;
say "red in array" if "red" ~~ \@array;
say "some keys end in e" if /e$/ ~~ %hash;
say "some keys end in e" if /e$/ ~~ \%hash;
```
Two arrays smartmatch if each element in the first array smartmatches (that is, is "in") the corresponding element in the second array, recursively.
```
use v5.10.1;
my @little = qw(red blue green);
my @bigger = ("red", "blue", [ "orange", "green" ] );
if (@little ~~ @bigger) { # true!
say "little is contained in bigger";
}
```
Because the smartmatch operator recurses on nested arrays, this will still report that "red" is in the array.
```
use v5.10.1;
my @array = qw(red blue green);
my $nested_array = [[[[[[[ @array ]]]]]]];
say "red in array" if "red" ~~ $nested_array;
```
If two arrays smartmatch each other, then they are deep copies of each others' values, as this example reports:
```
use v5.12.0;
my @a = (0, 1, 2, [3, [4, 5], 6], 7);
my @b = (0, 1, 2, [3, [4, 5], 6], 7);
if (@a ~~ @b && @b ~~ @a) {
say "a and b are deep copies of each other";
}
elsif (@a ~~ @b) {
say "a smartmatches in b";
}
elsif (@b ~~ @a) {
say "b smartmatches in a";
}
else {
say "a and b don't smartmatch each other at all";
}
```
If you were to set `$b[3] = 4`, then instead of reporting that "a and b are deep copies of each other", it now reports that `"b smartmatches in a"`. That's because the corresponding position in `@a` contains an array that (eventually) has a 4 in it.
Smartmatching one hash against another reports whether both contain the same keys, no more and no less. This could be used to see whether two records have the same field names, without caring what values those fields might have. For example:
```
use v5.10.1;
sub make_dogtag {
state $REQUIRED_FIELDS = { name=>1, rank=>1, serial_num=>1 };
my ($class, $init_fields) = @_;
die "Must supply (only) name, rank, and serial number"
unless $init_fields ~~ $REQUIRED_FIELDS;
...
}
```
However, this only does what you mean if `$init_fields` is indeed a hash reference. The condition `$init_fields ~~ $REQUIRED_FIELDS` also allows the strings `"name"`, `"rank"`, `"serial_num"` as well as any array reference that contains `"name"` or `"rank"` or `"serial_num"` anywhere to pass through.
The smartmatch operator is most often used as the implicit operator of a `when` clause. See the section on "Switch Statements" in <perlsyn>.
####
Smartmatching of Objects
To avoid relying on an object's underlying representation, if the smartmatch's right operand is an object that doesn't overload `~~`, it raises the exception "`Smartmatching a non-overloaded object breaks encapsulation`". That's because one has no business digging around to see whether something is "in" an object. These are all illegal on objects without a `~~` overload:
```
%hash ~~ $object
42 ~~ $object
"fred" ~~ $object
```
However, you can change the way an object is smartmatched by overloading the `~~` operator. This is allowed to extend the usual smartmatch semantics. For objects that do have an `~~` overload, see <overload>.
Using an object as the left operand is allowed, although not very useful. Smartmatching rules take precedence over overloading, so even if the object in the left operand has smartmatch overloading, this will be ignored. A left operand that is a non-overloaded object falls back on a string or numeric comparison of whatever the `ref` operator returns. That means that
```
$object ~~ X
```
does *not* invoke the overload method with `*X*` as an argument. Instead the above table is consulted as normal, and based on the type of `*X*`, overloading may or may not be invoked. For simple strings or numbers, "in" becomes equivalent to this:
```
$object ~~ $number ref($object) == $number
$object ~~ $string ref($object) eq $string
```
For example, this reports that the handle smells IOish (but please don't really do this!):
```
use IO::Handle;
my $fh = IO::Handle->new();
if ($fh ~~ /\bIO\b/) {
say "handle smells IOish";
}
```
That's because it treats `$fh` as a string like `"IO::Handle=GLOB(0x8039e0)"`, then pattern matches against that.
###
Bitwise And
Binary `"&"` returns its operands ANDed together bit by bit. Although no warning is currently raised, the result is not well defined when this operation is performed on operands that aren't either numbers (see ["Integer Arithmetic"](#Integer-Arithmetic)) nor bitstrings (see ["Bitwise String Operators"](#Bitwise-String-Operators)).
Note that `"&"` has lower priority than relational operators, so for example the parentheses are essential in a test like
```
print "Even\n" if ($x & 1) == 0;
```
If the "bitwise" feature is enabled via `use feature 'bitwise'` or `use v5.28`, then this operator always treats its operands as numbers. Before Perl 5.28 this feature produced a warning in the `"experimental::bitwise"` category.
###
Bitwise Or and Exclusive Or
Binary `"|"` returns its operands ORed together bit by bit.
Binary `"^"` returns its operands XORed together bit by bit.
Although no warning is currently raised, the results are not well defined when these operations are performed on operands that aren't either numbers (see ["Integer Arithmetic"](#Integer-Arithmetic)) nor bitstrings (see ["Bitwise String Operators"](#Bitwise-String-Operators)).
Note that `"|"` and `"^"` have lower priority than relational operators, so for example the parentheses are essential in a test like
```
print "false\n" if (8 | 2) != 10;
```
If the "bitwise" feature is enabled via `use feature 'bitwise'` or `use v5.28`, then this operator always treats its operands as numbers. Before Perl 5.28. this feature produced a warning in the `"experimental::bitwise"` category.
###
C-style Logical And
Binary `"&&"` performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.
###
C-style Logical Or
Binary `"||"` performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.
###
Logical Defined-Or
Although it has no direct equivalent in C, Perl's `//` operator is related to its C-style "or". In fact, it's exactly the same as `||`, except that it tests the left hand side's definedness instead of its truth. Thus, `EXPR1 // EXPR2` returns the value of `EXPR1` if it's defined, otherwise, the value of `EXPR2` is returned. (`EXPR1` is evaluated in scalar context, `EXPR2` in the context of `//` itself). Usually, this is the same result as `defined(EXPR1) ? EXPR1 : EXPR2` (except that the ternary-operator form can be used as a lvalue, while `EXPR1 // EXPR2` cannot). This is very useful for providing default values for variables. If you actually want to test if at least one of `$x` and `$y` is defined, use `defined($x // $y)`.
The `||`, `//` and `&&` operators return the last value evaluated (unlike C's `||` and `&&`, which return 0 or 1). Thus, a reasonably portable way to find out the home directory might be:
```
$home = $ENV{HOME}
// $ENV{LOGDIR}
// (getpwuid($<))[7]
// die "You're homeless!\n";
```
In particular, this means that you shouldn't use this for selecting between two aggregates for assignment:
```
@a = @b || @c; # This doesn't do the right thing
@a = scalar(@b) || @c; # because it really means this.
@a = @b ? @b : @c; # This works fine, though.
```
As alternatives to `&&` and `||` when used for control flow, Perl provides the `and` and `or` operators (see below). The short-circuit behavior is identical. The precedence of `"and"` and `"or"` is much lower, however, so that you can safely use them after a list operator without the need for parentheses:
```
unlink "alpha", "beta", "gamma"
or gripe(), next LINE;
```
With the C-style operators that would have been written like this:
```
unlink("alpha", "beta", "gamma")
|| (gripe(), next LINE);
```
It would be even more readable to write that this way:
```
unless(unlink("alpha", "beta", "gamma")) {
gripe();
next LINE;
}
```
Using `"or"` for assignment is unlikely to do what you want; see below.
###
Range Operators
Binary `".."` is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list. The range operator is useful for writing `foreach (1..10)` loops and for doing slice operations on arrays. In the current implementation, no temporary array is created when the range operator is used as the expression in `foreach` loops, but older versions of Perl might burn a lot of memory when you write something like this:
```
for (1 .. 1_000_000) {
# code
}
```
The range operator also works on strings, using the magical auto-increment, see below.
In scalar context, `".."` returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of **sed**, **awk**, and various editors. Each `".."` operator maintains its own boolean state, even across calls to a subroutine that contains it. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, *AFTER* which the range operator becomes false again. It doesn't become false till the next time the range operator is evaluated. It can test the right operand and become false on the same evaluation it became true (as in **awk**), but it still returns true once. If you don't want it to test the right operand until the next evaluation, as in **sed**, just use three dots (`"..."`) instead of two. In all other regards, `"..."` behaves just like `".."` does.
The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state. The precedence is a little lower than || and &&. The value returned is either the empty string for false, or a sequence number (beginning with 1) for true. The sequence number is reset for each range encountered. The final sequence number in a range has the string `"E0"` appended to it, which doesn't affect its numeric value, but gives you something to search for if you want to exclude the endpoint. You can exclude the beginning point by waiting for the sequence number to be greater than 1.
If either operand of scalar `".."` is a constant expression, that operand is considered true if it is equal (`==`) to the current input line number (the `$.` variable).
To be pedantic, the comparison is actually `int(EXPR) == int(EXPR)`, but that is only an issue if you use a floating point expression; when implicitly using `$.` as described in the previous paragraph, the comparison is `int(EXPR) == int($.)` which is only an issue when `$.` is set to a floating point value and you are not reading from a file. Furthermore, `"span" .. "spat"` or `2.18 .. 3.14` will not do what you want in scalar context because each of the operands are evaluated using their integer representation.
Examples:
As a scalar operator:
```
if (101 .. 200) { print; } # print 2nd hundred lines, short for
# if ($. == 101 .. $. == 200) { print; }
next LINE if (1 .. /^$/); # skip header lines, short for
# next LINE if ($. == 1 .. /^$/);
# (typically in a loop labeled LINE)
s/^/> / if (/^$/ .. eof()); # quote body
# parse mail messages
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof;
if ($in_header) {
# do something
} else { # in body
# do something else
}
} continue {
close ARGV if eof; # reset $. each file
}
```
Here's a simple example to illustrate the difference between the two range operators:
```
@lines = (" - Foo",
"01 - Bar",
"1 - Baz",
" - Quux");
foreach (@lines) {
if (/0/ .. /1/) {
print "$_\n";
}
}
```
This program will print only the line containing "Bar". If the range operator is changed to `...`, it will also print the "Baz" line.
And now some examples as a list operator:
```
for (101 .. 200) { print } # print $_ 100 times
@foo = @foo[0 .. $#foo]; # an expensive no-op
@foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
```
Because each operand is evaluated in integer form, `2.18 .. 3.14` will return two elements in list context.
```
@list = (2.18 .. 3.14); # same as @list = (2 .. 3);
```
The range operator in list context can make use of the magical auto-increment algorithm if both operands are strings, subject to the following rules:
* With one exception (below), if both strings look like numbers to Perl, the magic increment will not be applied, and the strings will be treated as numbers (more specifically, integers) instead.
For example, `"-2".."2"` is the same as `-2..2`, and `"2.18".."3.14"` produces `2, 3`.
* The exception to the above rule is when the left-hand string begins with `0` and is longer than one character, in this case the magic increment *will* be applied, even though strings like `"01"` would normally look like a number to Perl.
For example, `"01".."04"` produces `"01", "02", "03", "04"`, and `"00".."-1"` produces `"00"` through `"99"` - this may seem surprising, but see the following rules for why it works this way. To get dates with leading zeros, you can say:
```
@z2 = ("01" .. "31");
print $z2[$mday];
```
If you want to force strings to be interpreted as numbers, you could say
```
@numbers = ( 0+$first .. 0+$last );
```
**Note:** In Perl versions 5.30 and below, *any* string on the left-hand side beginning with `"0"`, including the string `"0"` itself, would cause the magic string increment behavior. This means that on these Perl versions, `"0".."-1"` would produce `"0"` through `"99"`, which was inconsistent with `0..-1`, which produces the empty list. This also means that `"0".."9"` now produces a list of integers instead of a list of strings.
* If the initial value specified isn't part of a magical increment sequence (that is, a non-empty string matching `/^[a-zA-Z]*[0-9]*\z/`), only the initial value will be returned.
For example, `"ax".."az"` produces `"ax", "ay", "az"`, but `"*x".."az"` produces only `"*x"`.
* For other initial values that are strings that do follow the rules of the magical increment, the corresponding sequence will be returned.
For example, you can say
```
@alphabet = ("A" .. "Z");
```
to get all normal letters of the English alphabet, or
```
$hexdigit = (0 .. 9, "a" .. "f")[$num & 15];
```
to get a hexadecimal digit.
* If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified. If the length of the final string is shorter than the first, the empty list is returned.
For example, `"a".."--"` is the same as `"a".."zz"`, `"0".."xx"` produces `"0"` through `"99"`, and `"aaa".."--"` returns the empty list.
As of Perl 5.26, the list-context range operator on strings works as expected in the scope of [`"use feature 'unicode_strings"`](feature#The-%27unicode_strings%27-feature). In previous versions, and outside the scope of that feature, it exhibits ["The "Unicode Bug"" in perlunicode](perlunicode#The-%22Unicode-Bug%22): its behavior depends on the internal encoding of the range endpoint.
Because the magical increment only works on non-empty strings matching `/^[a-zA-Z]*[0-9]*\z/`, the following will only return an alpha:
```
use charnames "greek";
my @greek_small = ("\N{alpha}" .. "\N{omega}");
```
To get the 25 traditional lowercase Greek letters, including both sigmas, you could use this instead:
```
use charnames "greek";
my @greek_small = map { chr } ( ord("\N{alpha}")
..
ord("\N{omega}")
);
```
However, because there are *many* other lowercase Greek characters than just those, to match lowercase Greek characters in a regular expression, you could use the pattern `/(?:(?=\p{Greek})\p{Lower})+/` (or the [experimental feature](perlrecharclass#Extended-Bracketed-Character-Classes) `/(?[ \p{Greek} & \p{Lower} ])+/`).
###
Conditional Operator
Ternary `"?:"` is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the `?` is true, the argument before the `:` is returned, otherwise the argument after the `:` is returned. For example:
```
printf "I have %d dog%s.\n", $n,
($n == 1) ? "" : "s";
```
Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected.
```
$x = $ok ? $y : $z; # get a scalar
@x = $ok ? @y : @z; # get an array
$x = $ok ? @y : @z; # oops, that's just a count!
```
The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning that you can assign to them):
```
($x_or_y ? $x : $y) = $z;
```
Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:
```
$x % 2 ? $x += 10 : $x += 2
```
Really means this:
```
(($x % 2) ? ($x += 10) : $x) += 2
```
Rather than this:
```
($x % 2) ? ($x += 10) : ($x += 2)
```
That should probably be written more simply as:
```
$x += ($x % 2) ? 10 : 2;
```
###
Assignment Operators
`"="` is the ordinary assignment operator.
Assignment operators work as in C. That is,
```
$x += 2;
```
is equivalent to
```
$x = $x + 2;
```
although without duplicating any side effects that dereferencing the lvalue might trigger, such as from `tie()`. Other assignment operators work similarly. The following are recognized:
```
**= += *= &= &.= <<= &&=
-= /= |= |.= >>= ||=
.= %= ^= ^.= //=
x=
```
Although these are grouped by family, they all have the precedence of assignment. These combined assignment operators can only operate on scalars, whereas the ordinary assignment operator can assign to arrays, hashes, lists and even references. (See ["Context"](perldata#Context) and ["List value constructors" in perldata](perldata#List-value-constructors), and ["Assigning to References" in perlref](perlref#Assigning-to-References).)
Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:
```
($tmp = $global) =~ tr/13579/24680/;
```
Although as of 5.14, that can be also be accomplished this way:
```
use v5.14;
$tmp = ($global =~ tr/13579/24680/r);
```
Likewise,
```
($x += 2) *= 3;
```
is equivalent to
```
$x += 2;
$x *= 3;
```
Similarly, a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment.
The three dotted bitwise assignment operators (`&.=` `|.=` `^.=`) are new in Perl 5.22. See ["Bitwise String Operators"](#Bitwise-String-Operators).
###
Comma Operator
Binary `","` is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator.
In list context, it's just the list argument separator, and inserts both its arguments into the list. These arguments are also evaluated from left to right.
The `=>` operator (sometimes pronounced "fat comma") is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behavior, the left operand can be quoted explicitly.
Otherwise, the `=>` operator behaves exactly as the comma operator or list argument separator, according to context.
For example:
```
use constant FOO => "something";
my %h = ( FOO => 23 );
```
is equivalent to:
```
my %h = ("FOO", 23);
```
It is *NOT*:
```
my %h = ("something", 23);
```
The `=>` operator is helpful in documenting the correspondence between keys and values in hashes, and other paired elements in lists.
```
%hash = ( $key => $value );
login( $username => $password );
```
The special quoting behavior ignores precedence, and hence may apply to *part* of the left operand:
```
print time.shift => "bbb";
```
That example prints something like `"1314363215shiftbbb"`, because the `=>` implicitly quotes the `shift` immediately on its left, ignoring the fact that `time.shift` is the entire left operand.
###
List Operators (Rightward)
On the right side of a list operator, the comma has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators `"and"`, `"or"`, and `"not"`, which may be used to evaluate calls to list operators without the need for parentheses:
```
open HANDLE, "< :encoding(UTF-8)", "filename"
or die "Can't open: $!\n";
```
However, some people find that code harder to read than writing it with parentheses:
```
open(HANDLE, "< :encoding(UTF-8)", "filename")
or die "Can't open: $!\n";
```
in which case you might as well just use the more customary `"||"` operator:
```
open(HANDLE, "< :encoding(UTF-8)", "filename")
|| die "Can't open: $!\n";
```
See also discussion of list operators in ["Terms and List Operators (Leftward)"](#Terms-and-List-Operators-%28Leftward%29).
###
Logical Not
Unary `"not"` returns the logical negation of the expression to its right. It's the equivalent of `"!"` except for the very low precedence.
###
Logical And
Binary `"and"` returns the logical conjunction of the two surrounding expressions. It's equivalent to `&&` except for the very low precedence. This means that it short-circuits: the right expression is evaluated only if the left expression is true.
###
Logical or and Exclusive Or
Binary `"or"` returns the logical disjunction of the two surrounding expressions. It's equivalent to `||` except for the very low precedence. This makes it useful for control flow:
```
print FH $data or die "Can't write to FH: $!";
```
This means that it short-circuits: the right expression is evaluated only if the left expression is false. Due to its precedence, you must be careful to avoid using it as replacement for the `||` operator. It usually works out better for flow control than in assignments:
```
$x = $y or $z; # bug: this is wrong
($x = $y) or $z; # really means this
$x = $y || $z; # better written this way
```
However, when it's a list-context assignment and you're trying to use `||` for control flow, you probably need `"or"` so that the assignment takes higher precedence.
```
@info = stat($file) || die; # oops, scalar sense of stat!
@info = stat($file) or die; # better, now @info gets its due
```
Then again, you could always use parentheses.
Binary `"xor"` returns the exclusive-OR of the two surrounding expressions. It cannot short-circuit (of course).
There is no low precedence operator for defined-OR.
###
C Operators Missing From Perl
Here is what C has that Perl doesn't:
unary & Address-of operator. (But see the `"\"` operator for taking a reference.)
unary \* Dereference-address operator. (Perl's prefix dereferencing operators are typed: `$`, `@`, `%`, and `&`.)
(TYPE) Type-casting operator.
###
Quote and Quote-like Operators
While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a `{}` represents any pair of delimiters you choose.
```
Customary Generic Meaning Interpolates
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)
y{}{} Transliteration no (but see below)
<<EOF here-doc yes*
* unless the delimiter is ''.
```
Non-bracketing delimiters use the same character fore and aft, but the four sorts of ASCII brackets (round, angle, square, curly) all nest, which means that
```
q{foo{bar}baz}
```
is the same as
```
'foo{bar}baz'
```
Note, however, that this does not always work for quoting Perl code:
```
$s = q{ if($x eq "}") ... }; # WRONG
```
is a syntax error. The `<Text::Balanced>` module (standard as of v5.8, and from CPAN before then) is able to do this properly.
There can (and in some cases, must) be whitespace between the operator and the quoting characters, except when `#` is being used as the quoting character. `q#foo#` is parsed as the string `foo`, while `q #foo#` is the operator `q` followed by a comment. Its argument will be taken from the next line. This allows you to write:
```
s {foo} # Replace foo
{bar} # with bar.
```
The cases where whitespace must be used are when the quoting character is a word character (meaning it matches `/\w/`):
```
q XfooX # Works: means the string 'foo'
qXfooX # WRONG!
```
The following escape sequences are available in constructs that interpolate, and in transliterations whose delimiters aren't single quotes (`"'"`). In all the ones with braces, any number of blanks and/or tabs adjoining and within the braces are allowed (and ignored).
```
Sequence Note Description
\t tab (HT, TAB)
\n newline (NL)
\r return (CR)
\f form feed (FF)
\b backspace (BS)
\a alarm (bell) (BEL)
\e escape (ESC)
\x{263A} [1,8] hex char (example shown: SMILEY)
\x{ 263A } Same, but shows optional blanks inside and
adjoining the braces
\x1b [2,8] restricted range hex char (example: ESC)
\N{name} [3] named Unicode character or character sequence
\N{U+263D} [4,8] Unicode character (example: FIRST QUARTER MOON)
\c[ [5] control char (example: chr(27))
\o{23072} [6,8] octal char (example: SMILEY)
\033 [7,8] restricted range octal char (example: ESC)
```
Note that any escape sequence using braces inside interpolated constructs may have optional blanks (tab or space characters) adjoining with and inside of the braces, as illustrated above by the second `\x{ }` example.
[1] The result is the character specified by the hexadecimal number between the braces. See ["[8]"](#%5B8%5D) below for details on which character.
Blanks (tab or space characters) may separate the number from either or both of the braces.
Otherwise, only hexadecimal digits are valid between the braces. If an invalid character is encountered, a warning will be issued and the invalid character and all subsequent characters (valid or invalid) within the braces will be discarded.
If there are no valid digits between the braces, the generated character is the NULL character (`\x{00}`). However, an explicit empty brace (`\x{}`) will not cause a warning (currently).
[2] The result is the character specified by the hexadecimal number in the range 0x00 to 0xFF. See ["[8]"](#%5B8%5D) below for details on which character.
Only hexadecimal digits are valid following `\x`. When `\x` is followed by fewer than two valid digits, any valid digits will be zero-padded. This means that `\x7` will be interpreted as `\x07`, and a lone `"\x"` will be interpreted as `\x00`. Except at the end of a string, having fewer than two valid digits will result in a warning. Note that although the warning says the illegal character is ignored, it is only ignored as part of the escape and will still be used as the subsequent character in the string. For example:
```
Original Result Warns?
"\x7" "\x07" no
"\x" "\x00" no
"\x7q" "\x07q" yes
"\xq" "\x00q" yes
```
[3] The result is the Unicode character or character sequence given by *name*. See <charnames>.
[4] `\N{U+*hexadecimal number*}` means the Unicode character whose Unicode code point is *hexadecimal number*.
[5] The character following `\c` is mapped to some other character as shown in the table:
```
Sequence Value
\c@ chr(0)
\cA chr(1)
\ca chr(1)
\cB chr(2)
\cb chr(2)
...
\cZ chr(26)
\cz chr(26)
\c[ chr(27)
# See below for chr(28)
\c] chr(29)
\c^ chr(30)
\c_ chr(31)
\c? chr(127) # (on ASCII platforms; see below for link to
# EBCDIC discussion)
```
In other words, it's the character whose code point has had 64 xor'd with its uppercase. `\c?` is DELETE on ASCII platforms because `ord("?") ^ 64` is 127, and `\c@` is NULL because the ord of `"@"` is 64, so xor'ing 64 itself produces 0.
Also, `\c\*X*` yields `chr(28) . "*X*"` for any *X*, but cannot come at the end of a string, because the backslash would be parsed as escaping the end quote.
On ASCII platforms, the resulting characters from the list above are the complete set of ASCII controls. This isn't the case on EBCDIC platforms; see ["OPERATOR DIFFERENCES" in perlebcdic](perlebcdic#OPERATOR-DIFFERENCES) for a full discussion of the differences between these for ASCII versus EBCDIC platforms.
Use of any other character following the `"c"` besides those listed above is discouraged, and as of Perl v5.20, the only characters actually allowed are the printable ASCII ones, minus the left brace `"{"`. What happens for any of the allowed other characters is that the value is derived by xor'ing with the seventh bit, which is 64, and a warning raised if enabled. Using the non-allowed characters generates a fatal error.
To get platform independent controls, you can use `\N{...}`.
[6] The result is the character specified by the octal number between the braces. See ["[8]"](#%5B8%5D) below for details on which character.
Blanks (tab or space characters) may separate the number from either or both of the braces.
Otherwise, if a character that isn't an octal digit is encountered, a warning is raised, and the value is based on the octal digits before it, discarding it and all following characters up to the closing brace. It is a fatal error if there are no octal digits at all.
[7] The result is the character specified by the three-digit octal number in the range 000 to 777 (but best to not use above 077, see next paragraph). See ["[8]"](#%5B8%5D) below for details on which character.
Some contexts allow 2 or even 1 digit, but any usage without exactly three digits, the first being a zero, may give unintended results. (For example, in a regular expression it may be confused with a backreference; see ["Octal escapes" in perlrebackslash](perlrebackslash#Octal-escapes).) Starting in Perl 5.14, you may use `\o{}` instead, which avoids all these problems. Otherwise, it is best to use this construct only for ordinals `\077` and below, remembering to pad to the left with zeros to make three digits. For larger ordinals, either use `\o{}`, or convert to something else, such as to hex and use `\N{U+}` (which is portable between platforms with different character sets) or `\x{}` instead.
[8] Several constructs above specify a character by a number. That number gives the character's position in the character set encoding (indexed from 0). This is called synonymously its ordinal, code position, or code point. Perl works on platforms that have a native encoding currently of either ASCII/Latin1 or EBCDIC, each of which allow specification of 256 characters. In general, if the number is 255 (0xFF, 0377) or below, Perl interprets this in the platform's native encoding. If the number is 256 (0x100, 0400) or above, Perl interprets it as a Unicode code point and the result is the corresponding Unicode character. For example `\x{50}` and `\o{120}` both are the number 80 in decimal, which is less than 256, so the number is interpreted in the native character set encoding. In ASCII the character in the 80th position (indexed from 0) is the letter `"P"`, and in EBCDIC it is the ampersand symbol `"&"`. `\x{100}` and `\o{400}` are both 256 in decimal, so the number is interpreted as a Unicode code point no matter what the native encoding is. The name of the character in the 256th position (indexed by 0) in Unicode is `LATIN CAPITAL LETTER A WITH MACRON`.
An exception to the above rule is that `\N{U+*hex number*}` is always interpreted as a Unicode code point, so that `\N{U+0050}` is `"P"` even on EBCDIC platforms.
**NOTE**: Unlike C and other languages, Perl has no `\v` escape sequence for the vertical tab (VT, which is 11 in both ASCII and EBCDIC), but you may use `\N{VT}`, `\ck`, `\N{U+0b}`, or `\x0b`. (`\v` does have meaning in regular expression patterns in Perl, see <perlre>.)
The following escape sequences are available in constructs that interpolate, but not in transliterations.
```
\l lowercase next character only
\u titlecase (not uppercase!) next character only
\L lowercase all characters till \E or end of string
\U uppercase all characters till \E or end of string
\F foldcase all characters till \E or end of string
\Q quote (disable) pattern metacharacters till \E or
end of string
\E end either case modification or quoted section
(whichever was last seen)
```
See ["quotemeta" in perlfunc](perlfunc#quotemeta) for the exact definition of characters that are quoted by `\Q`.
`\L`, `\U`, `\F`, and `\Q` can stack, in which case you need one `\E` for each. For example:
```
say "This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?";
This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it?
```
If a `use locale` form that includes `LC_CTYPE` is in effect (see <perllocale>), the case map used by `\l`, `\L`, `\u`, and `\U` is taken from the current locale. If Unicode (for example, `\N{}` or code points of 0x100 or beyond) is being used, the case map used by `\l`, `\L`, `\u`, and `\U` is as defined by Unicode. That means that case-mapping a single character can sometimes produce a sequence of several characters. Under `use locale`, `\F` produces the same results as `\L` for all locales but a UTF-8 one, where it instead uses the Unicode definition.
All systems use the virtual `"\n"` to represent a line terminator, called a "newline". There is no such thing as an unvarying, physical newline character. It is only an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read `"\r"` as ASCII CR and `"\n"` as ASCII LF. For example, on the ancient Macs (pre-MacOS X) of yesteryear, these used to be reversed, and on systems without a line terminator, printing `"\n"` might emit no actual data. In general, use `"\n"` when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF (`"\015\012"` or `"\cM\cJ"`) for line terminators, and although they often accept just `"\012"`, they seldom tolerate just `"\015"`. If you get in the habit of using `"\n"` for networking, you may be burned some day.
For constructs that do interpolate, variables beginning with "`$`" or "`@`" are interpolated. Subscripted variables such as `$a[3]` or `$href->{key}[0]` are also interpolated, as are array and hash slices. But method calls such as `$obj->meth` are not.
Interpolating an array or slice interpolates the elements in order, separated by the value of `$"`, so is equivalent to interpolating `join $", @array`. "Punctuation" arrays such as `@*` are usually interpolated only if the name is enclosed in braces `@{*}`, but the arrays `@_`, `@+`, and `@-` are interpolated even without braces.
For double-quoted strings, the quoting from `\Q` is applied after interpolation and escapes are processed.
```
"abc\Qfoo\tbar$s\Exyz"
```
is equivalent to
```
"abc" . quotemeta("foo\tbar$s") . "xyz"
```
For the pattern of regex operators (`qr//`, `m//` and `s///`), the quoting from `\Q` is applied after interpolation is processed, but before escapes are processed. This allows the pattern to match literally (except for `$` and `@`). For example, the following matches:
```
'\s\t' =~ /\Q\s\t/
```
Because `$` or `@` trigger interpolation, you'll need to use something like `/\Quser\E\@\Qhost/` to match them literally.
Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables. If this is not what you want, use `\Q` to interpolate a variable literally.
Apart from the behavior described above, Perl does not expand multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do *NOT* interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes.
###
Regexp Quote-Like Operators
Here are the quote-like operators that apply to pattern matching and related activities.
`qr/*STRING*/msixpodualn` This operator quotes (and possibly compiles) its *STRING* as a regular expression. *STRING* is interpolated the same way as *PATTERN* in `m/*PATTERN*/`. If `"'"` is used as the delimiter, no variable interpolation is done. Returns a Perl value which may be used instead of the corresponding `/*STRING*/msixpodualn` expression. The returned value is a normalized version of the original pattern. It magically differs from a string containing the same characters: `ref(qr/x/)` returns "Regexp"; however, dereferencing it is not well defined (you currently get the normalized version of the original pattern, but this may change).
For example,
```
$rex = qr/my.STRING/is;
print $rex; # prints (?si-xm:my.STRING)
s/$rex/foo/;
```
is equivalent to
```
s/my.STRING/foo/is;
```
The result may be used as a subpattern in a match:
```
$re = qr/$pattern/;
$string =~ /foo${re}bar/; # can be interpolated in other
# patterns
$string =~ $re; # or used standalone
$string =~ /$re/; # or this way
```
Since Perl may compile the pattern at the moment of execution of the `qr()` operator, using `qr()` may have speed advantages in some situations, notably if the result of `qr()` is used standalone:
```
sub match {
my $patterns = shift;
my @compiled = map qr/$_/i, @$patterns;
grep {
my $success = 0;
foreach my $pat (@compiled) {
$success = 1, last if /$pat/;
}
$success;
} @_;
}
```
Precompilation of the pattern into an internal representation at the moment of `qr()` avoids the need to recompile the pattern every time a match `/$pat/` is attempted. (Perl has many other internal optimizations, but none would be triggered in the above example if we did not use `qr()` operator.)
Options (specified by the following modifiers) are:
```
m Treat string as multiple lines.
s Treat string as single line. (Make . match a newline)
i Do case-insensitive pattern matching.
x Use extended regular expressions; specifying two
x's means \t and the SPACE character are ignored within
square-bracketed character classes
p When matching preserve a copy of the matched string so
that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be
defined (ignored starting in v5.20) as these are always
defined starting in that release
o Compile pattern only once.
a ASCII-restrict: Use ASCII for \d, \s, \w and [[:posix:]]
character classes; specifying two a's adds the further
restriction that no ASCII character will match a
non-ASCII one under /i.
l Use the current run-time locale's rules.
u Use Unicode rules.
d Use Unicode or native charset, as in 5.12 and earlier.
n Non-capture mode. Don't let () fill in $1, $2, etc...
```
If a precompiled pattern is embedded in a larger pattern then the effect of `"msixpluadn"` will be propagated appropriately. The effect that the `/o` modifier has is not propagated, being restricted to those patterns explicitly using it.
The `/a`, `/d`, `/l`, and `/u` modifiers (added in Perl 5.14) control the character set rules, but `/a` is the only one you are likely to want to specify explicitly; the other three are selected automatically by various pragmas.
See <perlre> for additional information on valid syntax for *STRING*, and for a detailed look at the semantics of regular expressions. In particular, all modifiers except the largely obsolete `/o` are further explained in ["Modifiers" in perlre](perlre#Modifiers). `/o` is described in the next section.
`m/*PATTERN*/msixpodualngc`
`/*PATTERN*/msixpodualngc`
Searches a string for a pattern match, and in scalar context returns true if it succeeds, false if it fails. If no string is specified via the `=~` or `!~` operator, the `$_` string is searched. (The string specified with `=~` need not be an lvalue--it may be the result of an expression evaluation, but remember the `=~` binds rather tightly.) See also <perlre>.
Options are as described in `qr//` above; in addition, the following match process modifiers are available:
```
g Match globally, i.e., find all occurrences.
c Do not reset search position on a failed match when /g is
in effect.
```
If `"/"` is the delimiter then the initial `m` is optional. With the `m` you can use any pair of non-whitespace (ASCII) characters as delimiters. This is particularly useful for matching path names that contain `"/"`, to avoid LTS (leaning toothpick syndrome). If `"?"` is the delimiter, then a match-only-once rule applies, described in `m?*PATTERN*?` below. If `"'"` (single quote) is the delimiter, no variable interpolation is performed on the *PATTERN*. When using a delimiter character valid in an identifier, whitespace is required after the `m`.
*PATTERN* may contain variables, which will be interpolated every time the pattern search is evaluated, except for when the delimiter is a single quote. (Note that `$(`, `$)`, and `$|` are not interpolated because they look like end-of-string tests.) Perl will not recompile the pattern unless an interpolated variable that it contains changes. You can force Perl to skip the test and never recompile by adding a `/o` (which stands for "once") after the trailing delimiter. Once upon a time, Perl would recompile regular expressions unnecessarily, and this modifier was useful to tell it not to do so, in the interests of speed. But now, the only reasons to use `/o` are one of:
1. The variables are thousands of characters long and you know that they don't change, and you need to wring out the last little bit of speed by having Perl skip testing for that. (There is a maintenance penalty for doing this, as mentioning `/o` constitutes a promise that you won't change the variables in the pattern. If you do change them, Perl won't even notice.)
2. you want the pattern to use the initial values of the variables regardless of whether they change or not. (But there are saner ways of accomplishing this than using `/o`.)
3. If the pattern contains embedded code, such as
```
use re 'eval';
$code = 'foo(?{ $x })';
/$code/
```
then perl will recompile each time, even though the pattern string hasn't changed, to ensure that the current value of `$x` is seen each time. Use `/o` if you want to avoid this.
The bottom line is that using `/o` is almost never a good idea.
The empty pattern `//`
If the *PATTERN* evaluates to the empty string, the last *successfully* matched regular expression is used instead. In this case, only the `g` and `c` flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match).
Note that it's possible to confuse Perl into thinking `//` (the empty regex) is really `//` (the defined-or operator). Perl is usually pretty good about this, but some pathological cases might trigger this, such as `$x///` (is that `($x) / (//)` or `$x // /`?) and `print $fh //` (`print $fh(//` or `print($fh //`?). In all of these examples, Perl will assume you meant defined-or. If you meant the empty regex, just use parentheses or spaces to disambiguate, or even prefix the empty regex with an `m` (so `//` becomes `m//`).
Matching in list context If the `/g` option is not used, `m//` in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, that is, (`$1`, `$2`, `$3`...) (Note that here `$1` etc. are also set). When there are no parentheses in the pattern, the return value is the list `(1)` for success. With or without parentheses, an empty list is returned upon failure.
Examples:
```
open(TTY, "+</dev/tty")
|| die "can't access /dev/tty: $!";
<TTY> =~ /^y/i && foo(); # do foo if desired
if (/Version: *([0-9.]*)/) { $version = $1; }
next if m#^/usr/spool/uucp#;
# poor man's grep
$arg = shift;
while (<>) {
print if /$arg/o; # compile only once (no longer needed!)
}
if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
```
This last example splits `$foo` into the first two words and the remainder of the line, and assigns those three fields to `$F1`, `$F2`, and `$Etc`. The conditional is true if any variables were assigned; that is, if the pattern matched.
The `/g` modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.
In scalar context, each execution of `m//g` finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the `pos()` function; see ["pos" in perlfunc](perlfunc#pos). A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the `/c` modifier (for example, `m//gc`). Modifying the target string also resets the search position.
`\G *assertion*`
You can intermix `m//g` matches with `m/\G.../g`, where `\G` is a zero-width assertion that matches the exact position where the previous `m//g`, if any, left off. Without the `/g` modifier, the `\G` assertion still anchors at `pos()` as it was at the start of the operation (see ["pos" in perlfunc](perlfunc#pos)), but the match is of course only attempted once. Using `\G` without `/g` on a target string that has not previously had a `/g` match applied to it is the same as using the `\A` assertion to match the beginning of the string. Note also that, currently, `\G` is only properly supported when anchored at the very beginning of the pattern.
Examples:
```
# list context
($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
# scalar context
local $/ = "";
while ($paragraph = <>) {
while ($paragraph =~ /\p{Ll}['")]*[.!?]+['")]*\s/g) {
$sentences++;
}
}
say $sentences;
```
Here's another way to check for sentences in a paragraph:
```
my $sentence_rx = qr{
(?: (?<= ^ ) | (?<= \s ) ) # after start-of-string or
# whitespace
\p{Lu} # capital letter
.*? # a bunch of anything
(?<= \S ) # that ends in non-
# whitespace
(?<! \b [DMS]r ) # but isn't a common abbr.
(?<! \b Mrs )
(?<! \b Sra )
(?<! \b St )
[.?!] # followed by a sentence
# ender
(?= $ | \s ) # in front of end-of-string
# or whitespace
}sx;
local $/ = "";
while (my $paragraph = <>) {
say "NEW PARAGRAPH";
my $count = 0;
while ($paragraph =~ /($sentence_rx)/g) {
printf "\tgot sentence %d: <%s>\n", ++$count, $1;
}
}
```
Here's how to use `m//gc` with `\G`:
```
$_ = "ppooqppqq";
while ($i++ < 2) {
print "1: '";
print $1 while /(o)/gc; print "', pos=", pos, "\n";
print "2: '";
print $1 if /\G(q)/gc; print "', pos=", pos, "\n";
print "3: '";
print $1 while /(p)/gc; print "', pos=", pos, "\n";
}
print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
```
The last example should print:
```
1: 'oo', pos=4
2: 'q', pos=5
3: 'pp', pos=7
1: '', pos=7
2: 'q', pos=8
3: '', pos=8
Final: 'q', pos=8
```
Notice that the final match matched `q` instead of `p`, which a match without the `\G` anchor would have done. Also note that the final match did not update `pos`. `pos` is only updated on a `/g` match. If the final match did indeed match `p`, it's a good bet that you're running an ancient (pre-5.6.0) version of Perl.
A useful idiom for `lex`-like scanners is `/\G.../gc`. You can combine several regexps like this to process a string part-by-part, doing different actions depending on which regexp matched. Each regexp tries to match where the previous one leaves off.
```
$_ = <<'EOL';
$url = URI::URL->new( "http://example.com/" );
die if $url eq "xXx";
EOL
LOOP: {
print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
print(" lowercase"), redo LOOP
if /\G\p{Ll}+\b[,.;]?\s*/gc;
print(" UPPERCASE"), redo LOOP
if /\G\p{Lu}+\b[,.;]?\s*/gc;
print(" Capitalized"), redo LOOP
if /\G\p{Lu}\p{Ll}+\b[,.;]?\s*/gc;
print(" MiXeD"), redo LOOP if /\G\pL+\b[,.;]?\s*/gc;
print(" alphanumeric"), redo LOOP
if /\G[\p{Alpha}\pN]+\b[,.;]?\s*/gc;
print(" line-noise"), redo LOOP if /\G\W+/gc;
print ". That's all!\n";
}
```
Here is the output (split into several lines):
```
line-noise lowercase line-noise UPPERCASE line-noise UPPERCASE
line-noise lowercase line-noise lowercase line-noise lowercase
lowercase line-noise lowercase lowercase line-noise lowercase
lowercase line-noise MiXeD line-noise. That's all!
```
`m?*PATTERN*?msixpodualngc` This is just like the `m/*PATTERN*/` search, except that it matches only once between calls to the `reset()` operator. This is a useful optimization when you want to see only the first occurrence of something in each file of a set of files, for instance. Only `m??` patterns local to the current package are reset.
```
while (<>) {
if (m?^$?) {
# blank line between header and body
}
} continue {
reset if eof; # clear m?? status for next file
}
```
Another example switched the first "latin1" encoding it finds to "utf8" in a pod file:
```
s//utf8/ if m? ^ =encoding \h+ \K latin1 ?x;
```
The match-once behavior is controlled by the match delimiter being `?`; with any other delimiter this is the normal `m//` operator.
In the past, the leading `m` in `m?*PATTERN*?` was optional, but omitting it would produce a deprecation warning. As of v5.22.0, omitting it produces a syntax error. If you encounter this construct in older code, you can just add `m`.
`s/*PATTERN*/*REPLACEMENT*/msixpodualngcer` Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (a value that is both an empty string (`""`) and numeric zero (`0`) as described in ["Relational Operators"](#Relational-Operators)).
If the `/r` (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when `/r` is used. The copy will always be a plain string, even if the input is an object or a tied variable.
If no string is specified via the `=~` or `!~` operator, the `$_` variable is searched and modified. Unless the `/r` option is used, the string specified must be a scalar variable, an array element, a hash element, or an assignment to one of those; that is, some sort of scalar lvalue.
If the delimiter chosen is a single quote, no variable interpolation is done on either the *PATTERN* or the *REPLACEMENT*. Otherwise, if the *PATTERN* contains a `$` that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at run-time. If you want the pattern compiled only once the first time the variable is interpolated, use the `/o` option. If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead. See <perlre> for further explanation on these.
Options are as with `m//` with the addition of the following replacement specific options:
```
e Evaluate the right side as an expression.
ee Evaluate the right side as a string then eval the
result.
r Return substitution and leave the original string
untouched.
```
Any non-whitespace delimiter may replace the slashes. Add space after the `s` when using a character allowed in identifiers. If single quotes are used, no interpretation is done on the replacement string (the `/e` modifier overrides this, however). Note that Perl treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the *PATTERN* is delimited by bracketing quotes, the *REPLACEMENT* has its own pair of quotes, which may or may not be bracketing quotes, for example, `s(foo)(bar)` or `s<foo>/bar/`. A `/e` will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second `e` modifier will cause the replacement portion to be `eval`ed before being run as a Perl expression.
Examples:
```
s/\bgreen\b/mauve/g; # don't change wintergreen
$path =~ s|/usr/bin|/usr/local/bin|;
s/Login: $foo/Login: $bar/; # run-time pattern
($foo = $bar) =~ s/this/that/; # copy first, then
# change
($foo = "$bar") =~ s/this/that/; # convert to string,
# copy, then change
$foo = $bar =~ s/this/that/r; # Same as above using /r
$foo = $bar =~ s/this/that/r
=~ s/that/the other/r; # Chained substitutes
# using /r
@foo = map { s/this/that/r } @bar # /r is very useful in
# maps
$count = ($paragraph =~ s/Mister\b/Mr./g); # get change-cnt
$_ = 'abc123xyz';
s/\d+/$&*2/e; # yields 'abc246xyz'
s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
s/%(.)/$percent{$1}/g; # change percent escapes; no /e
s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
s/^=(\w+)/pod($1)/ge; # use function call
$_ = 'abc123xyz';
$x = s/abc/def/r; # $x is 'def123xyz' and
# $_ remains 'abc123xyz'.
# expand variables in $_, but dynamics only, using
# symbolic dereferencing
s/\$(\w+)/${$1}/g;
# Add one to the value of any numbers in the string
s/(\d+)/1 + $1/eg;
# Titlecase words in the last 30 characters only (presuming
# that the substring doesn't start in the middle of a word)
substr($str, -30) =~ s/\b(\p{Alpha})(\p{Alpha}*)\b/\u$1\L$2/g;
# This will expand any embedded scalar variable
# (including lexicals) in $_ : First $1 is interpolated
# to the variable name, and then evaluated
s/(\$\w+)/$1/eeg;
# Delete (most) C comments.
$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;
s/^\s*(.*?)\s*$/$1/; # trim whitespace in $_,
# expensively
for ($variable) { # trim whitespace in $variable,
# cheap
s/^\s+//;
s/\s+$//;
}
s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
$foo !~ s/A/a/g; # Lowercase all A's in $foo; return
# 0 if any were found and changed;
# otherwise return 1
```
Note the use of `$` instead of `\` in the last example. Unlike **sed**, we use the \<*digit*> form only in the left hand side. Anywhere else it's $<*digit*>.
Occasionally, you can't use just a `/g` to get all the changes to occur that you might want. Here are two common cases:
```
# put commas in the right places in an integer
1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
# expand tabs to 8-column spacing
1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
```
While `s///` accepts the `/c` flag, it has no effect beyond producing a warning if warnings are enabled.
###
Quote-Like Operators
`q/*STRING*/`
`'*STRING*'`
A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.
```
$foo = q!I said, "You said, 'She said it.'"!;
$bar = q('This is it.');
$baz = '\n'; # a two-character string
```
`qq/*STRING*/`
`"*STRING*"`
A double-quoted, interpolated string.
```
$_ .= qq
(*** The previous line contains the naughty word "$1".\n)
if /\b(tcl|java|python)\b/i; # :-)
$baz = "\n"; # a one-character string
```
`qx/*STRING*/`
``*STRING*``
A string which is (possibly) interpolated and then executed as a system command, via */bin/sh* or its equivalent if required. Shell wildcards, pipes, and redirections will be honored. Similarly to `system`, if the string contains no shell metacharacters then it will executed directly. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string, or `undef` if the shell (or command) could not be started. In list context, returns a list of lines (however you've defined lines with `$/` or `$INPUT_RECORD_SEPARATOR`), or an empty list if the shell (or command) could not be started.
Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together:
```
$output = `cmd 2>&1`;
```
To capture a command's STDOUT but discard its STDERR:
```
$output = `cmd 2>/dev/null`;
```
To capture a command's STDERR but discard its STDOUT (ordering is important here):
```
$output = `cmd 2>&1 1>/dev/null`;
```
To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:
```
$output = `cmd 3>&1 1>&2 2>&3 3>&-`;
```
To read both a command's STDOUT and its STDERR separately, it's easiest to redirect them separately to files, and then read from those files when the program is done:
```
system("program args 1>program.stdout 2>program.stderr");
```
The STDIN filehandle used by the command is inherited from Perl's STDIN. For example:
```
open(SPLAT, "stuff") || die "can't open stuff: $!";
open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!";
print STDOUT `sort`;
```
will print the sorted contents of the file named *"stuff"*.
Using single-quote as a delimiter protects the command from Perl's double-quote interpolation, passing it on to the shell instead:
```
$perl_info = qx(ps $$); # that's Perl's $$
$shell_info = qx'ps $$'; # that's the new shell's $$
```
How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you will have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters. See <perlsec> for a clean and safe example of a manual `fork()` and `exec()` to emulate backticks safely.
On some platforms (notably DOS-like ones), the shell may not be capable of dealing with multiline commands, so putting newlines in the string may not get you what you want. You may be able to evaluate multiple commands in a single line by separating them with the command separator character, if your shell supports that (for example, `;` on many Unix shells and `&` on the Windows NT `cmd` shell).
Perl will attempt to flush all files opened for output before starting the child process, but this may not be supported on some platforms (see <perlport>). To be safe, you may need to set `$|` (`$AUTOFLUSH` in `[English](english)`) or call the `autoflush()` method of `<IO::Handle>` on any open handles.
Beware that some command shells may place restrictions on the length of the command line. You must ensure your strings don't exceed this limit after any necessary interpolations. See the platform-specific release notes for more details about your particular environment.
Using this operator can lead to programs that are difficult to port, because the shell commands called vary between systems, and may in fact not be present at all. As one example, the `type` command under the POSIX shell is very different from the `type` command under DOS. That doesn't mean you should go out of your way to avoid backticks when they're the right way to get something done. Perl was made to be a glue language, and one of the things it glues together is commands. Just understand what you're getting yourself into.
Like `system`, backticks put the child process exit code in `$?`. If you'd like to manually inspect 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;
}
```
Use the <open> pragma to control the I/O layers used when reading the output of the command, for example:
```
use open IN => ":encoding(UTF-8)";
my $x = `cmd-producing-utf-8`;
```
`qx//` can also be called like a function with ["readpipe" in perlfunc](perlfunc#readpipe).
See ["I/O Operators"](#I%2FO-Operators) for more discussion.
`qw/*STRING*/` Evaluates to a list of the words extracted out of *STRING*, using embedded whitespace as the word delimiters. It can be understood as being roughly equivalent to:
```
split(" ", q/STRING/);
```
the differences being that it only splits on ASCII whitespace, generates a real list at compile time, and in scalar context it returns the last element in the list. So this expression:
```
qw(foo bar baz)
```
is semantically equivalent to the list:
```
"foo", "bar", "baz"
```
Some frequently seen examples:
```
use POSIX qw( setlocale localeconv )
@EXPORT = qw( foo bar baz );
```
A common mistake is to try to separate the words with commas or to put comments into a multi-line `qw`-string. For this reason, the `use warnings` pragma and the **-w** switch (that is, the `$^W` variable) produces warnings if the *STRING* contains the `","` or the `"#"` character.
`tr/*SEARCHLIST*/*REPLACEMENTLIST*/cdsr`
`y/*SEARCHLIST*/*REPLACEMENTLIST*/cdsr`
Transliterates all occurrences of the characters found (or not found if the `/c` modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified. It returns the number of characters replaced or deleted. If no string is specified via the `=~` or `!~` operator, the `$_` string is transliterated.
For **sed** devotees, `y` is provided as a synonym for `tr`.
If the `/r` (non-destructive) option is present, a new copy of the string is made and its characters transliterated, and this copy is returned no matter whether it was modified or not: the original string is always left unchanged. The new copy is always a plain string, even if the input string is an object or a tied variable.
Unless the `/r` option is used, the string specified with `=~` must be a scalar variable, an array element, a hash element, or an assignment to one of those; in other words, an lvalue.
The characters delimitting *SEARCHLIST* and *REPLACEMENTLIST* can be any printable character, not just forward slashes. If they are single quotes (`tr'*SEARCHLIST*'*REPLACEMENTLIST*'`), the only interpolation is removal of `\` from pairs of `\\`; so hyphens are interpreted literally rather than specifying a character range.
Otherwise, a character range may be specified with a hyphen, so `tr/A-J/0-9/` does the same replacement as `tr/ACEGIBDFHJ/0246813579/`.
If the *SEARCHLIST* is delimited by bracketing quotes, the *REPLACEMENTLIST* must have its own pair of quotes, which may or may not be bracketing quotes; for example, `tr(aeiouy)(yuoiea)` or `tr[+\-*/]"ABCD"`. This final example shows a way to visually clarify what is going on for people who are more familiar with regular expression patterns than with `tr`, and who may think forward slash delimiters imply that `tr` is more like a regular expression pattern than it actually is. (Another option might be to use `tr[...][...]`.)
`tr` isn't fully like bracketed character classes, just (significantly) more like them than it is to full patterns. For example, characters appearing more than once in either list behave differently here than in patterns, and `tr` lists do not allow backslashed character classes such as `\d` or `\pL`, nor variable interpolation, so `"$"` and `"@"` are always treated as literals.
The allowed elements are literals plus `\'` (meaning a single quote). If the delimiters aren't single quotes, also allowed are any of the escape sequences accepted in double-quoted strings. Escape sequence details are in [the table near the beginning of this section](#Quote-and-Quote-like-Operators).
A hyphen at the beginning or end, or preceded by a backslash is also always considered a literal. Precede a delimiter character with a backslash to allow it.
The `tr` operator is not equivalent to the `[tr(1)](http://man.he.net/man1/tr)` utility. `tr[a-z][A-Z]` will uppercase the 26 letters "a" through "z", but for case changing not confined to ASCII, use [`lc`](perlfunc#lc), [`uc`](perlfunc#uc), [`lcfirst`](perlfunc#lcfirst), [`ucfirst`](perlfunc#ucfirst) (all documented in <perlfunc>), or the [substitution operator `s/*PATTERN*/*REPLACEMENT*/`](#s%2FPATTERN%2FREPLACEMENT%2Fmsixpodualngcer) (with `\U`, `\u`, `\L`, and `\l` string-interpolation escapes in the *REPLACEMENT* portion).
Most ranges are unportable between character sets, but certain ones signal Perl to do special handling to make them portable. There are two classes of portable ranges. The first are any subsets of the ranges `A-Z`, `a-z`, and `0-9`, when expressed as literal characters.
```
tr/h-k/H-K/
```
capitalizes the letters `"h"`, `"i"`, `"j"`, and `"k"` and nothing else, no matter what the platform's character set is. In contrast, all of
```
tr/\x68-\x6B/\x48-\x4B/
tr/h-\x6B/H-\x4B/
tr/\x68-k/\x48-K/
```
do the same capitalizations as the previous example when run on ASCII platforms, but something completely different on EBCDIC ones.
The second class of portable ranges is invoked when one or both of the range's end points are expressed as `\N{...}`
```
$string =~ tr/\N{U+20}-\N{U+7E}//d;
```
removes from `$string` all the platform's characters which are equivalent to any of Unicode U+0020, U+0021, ... U+007D, U+007E. This is a portable range, and has the same effect on every platform it is run on. In this example, these are the ASCII printable characters. So after this is run, `$string` has only controls and characters which have no ASCII equivalents.
But, even for portable ranges, it is not generally obvious what is included without having to look things up in the manual. A sound principle is to use only ranges that both begin from, and end at, either ASCII alphabetics of equal case (`b-e`, `B-E`), or digits (`1-4`). Anything else is unclear (and unportable unless `\N{...}` is used). If in doubt, spell out the character sets in full.
Options:
```
c Complement the SEARCHLIST.
d Delete found but unreplaced characters.
r Return the modified string and leave the original string
untouched.
s Squash duplicate replaced characters.
```
If the `/d` modifier is specified, any characters specified by *SEARCHLIST* not found in *REPLACEMENTLIST* are deleted. (Note that this is slightly more flexible than the behavior of some **tr** programs, which delete anything they find in the *SEARCHLIST*, period.)
If the `/s` modifier is specified, sequences of characters, all in a row, that were transliterated to the same character are squashed down to a single instance of that character.
```
my $a = "aaabbbca";
$a =~ tr/ab/dd/s; # $a now is "dcd"
```
If the `/d` modifier is used, the *REPLACEMENTLIST* is always interpreted exactly as specified. Otherwise, if the *REPLACEMENTLIST* is shorter than the *SEARCHLIST*, the final character, if any, is replicated until it is long enough. There won't be a final character if and only if the *REPLACEMENTLIST* is empty, in which case *REPLACEMENTLIST* is copied from *SEARCHLIST*. An empty *REPLACEMENTLIST* is useful for counting characters in a class, or for squashing character sequences in a class.
```
tr/abcd// tr/abcd/abcd/
tr/abcd/AB/ tr/abcd/ABBB/
tr/abcd//d s/[abcd]//g
tr/abcd/AB/d (tr/ab/AB/ + s/[cd]//g) - but run together
```
If the `/c` modifier is specified, the characters to be transliterated are the ones NOT in *SEARCHLIST*, that is, it is complemented. If `/d` and/or `/s` are also specified, they apply to the complemented *SEARCHLIST*. Recall, that if *REPLACEMENTLIST* is empty (except under `/d`) a copy of *SEARCHLIST* is used instead. That copy is made after complementing under `/c`. *SEARCHLIST* is sorted by code point order after complementing, and any *REPLACEMENTLIST* is applied to that sorted result. This means that under `/c`, the order of the characters specified in *SEARCHLIST* is irrelevant. This can lead to different results on EBCDIC systems if *REPLACEMENTLIST* contains more than one character, hence it is generally non-portable to use `/c` with such a *REPLACEMENTLIST*.
Another way of describing the operation is this: If `/c` is specified, the *SEARCHLIST* is sorted by code point order, then complemented. If *REPLACEMENTLIST* is empty and `/d` is not specified, *REPLACEMENTLIST* is replaced by a copy of *SEARCHLIST* (as modified under `/c`), and these potentially modified lists are used as the basis for what follows. Any character in the target string that isn't in *SEARCHLIST* is passed through unchanged. Every other character in the target string is replaced by the character in *REPLACEMENTLIST* that positionally corresponds to its mate in *SEARCHLIST*, except that under `/s`, the 2nd and following characters are squeezed out in a sequence of characters in a row that all translate to the same character. If *SEARCHLIST* is longer than *REPLACEMENTLIST*, characters in the target string that match a character in *SEARCHLIST* that doesn't have a correspondence in *REPLACEMENTLIST* are either deleted from the target string if `/d` is specified; or replaced by the final character in *REPLACEMENTLIST* if `/d` isn't specified.
Some examples:
```
$ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case ASCII
$cnt = tr/*/*/; # count the stars in $_
$cnt = tr/*//; # same thing
$cnt = $sky =~ tr/*/*/; # count the stars in $sky
$cnt = $sky =~ tr/*//; # same thing
$cnt = $sky =~ tr/*//c; # count all the non-stars in $sky
$cnt = $sky =~ tr/*/*/c; # same, but transliterate each non-star
# into a star, leaving the already-stars
# alone. Afterwards, everything in $sky
# is a star.
$cnt = tr/0-9//; # count the ASCII digits in $_
tr/a-zA-Z//s; # bookkeeper -> bokeper
tr/o/o/s; # bookkeeper -> bokkeeper
tr/oe/oe/s; # bookkeeper -> bokkeper
tr/oe//s; # bookkeeper -> bokkeper
tr/oe/o/s; # bookkeeper -> bokkopor
($HOST = $host) =~ tr/a-z/A-Z/;
$HOST = $host =~ tr/a-z/A-Z/r; # same thing
$HOST = $host =~ tr/a-z/A-Z/r # chained with s///r
=~ s/:/ -p/r;
tr/a-zA-Z/ /cs; # change non-alphas to single space
@stripped = map tr/a-zA-Z/ /csr, @original;
# /r with map
tr [\200-\377]
[\000-\177]; # wickedly delete 8th bit
$foo !~ tr/A/a/ # transliterate all the A's in $foo to 'a',
# return 0 if any were found and changed.
# Otherwise return 1
```
If multiple transliterations are given for a character, only the first one is used:
```
tr/AAA/XYZ/
```
will transliterate any A to X.
Because the transliteration table is built at compile time, neither the *SEARCHLIST* nor the *REPLACEMENTLIST* are subjected to double quote interpolation. That means that if you want to use variables, you must use an `eval()`:
```
eval "tr/$oldlist/$newlist/";
die $@ if $@;
eval "tr/$oldlist/$newlist/, 1" or die $@;
```
`<<*EOF*` A line-oriented form of quoting is based on the shell "here-document" syntax. Following a `<<` you specify a string to terminate the quoted material, and all lines following the current line down to the terminating string are the value of the item.
Prefixing the terminating string with a `~` specifies that you want to use ["Indented Here-docs"](#Indented-Here-docs) (see below).
The terminating string may be either an identifier (a word), or some quoted text. An unquoted identifier works like double quotes. There may not be a space between the `<<` and the identifier, unless the identifier is explicitly quoted. The terminating string must appear by itself (unquoted and with no surrounding whitespace) on the terminating line.
If the terminating string is quoted, the type of quotes used determine the treatment of the text.
Double Quotes Double quotes indicate that the text will be interpolated using exactly the same rules as normal double quoted strings.
```
print <<EOF;
The price is $Price.
EOF
print << "EOF"; # same as above
The price is $Price.
EOF
```
Single Quotes Single quotes indicate the text is to be treated literally with no interpolation of its content. This is similar to single quoted strings except that backslashes have no special meaning, with `\\` being treated as two backslashes and not one as they would in every other quoting construct.
Just as in the shell, a backslashed bareword following the `<<` means the same thing as a single-quoted string does:
```
$cost = <<'VISTA'; # hasta la ...
That'll be $10 please, ma'am.
VISTA
$cost = <<\VISTA; # Same thing!
That'll be $10 please, ma'am.
VISTA
```
This is the only form of quoting in perl where there is no need to worry about escaping content, something that code generators can and do make good use of.
Backticks The content of the here doc is treated just as it would be if the string were embedded in backticks. Thus the content is interpolated as though it were double quoted and then executed via the shell, with the results of the execution returned.
```
print << `EOC`; # execute command and get results
echo hi there
EOC
```
Indented Here-docs The here-doc modifier `~` allows you to indent your here-docs to make the code more readable:
```
if ($some_var) {
print <<~EOF;
This is a here-doc
EOF
}
```
This will print...
```
This is a here-doc
```
...with no leading whitespace.
The line containing the delimiter that marks the end of the here-doc determines the indentation template for the whole thing. Compilation croaks if any non-empty line inside the here-doc does not begin with the precise indentation of the terminating line. (An empty line consists of the single character "\n".) For example, suppose the terminating line begins with a tab character followed by 4 space characters. Every non-empty line in the here-doc must begin with a tab followed by 4 spaces. They are stripped from each line, and any leading white space remaining on a line serves as the indentation for that line. Currently, only the TAB and SPACE characters are treated as whitespace for this purpose. Tabs and spaces may be mixed, but are matched exactly; tabs remain tabs and are not expanded.
Additional beginning whitespace (beyond what preceded the delimiter) will be preserved:
```
print <<~EOF;
This text is not indented
This text is indented with two spaces
This text is indented with two tabs
EOF
```
Finally, the modifier may be used with all of the forms mentioned above:
```
<<~\EOF;
<<~'EOF'
<<~"EOF"
<<~`EOF`
```
And whitespace may be used between the `~` and quoted delimiters:
```
<<~ 'EOF'; # ... "EOF", `EOF`
```
It is possible to stack multiple here-docs in a row:
```
print <<"foo", <<"bar"; # you can stack them
I said foo.
foo
I said bar.
bar
myfunc(<< "THIS", 23, <<'THAT');
Here's a line
or two.
THIS
and here's another.
THAT
```
Just don't forget that you have to put a semicolon on the end to finish the statement, as Perl doesn't know you're not going to try to do this:
```
print <<ABC
179231
ABC
+ 20;
```
If you want to remove the line terminator from your here-docs, use `chomp()`.
```
chomp($string = <<'END');
This is a string.
END
```
If you want your here-docs to be indented with the rest of the code, use the `<<~FOO` construct described under ["Indented Here-docs"](#Indented-Here-docs):
```
$quote = <<~'FINIS';
The Road goes ever on and on,
down from the door where it began.
FINIS
```
If you use a here-doc within a delimited construct, such as in `s///eg`, the quoted material must still come on the line following the `<<FOO` marker, which means it may be inside the delimited construct:
```
s/this/<<E . 'that'
the other
E
. 'more '/eg;
```
It works this way as of Perl 5.18. Historically, it was inconsistent, and you would have to write
```
s/this/<<E . 'that'
. 'more '/eg;
the other
E
```
outside of string evals.
Additionally, quoting rules for the end-of-string identifier are unrelated to Perl's quoting rules. `q()`, `qq()`, and the like are not supported in place of `''` and `""`, and the only interpolation is for backslashing the quoting character:
```
print << "abc\"def";
testing...
abc"def
```
Finally, quoted strings cannot span multiple lines. The general rule is that the identifier must be a string literal. Stick with that, and you should be safe.
###
Gory details of parsing quoted constructs
When presented with something that might have several different interpretations, Perl uses the **DWIM** (that's "Do What I Mean") principle to pick the most probable interpretation. This strategy is so successful that Perl programmers often do not suspect the ambivalence of what they write. But from time to time, Perl's notions differ substantially from what the author honestly meant.
This section hopes to clarify how Perl handles quoted constructs. Although the most common reason to learn this is to unravel labyrinthine regular expressions, because the initial steps of parsing are the same for all quoting operators, they are all discussed together.
The most important Perl parsing rule is the first one discussed below: when processing a quoted construct, Perl first finds the end of that construct, then interprets its contents. If you understand this rule, you may skip the rest of this section on the first reading. The other rules are likely to contradict the user's expectations much less frequently than this first one.
Some passes discussed below are performed concurrently, but because their results are the same, we consider them individually. For different quoting constructs, Perl performs different numbers of passes, from one to four, but these passes are always performed in the same order.
Finding the end The first pass is finding the end of the quoted construct. This results in saving to a safe location a copy of the text (between the starting and ending delimiters), normalized as necessary to avoid needing to know what the original delimiters were.
If the construct is a here-doc, the ending delimiter is a line that has a terminating string as the content. Therefore `<<EOF` is terminated by `EOF` immediately followed by `"\n"` and starting from the first column of the terminating line. When searching for the terminating line of a here-doc, nothing is skipped. In other words, lines after the here-doc syntax are compared with the terminating string line by line.
For the constructs except here-docs, single characters are used as starting and ending delimiters. If the starting delimiter is an opening punctuation (that is `(`, `[`, `{`, or `<`), the ending delimiter is the corresponding closing punctuation (that is `)`, `]`, `}`, or `>`). If the starting delimiter is an unpaired character like `/` or a closing punctuation, the ending delimiter is the same as the starting delimiter. Therefore a `/` terminates a `qq//` construct, while a `]` terminates both `qq[]` and `qq]]` constructs.
When searching for single-character delimiters, escaped delimiters and `\\` are skipped. For example, while searching for terminating `/`, combinations of `\\` and `\/` are skipped. If the delimiters are bracketing, nested pairs are also skipped. For example, while searching for a closing `]` paired with the opening `[`, combinations of `\\`, `\]`, and `\[` are all skipped, and nested `[` and `]` are skipped as well. However, when backslashes are used as the delimiters (like `qq\\` and `tr\\\`), nothing is skipped. During the search for the end, backslashes that escape delimiters or other backslashes are removed (exactly speaking, they are not copied to the safe location).
For constructs with three-part delimiters (`s///`, `y///`, and `tr///`), the search is repeated once more. If the first delimiter is not an opening punctuation, the three delimiters must be the same, such as `s!!!` and `tr)))`, in which case the second delimiter terminates the left part and starts the right part at once. If the left part is delimited by bracketing punctuation (that is `()`, `[]`, `{}`, or `<>`), the right part needs another pair of delimiters such as `s(){}` and `tr[]//`. In these cases, whitespace and comments are allowed between the two parts, although the comment must follow at least one whitespace character; otherwise a character expected as the start of the comment may be regarded as the starting delimiter of the right part.
During this search no attention is paid to the semantics of the construct. Thus:
```
"$hash{"$foo/$bar"}"
```
or:
```
m/
bar # NOT a comment, this slash / terminated m//!
/x
```
do not form legal quoted expressions. The quoted part ends on the first `"` and `/`, and the rest happens to be a syntax error. Because the slash that terminated `m//` was followed by a `SPACE`, the example above is not `m//x`, but rather `m//` with no `/x` modifier. So the embedded `#` is interpreted as a literal `#`.
Also no attention is paid to `\c\` (multichar control char syntax) during this search. Thus the second `\` in `qq/\c\/` is interpreted as a part of `\/`, and the following `/` is not recognized as a delimiter. Instead, use `\034` or `\x1c` at the end of quoted constructs.
Interpolation The next step is interpolation in the text obtained, which is now delimiter-independent. There are multiple cases.
`<<'EOF'`
No interpolation is performed. Note that the combination `\\` is left intact, since escaped delimiters are not available for here-docs.
`m''`, the pattern of `s'''`
No interpolation is performed at this stage. Any backslashed sequences including `\\` are treated at the stage of ["Parsing regular expressions"](#Parsing-regular-expressions).
`''`, `q//`, `tr'''`, `y'''`, the replacement of `s'''`
The only interpolation is removal of `\` from pairs of `\\`. Therefore `"-"` in `tr'''` and `y'''` is treated literally as a hyphen and no character range is available. `\1` in the replacement of `s'''` does not work as `$1`.
`tr///`, `y///`
No variable interpolation occurs. String modifying combinations for case and quoting such as `\Q`, `\U`, and `\E` are not recognized. The other escape sequences such as `\200` and `\t` and backslashed characters such as `\\` and `\-` are converted to appropriate literals. The character `"-"` is treated specially and therefore `\-` is treated as a literal `"-"`.
`""`, ````, `qq//`, `qx//`, `<file*glob>`, `<<"EOF"`
`\Q`, `\U`, `\u`, `\L`, `\l`, `\F` (possibly paired with `\E`) are converted to corresponding Perl constructs. Thus, `"$foo\Qbaz$bar"` is converted to `$foo . (quotemeta("baz" . $bar))` internally. The other escape sequences such as `\200` and `\t` and backslashed characters such as `\\` and `\-` are replaced with appropriate expansions.
Let it be stressed that *whatever falls between `\Q` and `\E`* is interpolated in the usual way. Something like `"\Q\\E"` has no `\E` inside. Instead, it has `\Q`, `\\`, and `E`, so the result is the same as for `"\\\\E"`. As a general rule, backslashes between `\Q` and `\E` may lead to counterintuitive results. So, `"\Q\t\E"` is converted to `quotemeta("\t")`, which is the same as `"\\\t"` (since TAB is not alphanumeric). Note also that:
```
$str = '\t';
return "\Q$str";
```
may be closer to the conjectural *intention* of the writer of `"\Q\t\E"`.
Interpolated scalars and arrays are converted internally to the `join` and `"."` catenation operations. Thus, `"$foo XXX '@arr'"` becomes:
```
$foo . " XXX '" . (join $", @arr) . "'";
```
All operations above are performed simultaneously, left to right.
Because the result of `"\Q *STRING* \E"` has all metacharacters quoted, there is no way to insert a literal `$` or `@` inside a `\Q\E` pair. If protected by `\`, `$` will be quoted to become `"\\\$"`; if not, it is interpreted as the start of an interpolated scalar.
Note also that the interpolation code needs to make a decision on where the interpolated scalar ends. For instance, whether `"a $x -> {c}"` really means:
```
"a " . $x . " -> {c}";
```
or:
```
"a " . $x -> {c};
```
Most of the time, the longest possible text that does not include spaces between components and which contains matching braces or brackets. because the outcome may be determined by voting based on heuristic estimators, the result is not strictly predictable. Fortunately, it's usually correct for ambiguous cases.
The replacement of `s///`
Processing of `\Q`, `\U`, `\u`, `\L`, `\l`, `\F` and interpolation happens as with `qq//` constructs.
It is at this step that `\1` is begrudgingly converted to `$1` in the replacement text of `s///`, in order to correct the incorrigible *sed* hackers who haven't picked up the saner idiom yet. A warning is emitted if the `use warnings` pragma or the **-w** command-line flag (that is, the `$^W` variable) was set.
`RE` in `m?RE?`, `/RE/`, `m/RE/`, `s/RE/foo/`, Processing of `\Q`, `\U`, `\u`, `\L`, `\l`, `\F`, `\E`, and interpolation happens (almost) as with `qq//` constructs.
Processing of `\N{...}` is also done here, and compiled into an intermediate form for the regex compiler. (This is because, as mentioned below, the regex compilation may be done at execution time, and `\N{...}` is a compile-time construct.)
However any other combinations of `\` followed by a character are not substituted but only skipped, in order to parse them as regular expressions at the following step. As `\c` is skipped at this step, `@` of `\c@` in RE is possibly treated as an array symbol (for example `@foo`), even though the same text in `qq//` gives interpolation of `\c@`.
Code blocks such as `(?{BLOCK})` are handled by temporarily passing control back to the perl parser, in a similar way that an interpolated array subscript expression such as `"foo$array[1+f("[xyz")]bar"` would be.
Moreover, inside `(?{BLOCK})`, `(?# comment )`, and a `#`-comment in a `/x`-regular expression, no processing is performed whatsoever. This is the first step at which the presence of the `/x` modifier is relevant.
Interpolation in patterns has several quirks: `$|`, `$(`, `$)`, `@+` and `@-` are not interpolated, and constructs `$var[SOMETHING]` are voted (by several different estimators) to be either an array element or `$var` followed by an RE alternative. This is where the notation `${arr[$bar]}` comes handy: `/${arr[0-9]}/` is interpreted as array element `-9`, not as a regular expression from the variable `$arr` followed by a digit, which would be the interpretation of `/$arr[0-9]/`. Since voting among different estimators may occur, the result is not predictable.
The lack of processing of `\\` creates specific restrictions on the post-processed text. If the delimiter is `/`, one cannot get the combination `\/` into the result of this step. `/` will finish the regular expression, `\/` will be stripped to `/` on the previous step, and `\\/` will be left as is. Because `/` is equivalent to `\/` inside a regular expression, this does not matter unless the delimiter happens to be character special to the RE engine, such as in `s*foo*bar*`, `m[foo]`, or `m?foo?`; or an alphanumeric char, as in:
```
m m ^ a \s* b mmx;
```
In the RE above, which is intentionally obfuscated for illustration, the delimiter is `m`, the modifier is `mx`, and after delimiter-removal the RE is the same as for `m/ ^ a \s* b /mx`. There's more than one reason you're encouraged to restrict your delimiters to non-alphanumeric, non-whitespace choices.
This step is the last one for all constructs except regular expressions, which are processed further.
Parsing regular expressions Previous steps were performed during the compilation of Perl code, but this one happens at run time, although it may be optimized to be calculated at compile time if appropriate. After preprocessing described above, and possibly after evaluation if concatenation, joining, casing translation, or metaquoting are involved, the resulting *string* is passed to the RE engine for compilation.
Whatever happens in the RE engine might be better discussed in <perlre>, but for the sake of continuity, we shall do so here.
This is another step where the presence of the `/x` modifier is relevant. The RE engine scans the string from left to right and converts it into a finite automaton.
Backslashed characters are either replaced with corresponding literal strings (as with `\{`), or else they generate special nodes in the finite automaton (as with `\b`). Characters special to the RE engine (such as `|`) generate corresponding nodes or groups of nodes. `(?#...)` comments are ignored. All the rest is either converted to literal strings to match, or else is ignored (as is whitespace and `#`-style comments if `/x` is present).
Parsing of the bracketed character class construct, `[...]`, is rather different than the rule used for the rest of the pattern. The terminator of this construct is found using the same rules as for finding the terminator of a `{}`-delimited construct, the only exception being that `]` immediately following `[` is treated as though preceded by a backslash.
The terminator of runtime `(?{...})` is found by temporarily switching control to the perl parser, which should stop at the point where the logically balancing terminating `}` is found.
It is possible to inspect both the string given to RE engine and the resulting finite automaton. See the arguments `debug`/`debugcolor` in the `use <re>` pragma, as well as Perl's **-Dr** command-line switch documented in ["Command Switches" in perlrun](perlrun#Command-Switches).
Optimization of regular expressions This step is listed for completeness only. Since it does not change semantics, details of this step are not documented and are subject to change without notice. This step is performed over the finite automaton that was generated during the previous pass.
It is at this stage that `split()` silently optimizes `/^/` to mean `/^/m`.
###
I/O Operators
There are several I/O operators you should know about.
A string enclosed by backticks (grave accents) first undergoes double-quote interpolation. It is then interpreted as an external command, and the output of that command is the value of the backtick string, like in a shell. In scalar context, a single string consisting of all output is returned. In list context, a list of values is returned, one per line of output. (You can set `$/` to use a different line terminator.) The command is executed each time the pseudo-literal is evaluated. The status value of the command is returned in `$?` (see <perlvar> for the interpretation of `$?`). Unlike in **csh**, no translation is done on the return data--newlines remain newlines. Unlike in any of the shells, single quotes do not hide variable names in the command from interpretation. To pass a literal dollar-sign through to the shell you need to hide it with a backslash. The generalized form of backticks is `qx//`, or you can call the ["readpipe" in perlfunc](perlfunc#readpipe) function. (Because backticks always undergo shell expansion as well, see <perlsec> for security concerns.)
In scalar context, evaluating a filehandle in angle brackets yields the next line from that file (the newline, if any, included), or `undef` at end-of-file or on error. When `$/` is set to `undef` (sometimes known as file-slurp mode) and the file is empty, it returns `''` the first time, followed by `undef` subsequently.
Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a `while` statement (even if disguised as a `for(;;)` loop), the value is automatically assigned to the global variable `$_`, destroying whatever was there previously. (This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write.) The `$_` variable is not implicitly localized. You'll have to put a `local $_;` before the loop if you want that to happen. Furthermore, if the input symbol or an explicit assignment of the input symbol 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.
Thus the following lines are equivalent:
```
while (defined($_ = <STDIN>)) { print; }
while ($_ = <STDIN>) { print; }
while (<STDIN>) { print; }
for (;<STDIN>;) { print; }
print while defined($_ = <STDIN>);
print while ($_ = <STDIN>);
print while <STDIN>;
```
This also behaves similarly, but assigns to a lexical variable instead of to `$_`:
```
while (my $line = <STDIN>) { print $line }
```
In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined. The defined test avoids problems where the line has a string value that would be treated as false by Perl; for example a "" or a `"0"` with no trailing newline. If you really mean for such values to terminate the loop, they should be tested for explicitly:
```
while (($_ = <STDIN>) ne '0') { ... }
while (<STDIN>) { last unless $_; ... }
```
In other boolean contexts, `<*FILEHANDLE*>` without an explicit `defined` test or comparison elicits a warning if the `use warnings` pragma or the **-w** command-line switch (the `$^W` variable) is in effect.
The filehandles STDIN, STDOUT, and STDERR are predefined. (The filehandles `stdin`, `stdout`, and `stderr` will also work except in packages, where they would be interpreted as local identifiers rather than global.) Additional filehandles may be created with the `open()` function, amongst others. See <perlopentut> and ["open" in perlfunc](perlfunc#open) for details on this.
If a `<*FILEHANDLE*>` is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element. It's easy to grow to a rather large data space this way, so use with care.
`<*FILEHANDLE*>` may also be spelled `readline(**FILEHANDLE*)`. See ["readline" in perlfunc](perlfunc#readline).
The null filehandle `<>` (sometimes called the diamond operator) is special: it can be used to emulate the behavior of **sed** and **awk**, and any other Unix filter program that takes a list of filenames, doing the same to each line of input from all of them. Input from `<>` comes either from standard input, or from each file listed on the command line. Here's how it works: the first time `<>` is evaluated, the `@ARGV` array is checked, and if it is empty, `$ARGV[0]` is set to `"-"`, which when opened gives you standard input. The `@ARGV` array is then processed as a list of filenames. The loop
```
while (<>) {
... # code for each line
}
```
is equivalent to the following Perl-like pseudo code:
```
unshift(@ARGV, '-') unless @ARGV;
while ($ARGV = shift) {
open(ARGV, $ARGV);
while (<ARGV>) {
... # code for each line
}
}
```
except that it isn't so cumbersome to say, and will actually work. It really does shift the `@ARGV` array and put the current filename into the `$ARGV` variable. It also uses filehandle *ARGV* internally. `<>` is just a synonym for `<ARGV>`, which is magical. (The pseudo code above doesn't work because it treats `<ARGV>` as non-magical.)
Since the null filehandle uses the two argument form of ["open" in perlfunc](perlfunc#open) it interprets special characters, so if you have a script like this:
```
while (<>) {
print;
}
```
and call it with `perl dangerous.pl 'rm -rfv *|'`, it actually opens a pipe, executes the `rm` command and reads `rm`'s output from that pipe. If you want all items in `@ARGV` to be interpreted as file names, you can use the module `ARGV::readonly` from CPAN, or use the double diamond bracket:
```
while (<<>>) {
print;
}
```
Using double angle brackets inside of a while causes the open to use the three argument form (with the second argument being `<`), so all arguments in `ARGV` are treated as literal filenames (including `"-"`). (Note that for convenience, if you use `<<>>` and if `@ARGV` is empty, it will still read from the standard input.)
You can modify `@ARGV` before the first `<>` as long as the array ends up containing the list of filenames you really want. Line numbers (`$.`) continue as though the input were one big happy file. See the example in ["eof" in perlfunc](perlfunc#eof) for how to reset line numbers on each file.
If you want to set `@ARGV` to your own list of files, go right ahead. This sets `@ARGV` to all plain text files if no `@ARGV` was given:
```
@ARGV = grep { -f && -T } glob('*') unless @ARGV;
```
You can even set them to pipe commands. For example, this automatically filters compressed arguments through **gzip**:
```
@ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
```
If you want to pass switches into your script, you can use one of the `Getopts` modules or put a loop on the front like this:
```
while ($_ = $ARGV[0], /^-/) {
shift;
last if /^--$/;
if (/^-D(.*)/) { $debug = $1 }
if (/^-v/) { $verbose++ }
# ... # other switches
}
while (<>) {
# ... # code for each line
}
```
The `<>` symbol will return `undef` for end-of-file only once. If you call it again after this, it will assume you are processing another `@ARGV` list, and if you haven't set `@ARGV`, will read input from STDIN.
If what the angle brackets contain is a simple scalar variable (for example, `$foo`), then that variable contains the name of the filehandle to input from, or its typeglob, or a reference to the same. For example:
```
$fh = \*STDIN;
$line = <$fh>;
```
If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means `<$x>` is always a `readline()` from an indirect handle, but `<$hash{key}>` is always a `glob()`. That's because `$x` is a simple scalar variable, but `$hash{key}` is not--it's a hash element. Even `<$x >` (note the extra space) is treated as `glob("$x ")`, not `readline($x)`.
One level of double-quote interpretation is done first, but you can't say `<$foo>` because that's an indirect filehandle as explained in the previous paragraph. (In older versions of Perl, programmers would insert curly brackets to force interpretation as a filename glob: `<${foo}>`. These days, it's considered cleaner to call the internal function directly as `glob($foo)`, which is probably the right way to have done it in the first place.) For example:
```
while (<*.c>) {
chmod 0644, $_;
}
```
is roughly equivalent to:
```
open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
while (<FOO>) {
chomp;
chmod 0644, $_;
}
```
except that the globbing is actually done internally using the standard `<File::Glob>` extension. Of course, the shortest way to do the above is:
```
chmod 0644, <*.c>;
```
A (file)glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In list context, this isn't important because you automatically get them all anyway. However, in scalar context the operator returns the next value each time it's called, or `undef` when the list has run out. As with filehandle reads, an automatic `defined` is generated when the glob occurs in the test part of a `while`, because legal glob returns (for example, a file called *0*) would otherwise terminate the loop. Again, `undef` is returned only once. So if you're expecting a single value from a glob, it is much better to say
```
($file) = <blurch*>;
```
than
```
$file = <blurch*>;
```
because the latter will alternate between returning a filename and returning false.
If you're trying to do variable interpolation, it's definitely better to use the `glob()` function, because the older notation can cause people to become confused with the indirect filehandle notation.
```
@files = glob("$dir/*.[ch]");
@files = glob($files[$i]);
```
If an angle-bracket-based globbing expression is used as the condition of a `while` or `for` loop, then it will be implicitly assigned to `$_`. If either a globbing expression or an explicit assignment of a globbing 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.
###
Constant Folding
Like C, Perl does a certain amount of expression evaluation at compile time whenever it determines that all arguments to an operator are static and have no side effects. In particular, string concatenation happens at compile time between literals that don't do variable substitution. Backslash interpolation also happens at compile time. You can say
```
'Now is the time for all'
. "\n"
. 'good men to come to.'
```
and this all reduces to one string internally. Likewise, if you say
```
foreach $file (@filenames) {
if (-s $file > 5 + 100 * 2**16) { }
}
```
the compiler precomputes the number which that expression represents so that the interpreter won't have to.
###
No-ops
Perl doesn't officially have a no-op operator, but the bare constants `0` and `1` are special-cased not to produce a warning in void context, so you can for example safely do
```
1 while foo();
```
###
Bitwise String Operators
Bitstrings of any size may be manipulated by the bitwise operators (`~ | & ^`).
If the operands to a binary bitwise op are strings of different sizes, **|** and **^** ops act as though the shorter operand had additional zero bits on the right, while the **&** op acts as though the longer operand were truncated to the length of the shorter. The granularity for such extension or truncation is one or more bytes.
```
# ASCII-based examples
print "j p \n" ^ " a h"; # prints "JAPH\n"
print "JA" | " ph\n"; # prints "japh\n"
print "japh\nJunk" & '_____'; # prints "JAPH\n";
print 'p N$' ^ " E<H\n"; # prints "Perl\n";
```
If you are intending to manipulate bitstrings, be certain that you're supplying bitstrings: If an operand is a number, that will imply a **numeric** bitwise operation. You may explicitly show which type of operation you intend by using `""` or `0+`, as in the examples below.
```
$foo = 150 | 105; # yields 255 (0x96 | 0x69 is 0xFF)
$foo = '150' | 105; # yields 255
$foo = 150 | '105'; # yields 255
$foo = '150' | '105'; # yields string '155' (under ASCII)
$baz = 0+$foo & 0+$bar; # both ops explicitly numeric
$biz = "$foo" ^ "$bar"; # both ops explicitly stringy
```
This somewhat unpredictable behavior can be avoided with the "bitwise" feature, new in Perl 5.22. You can enable it via `use feature 'bitwise'` or `use v5.28`. Before Perl 5.28, it used to emit a warning in the `"experimental::bitwise"` category. Under this feature, the four standard bitwise operators (`~ | & ^`) are always numeric. Adding a dot after each operator (`~. |. &. ^.`) forces it to treat its operands as strings:
```
use feature "bitwise";
$foo = 150 | 105; # yields 255 (0x96 | 0x69 is 0xFF)
$foo = '150' | 105; # yields 255
$foo = 150 | '105'; # yields 255
$foo = '150' | '105'; # yields 255
$foo = 150 |. 105; # yields string '155'
$foo = '150' |. 105; # yields string '155'
$foo = 150 |.'105'; # yields string '155'
$foo = '150' |.'105'; # yields string '155'
$baz = $foo & $bar; # both operands numeric
$biz = $foo ^. $bar; # both operands stringy
```
The assignment variants of these operators (`&= |= ^= &.= |.= ^.=`) behave likewise under the feature.
It is a fatal error if an operand contains a character whose ordinal value is above 0xFF, and hence not expressible except in UTF-8. The operation is performed on a non-UTF-8 copy for other operands encoded in UTF-8. See ["Byte and Character Semantics" in perlunicode](perlunicode#Byte-and-Character-Semantics).
See ["vec" in perlfunc](perlfunc#vec) for information on how to manipulate individual bits in a bit vector.
###
Integer Arithmetic
By default, Perl assumes that it must do most of its arithmetic in floating point. But by saying
```
use integer;
```
you may tell the compiler to use integer operations (see <integer> for a detailed explanation) from here to the end of the enclosing BLOCK. An inner BLOCK may countermand this by saying
```
no integer;
```
which lasts until the end of that BLOCK. Note that this doesn't mean everything is an integer, merely that Perl will use integer operations for arithmetic, comparison, and bitwise operators. For example, even under `use integer`, if you take the `sqrt(2)`, you'll still get `1.4142135623731` or so.
Used on numbers, the bitwise operators (`&` `|` `^` `~` `<<` `>>`) always produce integral results. (But see also ["Bitwise String Operators"](#Bitwise-String-Operators).) However, `use integer` still has meaning for them. By default, their results are interpreted as unsigned integers, but if `use integer` is in effect, their results are interpreted as signed integers. For example, `~0` usually evaluates to a large integral value. However, `use integer; ~0` is `-1` on two's-complement machines.
###
Floating-point Arithmetic
While `use integer` provides integer-only arithmetic, there is no analogous mechanism to provide automatic rounding or truncation to a certain number of decimal places. For rounding to a certain number of digits, `sprintf()` or `printf()` is usually the easiest route. See <perlfaq4>.
Floating-point numbers are only approximations to what a mathematician would call real numbers. There are infinitely more reals than floats, so some corners must be cut. For example:
```
printf "%.20g\n", 123456789123456789;
# produces 123456789123456784
```
Testing for exact floating-point equality or inequality is not a good idea. Here's a (relatively expensive) work-around to compare whether two floating-point numbers are equal to a particular number of decimal places. See Knuth, volume II, for a more robust treatment of this topic.
```
sub fp_equal {
my ($X, $Y, $POINTS) = @_;
my ($tX, $tY);
$tX = sprintf("%.${POINTS}g", $X);
$tY = sprintf("%.${POINTS}g", $Y);
return $tX eq $tY;
}
```
The POSIX module (part of the standard perl distribution) implements `ceil()`, `floor()`, and other mathematical and trigonometric functions. The `<Math::Complex>` module (part of the standard perl distribution) defines mathematical functions that work on both the reals and the imaginary numbers. `Math::Complex` is not as efficient as POSIX, but POSIX can't work with complex numbers.
Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.
###
Bigger Numbers
The standard `<Math::BigInt>`, `<Math::BigRat>`, and `<Math::BigFloat>` modules, along with the `bignum`, `bigint`, and `bigrat` pragmas, provide variable-precision arithmetic and overloaded operators, although they're currently pretty slow. At the cost of some space and considerable speed, they avoid the normal pitfalls associated with limited-precision representations.
```
use 5.010;
use bigint; # easy interface to Math::BigInt
$x = 123456789123456789;
say $x * $x;
+15241578780673678515622620750190521
```
Or with rationals:
```
use 5.010;
use bigrat;
$x = 3/22;
$y = 4/6;
say "x/y is ", $x/$y;
say "x*y is ", $x*$y;
x/y is 9/44
x*y is 1/11
```
Several modules let you calculate with unlimited or fixed precision (bound only by memory and CPU time). There are also some non-standard modules that provide faster implementations via external C libraries.
Here is a short, but incomplete summary:
```
Math::String treat string sequences like numbers
Math::FixedPrecision calculate with a fixed precision
Math::Currency for currency calculations
Bit::Vector manipulate bit vectors fast (uses C)
Math::BigIntFast Bit::Vector wrapper for big numbers
Math::Pari provides access to the Pari C library
Math::Cephes uses the external Cephes C library (no
big numbers)
Math::Cephes::Fraction fractions via the Cephes library
Math::GMP another one using an external C library
Math::GMPz an alternative interface to libgmp's big ints
Math::GMPq an interface to libgmp's fraction numbers
Math::GMPf an interface to libgmp's floating point numbers
```
Choose wisely.
| programming_docs |
perl lib lib
===
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Adding directories to @INC](#Adding-directories-to-@INC)
+ [Deleting directories from @INC](#Deleting-directories-from-@INC)
+ [Restoring original @INC](#Restoring-original-@INC)
* [CAVEATS](#CAVEATS)
* [NOTES](#NOTES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
lib - manipulate @INC at compile time
SYNOPSIS
--------
```
use lib LIST;
no lib LIST;
```
DESCRIPTION
-----------
This is a small simple module which simplifies the manipulation of @INC at compile time.
It is typically used to add extra directories to perl's search path so that later `use` or `require` statements will find modules which are not located on perl's default search path.
###
Adding directories to @INC
The parameters to `use lib` are added to the start of the perl search path. Saying
```
use lib LIST;
```
is *almost* the same as saying
```
BEGIN { unshift(@INC, LIST) }
```
For each directory in LIST (called $dir here) the lib module also checks to see if a directory called $dir/$archname/auto exists. If so the $dir/$archname directory is assumed to be a corresponding architecture specific directory and is added to @INC in front of $dir. lib.pm also checks if directories called $dir/$version and $dir/$version/$archname exist and adds these directories to @INC.
The current value of `$archname` can be found with this command:
```
perl -V:archname
```
The corresponding command to get the current value of `$version` is:
```
perl -V:version
```
To avoid memory leaks, all trailing duplicate entries in @INC are removed.
###
Deleting directories from @INC
You should normally only add directories to @INC. If you need to delete directories from @INC take care to only delete those which you added yourself or which you are certain are not needed by other modules in your script. Other modules may have added directories which they need for correct operation.
The `no lib` statement deletes all instances of each named directory from @INC.
For each directory in LIST (called $dir here) the lib module also checks to see if a directory called $dir/$archname/auto exists. If so the $dir/$archname directory is assumed to be a corresponding architecture specific directory and is also deleted from @INC. lib.pm also checks if directories called $dir/$version and $dir/$version/$archname exist and deletes these directories from @INC.
###
Restoring original @INC
When the lib module is first loaded it records the current value of @INC in an array `@lib::ORIG_INC`. To restore @INC to that value you can say
```
@INC = @lib::ORIG_INC;
```
CAVEATS
-------
In order to keep lib.pm small and simple, it only works with Unix filepaths. This doesn't mean it only works on Unix, but non-Unix users must first translate their file paths to Unix conventions.
```
# VMS users wanting to put [.stuff.moo] into
# their @INC would write
use lib 'stuff/moo';
```
NOTES
-----
In the future, this module will likely use File::Spec for determining paths, as it does now for Mac OS (where Unix-style or Mac-style paths work, and Unix-style paths are converted properly to Mac-style paths before being added to @INC).
If you try to add a file to @INC as follows:
```
use lib 'this_is_a_file.txt';
```
`lib` will warn about this. The sole exceptions are files with the `.par` extension which are intended to be used as libraries.
SEE ALSO
---------
FindBin - optional module which deals with paths relative to the source file.
PAR - optional module which can treat `.par` files as Perl libraries.
AUTHOR
------
Tim Bunce, 2nd June 1995.
`lib` is maintained by the perl5-porters. Please direct any questions to the canonical mailing list. Anything that is applicable to the CPAN release can be sent to its maintainer, though.
Maintainer: The Perl5-Porters <[email protected]>
Maintainer of the CPAN release: Steffen Mueller <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This package has been part of the perl core since perl 5.001. It has been released separately to CPAN so older installations can benefit from bug fixes.
This package has the same copyright and license as the perl core.
perl perlfaq7 perlfaq7
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [Can I get a BNF/yacc/RE for the Perl language?](#Can-I-get-a-BNF/yacc/RE-for-the-Perl-language?)
+ [What are all these $@%&\* punctuation signs, and how do I know when to use them?](#What-are-all-these-%24@%25&*-punctuation-signs,-and-how-do-I-know-when-to-use-them?)
+ [Do I always/never have to quote my strings or use semicolons and commas?](#Do-I-always/never-have-to-quote-my-strings-or-use-semicolons-and-commas?)
+ [How do I skip some return values?](#How-do-I-skip-some-return-values?)
+ [How do I temporarily block warnings?](#How-do-I-temporarily-block-warnings?)
+ [What's an extension?](#What's-an-extension?)
+ [Why do Perl operators have different precedence than C operators?](#Why-do-Perl-operators-have-different-precedence-than-C-operators?)
+ [How do I declare/create a structure?](#How-do-I-declare/create-a-structure?)
+ [How do I create a module?](#How-do-I-create-a-module?)
+ [How do I adopt or take over a module already on CPAN?](#How-do-I-adopt-or-take-over-a-module-already-on-CPAN?)
+ [How do I create a class?](#How-do-I-create-a-class?)
+ [How can I tell if a variable is tainted?](#How-can-I-tell-if-a-variable-is-tainted?)
+ [What's a closure?](#What's-a-closure?)
+ [What is variable suicide and how can I prevent it?](#What-is-variable-suicide-and-how-can-I-prevent-it?)
+ [How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?](#How-can-I-pass/return-a-%7BFunction,-FileHandle,-Array,-Hash,-Method,-Regex%7D?)
+ [How do I create a static variable?](#How-do-I-create-a-static-variable?)
+ [What's the difference between dynamic and lexical (static) scoping? Between local() and my()?](#What's-the-difference-between-dynamic-and-lexical-(static)-scoping?-Between-local()-and-my()?)
+ [How can I access a dynamic variable while a similarly named lexical is in scope?](#How-can-I-access-a-dynamic-variable-while-a-similarly-named-lexical-is-in-scope?)
+ [What's the difference between deep and shallow binding?](#What's-the-difference-between-deep-and-shallow-binding?)
+ [Why doesn't "my($foo) = <$fh>;" work right?](#Why-doesn't-%22my(%24foo)-=-%3C%24fh%3E;%22-work-right?)
+ [How do I redefine a builtin function, operator, or method?](#How-do-I-redefine-a-builtin-function,-operator,-or-method?)
+ [What's the difference between calling a function as &foo and foo()?](#What's-the-difference-between-calling-a-function-as-&foo-and-foo()?)
+ [How do I create a switch or case statement?](#How-do-I-create-a-switch-or-case-statement?)
+ [How can I catch accesses to undefined variables, functions, or methods?](#How-can-I-catch-accesses-to-undefined-variables,-functions,-or-methods?)
+ [Why can't a method included in this same file be found?](#Why-can't-a-method-included-in-this-same-file-be-found?)
+ [How can I find out my current or calling package?](#How-can-I-find-out-my-current-or-calling-package?)
+ [How can I comment out a large block of Perl code?](#How-can-I-comment-out-a-large-block-of-Perl-code?)
+ [How do I clear a package?](#How-do-I-clear-a-package?)
+ [How can I use a variable as a variable name?](#How-can-I-use-a-variable-as-a-variable-name?)
+ [What does "bad interpreter" mean?](#What-does-%22bad-interpreter%22-mean?)
+ [Do I need to recompile XS modules when there is a change in the C library?](#Do-I-need-to-recompile-XS-modules-when-there-is-a-change-in-the-C-library?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq7 - General Perl Language Issues
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
This section deals with general Perl language issues that don't clearly fit into any of the other sections.
###
Can I get a BNF/yacc/RE for the Perl language?
There is no BNF, but you can paw your way through the yacc grammar in perly.y in the source distribution if you're particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well.
In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF. The work of parsing perl is distributed between yacc, the lexer, smoke and mirrors."
###
What are all these $@%&\* punctuation signs, and how do I know when to use them?
They are type specifiers, as detailed in <perldata>:
```
$ for scalar values (number, string or reference)
@ for arrays
% for hashes (associative arrays)
& for subroutines (aka functions, procedures, methods)
* for all types of that symbol name. In version 4 you used them like
pointers, but in modern perls you can just use references.
```
There are a couple of other symbols that you're likely to encounter that aren't really type specifiers:
```
<> are used for inputting a record from a filehandle.
\ takes a reference to something.
```
Note that <FILE> is *neither* the type specifier for files nor the name of the handle. It is the `<>` operator applied to the handle FILE. It reads one line (well, record--see ["$/" in perlvar](perlvar#%24%2F)) from the handle FILE in scalar context, or *all* lines in list context. When performing open, close, or any other operation besides `<>` on files, or even when talking about the handle, do *not* use the brackets. These are correct: `eof(FH)`, `seek(FH, 0, 2)` and "copying from STDIN to FILE".
###
Do I always/never have to quote my strings or use semicolons and commas?
Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under `use strict`). But a hash key consisting of a simple word and the left-hand operand to the `=>` operator both count as though they were quoted:
```
This is like this
------------ ---------------
$foo{line} $foo{'line'}
bar => stuff 'bar' => stuff
```
The final semicolon in a block is optional, as is the final comma in a list. Good style (see <perlstyle>) says to put them in except for one-liners:
```
if ($whoops) { exit 1 }
my @nums = (1, 2, 3);
if ($whoops) {
exit 1;
}
my @lines = (
"There Beren came from mountains cold",
"And lost he wandered under leaves",
);
```
###
How do I skip some return values?
One way is to treat the return values as a list and index into it:
```
$dir = (getpwnam($user))[7];
```
Another way is to use undef as an element on the left-hand-side:
```
($dev, $ino, undef, undef, $uid, $gid) = stat($file);
```
You can also use a list slice to select only the elements that you need:
```
($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];
```
###
How do I temporarily block warnings?
If you are running Perl 5.6.0 or better, the `use warnings` pragma allows fine control of what warnings are produced. See <perllexwarn> for more details.
```
{
no warnings; # temporarily turn off warnings
$x = $y + $z; # I know these might be undef
}
```
Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still get other categories of warnings. See <perllexwarn> for the complete details, including the category names and hierarchy.
```
{
no warnings 'uninitialized';
$x = $y + $z;
}
```
If you have an older version of Perl, the `$^W` variable (documented in <perlvar>) controls runtime warnings for a block:
```
{
local $^W = 0; # temporarily turn off warnings
$x = $y + $z; # I know these might be undef
}
```
Note that like all the punctuation variables, you cannot currently use my() on `$^W`, only local().
###
What's an extension?
An extension is a way of calling compiled C code from Perl. Reading <perlxstut> is a good place to learn more about extensions.
###
Why do Perl operators have different precedence than C operators?
Actually, they don't. All C operators that Perl copies have the same precedence in Perl as they do in C. The problem is with operators that C doesn't have, especially functions that give a list context to everything on their right, eg. print, chmod, exec, and so on. Such functions are called "list operators" and appear as such in the precedence table in <perlop>.
A common mistake is to write:
```
unlink $file || die "snafu";
```
This gets interpreted as:
```
unlink ($file || die "snafu");
```
To avoid this problem, either put in extra parentheses or use the super low precedence `or` operator:
```
(unlink $file) || die "snafu";
unlink $file or die "snafu";
```
The "English" operators (`and`, `or`, `xor`, and `not`) deliberately have precedence lower than that of list operators for just such situations as the one above.
Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making `-2**2` produce a negative four and not a positive one. It is also right-associating, meaning that `2**3**2` is two raised to the ninth power, not eight squared.
Although it has the same precedence as in C, Perl's `?:` operator produces an lvalue. This assigns $x to either $if\_true or $if\_false, depending on the trueness of $maybe:
```
($maybe ? $if_true : $if_false) = $x;
```
###
How do I declare/create a structure?
In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See <perlref> and <perldsc> for details. Here's an example:
```
$person = {}; # new anonymous hash
$person->{AGE} = 24; # set field AGE to 24
$person->{NAME} = "Nat"; # set field NAME to "Nat"
```
If you're looking for something a bit more rigorous, try <perlootut>.
###
How do I create a module?
<perlnewmod> is a good place to start, ignore the bits about uploading to CPAN if you don't want to make your module publicly available.
<ExtUtils::ModuleMaker> and <Module::Starter> are also good places to start. Many CPAN authors now use <Dist::Zilla> to automate as much as possible.
Detailed documentation about modules can be found at: <perlmod>, <perlmodlib>, <perlmodstyle>.
If you need to include C code or C library interfaces use h2xs. h2xs will create the module distribution structure and the initial interface files. <perlxs> and <perlxstut> explain the details.
###
How do I adopt or take over a module already on CPAN?
Ask the current maintainer to make you a co-maintainer or transfer the module to you.
If you can not reach the author for some reason contact the PAUSE admins at [email protected] who may be able to help, but each case is treated separately.
* Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: <http://pause.perl.org>
* Write to [email protected] explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer.
* Post a public message in a heavily trafficked site announcing your intention to take over the module.
* Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transfer it to you.
###
How do I create a class?
(contributed by brian d foy)
In Perl, a class is just a package, and methods are just subroutines. Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you).
See also <perlootut>, a tutorial that covers class creation, and <perlobj>.
###
How can I tell if a variable is tainted?
You can use the tainted() function of the Scalar::Util module, available from CPAN (or included with Perl since release 5.8.0). See also ["Laundering and Detecting Tainted Data" in perlsec](perlsec#Laundering-and-Detecting-Tainted-Data).
###
What's a closure?
Closures are documented in <perlref>.
*Closure* is a computer science term with a precise but hard-to-explain meaning. Usually, closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding).
Closures are most often used in programming languages where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for example. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures.
Here's a classic non-closure function-generating function:
```
sub add_function_generator {
return sub { shift() + shift() };
}
my $add_sub = add_function_generator();
my $sum = $add_sub->(4,5); # $sum is 9 now.
```
The anonymous subroutine returned by add\_function\_generator() isn't technically a closure because it refers to no lexicals outside its own scope. Using a closure gives you a *function template* with some customization slots left out to be filled later.
Contrast this with the following make\_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created.
```
sub make_adder {
my $addpiece = shift;
return sub { shift() + $addpiece };
}
my $f1 = make_adder(20);
my $f2 = make_adder(555);
```
Now `$f1->($n)` is always 20 plus whatever $n you pass in, whereas `$f2->($n)` is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around.
Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function:
```
my $line;
timeout( 30, sub { $line = <STDIN> } );
```
If the code to execute had been passed in as a string, `'$line = <STDIN>'`, there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope.
Another use for a closure is to make a variable *private* to a named subroutine, e.g. a counter that gets initialized at creation time of the sub and can only be modified from within the sub. This is sometimes used with a BEGIN block in package files to make sure a variable doesn't get meddled with during the lifetime of the package:
```
BEGIN {
my $id = 0;
sub next_id { ++$id }
}
```
This is discussed in more detail in <perlsub>; see the entry on *Persistent Private Variables*.
###
What is variable suicide and how can I prevent it?
This problem was fixed in perl 5.004\_05, so preventing it means upgrading your version of perl. ;)
Variable suicide is when you (temporarily or permanently) lose the value of a variable. It is caused by scoping through my() and local() interacting with either closures or aliased foreach() iterator variables and subroutine arguments. It used to be easy to inadvertently lose a variable's value this way, but now it's much harder. Take this code:
```
my $f = 'foo';
sub T {
while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
}
T;
print "Finally $f\n";
```
If you are experiencing variable suicide, that `my $f` in the subroutine doesn't pick up a fresh copy of the `$f` whose value is `'foo'`. The output shows that inside the subroutine the value of `$f` leaks through when it shouldn't, as in this output:
```
foobar
foobarbar
foobarbarbar
Finally foo
```
The $f that has "bar" added to it three times should be a new `$f` `my $f` should create a new lexical variable each time through the loop. The expected output is:
```
foobar
foobar
foobar
Finally foo
```
###
How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?
You need to pass references to these objects. See ["Pass by Reference" in perlsub](perlsub#Pass-by-Reference) for this particular question, and <perlref> for information on references.
Passing Variables and Functions Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function:
```
func( \$some_scalar );
func( \@some_array );
func( [ 1 .. 10 ] );
func( \%some_hash );
func( { this => 10, that => 20 } );
func( \&some_func );
func( sub { $_[0] ** $_[1] } );
```
Passing Filehandles As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar.
```
open my $fh, $filename or die "Cannot open $filename! $!";
func( $fh );
sub func {
my $passed_fh = shift;
my $line = <$passed_fh>;
}
```
Before Perl 5.6, you had to use the `*FH` or `\*FH` notations. These are "typeglobs"--see ["Typeglobs and Filehandles" in perldata](perldata#Typeglobs-and-Filehandles) and especially ["Pass by Reference" in perlsub](perlsub#Pass-by-Reference) for more information.
Passing Regexes Here's an example of how to pass in a string and a regular expression for it to match against. You construct the pattern with the `qr//` operator:
```
sub compare {
my ($val1, $regex) = @_;
my $retval = $val1 =~ /$regex/;
return $retval;
}
$match = compare("old McDonald", qr/d.*D/i);
```
Passing Methods To pass an object method into a subroutine, you can do this:
```
call_a_lot(10, $some_obj, "methname")
sub call_a_lot {
my ($count, $widget, $trick) = @_;
for (my $i = 0; $i < $count; $i++) {
$widget->$trick();
}
}
```
Or, you can use a closure to bundle up the object, its method call, and arguments:
```
my $whatnot = sub { $some_obj->obfuscate(@args) };
func($whatnot);
sub func {
my $code = shift;
&$code();
}
```
You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution).
###
How do I create a static variable?
(contributed by brian d foy)
In Perl 5.10, declare the variable with `state`. The `state` declaration creates the lexical variable that persists between calls to the subroutine:
```
sub counter { state $count = 1; $count++ }
```
You can fake a static variable by using a lexical variable which goes out of scope. In this example, you define the subroutine `counter`, and it uses the lexical variable `$count`. Since you wrap this in a BEGIN block, `$count` is defined at compile-time, but also goes out of scope at the end of the BEGIN block. The BEGIN block also ensures that the subroutine and the value it uses is defined at compile-time so the subroutine is ready to use just like any other subroutine, and you can put this code in the same place as other subroutines in the program text (i.e. at the end of the code, typically). The subroutine `counter` still has a reference to the data, and is the only way you can access the value (and each time you do, you increment the value). The data in chunk of memory defined by `$count` is private to `counter`.
```
BEGIN {
my $count = 1;
sub counter { $count++ }
}
my $start = counter();
.... # code that calls counter();
my $end = counter();
```
In the previous example, you created a function-private variable because only one function remembered its reference. You could define multiple functions while the variable is in scope, and each function can share the "private" variable. It's not really "static" because you can access it outside the function while the lexical variable is in scope, and even create references to it. In this example, `increment_count` and `return_count` share the variable. One function adds to the value and the other simply returns the value. They can both access `$count`, and since it has gone out of scope, there is no other way to access it.
```
BEGIN {
my $count = 1;
sub increment_count { $count++ }
sub return_count { $count }
}
```
To declare a file-private variable, you still use a lexical variable. A file is also a scope, so a lexical variable defined in the file cannot be seen from any other file.
See ["Persistent Private Variables" in perlsub](perlsub#Persistent-Private-Variables) for more information. The discussion of closures in <perlref> may help you even though we did not use anonymous subroutines in this answer. See ["Persistent Private Variables" in perlsub](perlsub#Persistent-Private-Variables) for details.
###
What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
`local($x)` saves away the old value of the global variable `$x` and assigns a new value for the duration of the subroutine *which is visible in other functions called from that subroutine*. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.
`my($x)` creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.
For instance:
```
sub visible {
print "var has value $var\n";
}
sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}
sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}
$var = 'global';
visible(); # prints global
dynamic(); # prints local
lexical(); # prints global
```
Notice how at no point does the value "private" get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from the called subroutine.
In summary, local() doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables.
See ["Private Variables via my()" in perlsub](perlsub#Private-Variables-via-my%28%29) and ["Temporary Values via local()" in perlsub](perlsub#Temporary-Values-via-local%28%29) for excruciating details.
###
How can I access a dynamic variable while a similarly named lexical is in scope?
If you know your package, you can just mention it explicitly, as in $Some\_Pack::var. Note that the notation $::var is **not** the dynamic $var in the current package, but rather the one in the "main" package, as though you had written $main::var.
```
use vars '$var';
local $var = "global";
my $var = "lexical";
print "lexical is $var\n";
print "global is $main::var\n";
```
Alternatively you can use the compiler directive our() to bring a dynamic variable into the current lexical scope.
```
require 5.006; # our() did not exist before 5.6
use vars '$var';
local $var = "global";
my $var = "lexical";
print "lexical is $var\n";
{
our $var;
print "global is $var\n";
}
```
###
What's the difference between deep and shallow binding?
In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. In shallow binding, they are whichever variables with the same names happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e., those created with my()). However, dynamic variables (aka global, local, or package variables) are effectively shallowly bound. Consider this just one more reason not to use them. See the answer to ["What's a closure?"](#What%27s-a-closure%3F).
###
Why doesn't "my($foo) = <$fh>;" work right?
`my()` and `local()` give list context to the right hand side of `=`. The <$fh> read operation, like so many of Perl's functions and operators, can tell which context it was called in and behaves appropriately. In general, the scalar() function can help. This function does nothing to the data itself (contrary to popular myth) but rather tells its argument to behave in whatever its scalar fashion is. If that function doesn't have a defined scalar behavior, this of course doesn't help you (such as with sort()).
To enforce scalar context in this particular case, however, you need merely omit the parentheses:
```
local($foo) = <$fh>; # WRONG
local($foo) = scalar(<$fh>); # ok
local $foo = <$fh>; # right
```
You should probably be using lexical variables anyway, although the issue is the same here:
```
my($foo) = <$fh>; # WRONG
my $foo = <$fh>; # right
```
###
How do I redefine a builtin function, operator, or method?
Why do you want to do that? :-)
If you want to override a predefined function, such as open(), then you'll have to import the new definition from a different module. See ["Overriding Built-in Functions" in perlsub](perlsub#Overriding-Built-in-Functions).
If you want to overload a Perl operator, such as `+` or `**`, then you'll want to use the `use overload` pragma, documented in <overload>.
If you're talking about obscuring method calls in parent classes, see ["Overriding methods and method resolution" in perlootut](perlootut#Overriding-methods-and-method-resolution).
###
What's the difference between calling a function as &foo and foo()?
(contributed by brian d foy)
Calling a subroutine as `&foo` with no trailing parentheses ignores the prototype of `foo` and passes it the current value of the argument list, `@_`. Here's an example; the `bar` subroutine calls `&foo`, which prints its arguments list:
```
sub foo { print "Args in foo are: @_\n"; }
sub bar { &foo; }
bar( "a", "b", "c" );
```
When you call `bar` with arguments, you see that `foo` got the same `@_`:
```
Args in foo are: a b c
```
Calling the subroutine with trailing parentheses, with or without arguments, does not use the current `@_`. Changing the example to put parentheses after the call to `foo` changes the program:
```
sub foo { print "Args in foo are: @_\n"; }
sub bar { &foo(); }
bar( "a", "b", "c" );
```
Now the output shows that `foo` doesn't get the `@_` from its caller.
```
Args in foo are:
```
However, using `&` in the call still overrides the prototype of `foo` if present:
```
sub foo ($$$) { print "Args infoo are: @_\n"; }
sub bar_1 { &foo; }
sub bar_2 { &foo(); }
sub bar_3 { foo( $_[0], $_[1], $_[2] ); }
# sub bar_4 { foo(); }
# bar_4 doesn't compile: "Not enough arguments for main::foo at ..."
bar_1( "a", "b", "c" );
# Args in foo are: a b c
bar_2( "a", "b", "c" );
# Args in foo are:
bar_3( "a", "b", "c" );
# Args in foo are: a b c
```
The main use of the `@_` pass-through feature is to write subroutines whose main job it is to call other subroutines for you. For further details, see <perlsub>.
###
How do I create a switch or case statement?
There is a given/when statement in Perl, but it is experimental and likely to change in future. See <perlsyn> for more details.
The general answer is to use a CPAN module such as <Switch::Plain>:
```
use Switch::Plain;
sswitch($variable_holding_a_string) {
case 'first': { }
case 'second': { }
default: { }
}
```
or for more complicated comparisons, `if-elsif-else`:
```
for ($variable_to_test) {
if (/pat1/) { } # do something
elsif (/pat2/) { } # do something else
elsif (/pat3/) { } # do something else
else { } # default
}
```
Here's a simple example of a switch based on pattern matching, lined up in a way to make it look more like a switch statement. We'll do a multiway conditional based on the type of reference stored in $whatchamacallit:
```
SWITCH: for (ref $whatchamacallit) {
/^$/ && die "not a reference";
/SCALAR/ && do {
print_scalar($$ref);
last SWITCH;
};
/ARRAY/ && do {
print_array(@$ref);
last SWITCH;
};
/HASH/ && do {
print_hash(%$ref);
last SWITCH;
};
/CODE/ && do {
warn "can't print function ref";
last SWITCH;
};
# DEFAULT
warn "User defined type skipped";
}
```
See <perlsyn> for other examples in this style.
Sometimes you should change the positions of the constant and the variable. For example, let's say you wanted to test which of many answers you were given, but in a case-insensitive way that also allows abbreviations. You can use the following technique if the strings all start with different characters or if you want to arrange the matches so that one takes precedence over another, as `"SEND"` has precedence over `"STOP"` here:
```
chomp($answer = <>);
if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
```
A totally different approach is to create a hash of function references.
```
my %commands = (
"happy" => \&joy,
"sad", => \&sullen,
"done" => sub { die "See ya!" },
"mad" => \&angry,
);
print "How are you? ";
chomp($string = <STDIN>);
if ($commands{$string}) {
$commands{$string}->();
} else {
print "No such command: $string\n";
}
```
Starting from Perl 5.8, a source filter module, `Switch`, can also be used to get switch and case. Its use is now discouraged, because it's not fully compatible with the native switch of Perl 5.10, and because, as it's implemented as a source filter, it doesn't always work as intended when complex syntax is involved.
###
How can I catch accesses to undefined variables, functions, or methods?
The AUTOLOAD method, discussed in ["Autoloading" in perlsub](perlsub#Autoloading) lets you capture calls to undefined functions and methods.
When it comes to undefined variables that would trigger a warning under `use warnings`, you can promote the warning to an error.
```
use warnings FATAL => qw(uninitialized);
```
###
Why can't a method included in this same file be found?
Some possible reasons: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out <perlootut> for details about any of the above cases. You may also use `print ref($object)` to find out the class `$object` was blessed into.
Another possible reason for problems is that you've used the indirect object syntax (eg, `find Guru "Samy"`) on a class name before Perl has seen that such a package exists. It's wisest to make sure your packages are all defined before you start using them, which will be taken care of if you use the `use` statement instead of `require`. If not, make sure to use arrow notation (eg., `Guru->find("Samy")`) instead. Object notation is explained in <perlobj>.
Make sure to read about creating modules in <perlmod> and the perils of indirect objects in ["Method Invocation" in perlobj](perlobj#Method-Invocation).
###
How can I find out my current or calling package?
(contributed by brian d foy)
To find the package you are currently in, use the special literal `__PACKAGE__`, as documented in <perldata>. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables:
```
my $current_package = __PACKAGE__;
print "I am in package $current_package\n";
```
If you want to find the package calling your code, perhaps to give better diagnostics as [Carp](carp) does, use the `caller` built-in:
```
sub foo {
my @args = ...;
my( $package, $filename, $line ) = caller;
print "I was called from package $package\n";
);
```
By default, your program starts in package `main`, so you will always be in some package.
This is different from finding out the package an object is blessed into, which might not be the current package. For that, use `blessed` from <Scalar::Util>, part of the Standard Library since Perl 5.8:
```
use Scalar::Util qw(blessed);
my $object_package = blessed( $object );
```
Most of the time, you shouldn't care what package an object is blessed into, however, as long as it claims to inherit from that class:
```
my $is_right_class = eval { $object->isa( $package ) }; # true or false
```
And, with Perl 5.10 and later, you don't have to check for an inheritance to see if the object can handle a role. For that, you can use `DOES`, which comes from `UNIVERSAL`:
```
my $class_does_it = eval { $object->DOES( $role ) }; # true or false
```
You can safely replace `isa` with `DOES` (although the converse is not true).
###
How can I comment out a large block of Perl code?
(contributed by brian d foy)
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the `#` comments). You end the comment with `=cut`, ending the Pod section:
```
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
```
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The `=begin` directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with `comment`. End the comment using `=end` with the same label. You still need the `=cut` to go back to Perl code from the Pod comment:
```
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
```
For more information on Pod, check out <perlpod> and <perlpodspec>.
###
How do I clear a package?
Use this code, provided by Mark-Jason Dominus:
```
sub scrub_package {
no strict 'refs';
my $pack = shift;
die "Shouldn't delete main package"
if $pack eq "" || $pack eq "main";
my $stash = *{$pack . '::'}{HASH};
my $name;
foreach $name (keys %$stash) {
my $fullname = $pack . '::' . $name;
# Get rid of everything with that name.
undef $$fullname;
undef @$fullname;
undef %$fullname;
undef &$fullname;
undef *$fullname;
}
}
```
Or, if you're using a recent release of Perl, you can just use the Symbol::delete\_package() function instead.
###
How can I use a variable as a variable name?
Beginners often think they want to have a variable contain the name of a variable.
```
$fred = 23;
$varname = "fred";
++$$varname; # $fred now 24
```
This works *sometimes*, but it is a very bad idea for two reasons.
The first reason is that this technique *only works on global variables*. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code.
Symbolic references are forbidden under the `use strict` pragma. They are not true references and consequently are not reference-counted or garbage-collected.
The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash (like `%main::`) instead of a user-defined hash. The solution is to use your own hash or a real reference instead.
```
$USER_VARS{"fred"} = 23;
my $varname = "fred";
$USER_VARS{$varname}++; # not $$varname++
```
There we're using the %USER\_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program's variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables:
```
$str = 'this has a $fred and $barney in it';
$str =~ s/(\$\w+)/$1/eeg; # need double eval
```
it would be better to keep a hash around like %USER\_VARS and have variable references actually refer to entries in that hash:
```
$str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all
```
That's faster, cleaner, and safer than the previous approach. Of course, you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc.
```
$str = 'this has a %fred% and %barney% in it';
$str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all
```
Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build proper data structures using hashes. For example, let's say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name.
```
$name = "fred";
$$name{WIFE} = "wilma"; # set %fred
$name = "barney";
$$name{WIFE} = "betty"; # set %barney
```
This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write:
```
$folks{"fred"}{WIFE} = "wilma";
$folks{"barney"}{WIFE} = "betty";
```
And just use a multilevel hash to start with.
The only times that you absolutely *must* use symbolic references are when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution.
In those cases, you would turn off `strict 'refs'` temporarily so you can play around with the symbol table. For example:
```
@colors = qw(red blue green yellow orange purple violet);
for my $name (@colors) {
no strict 'refs'; # renege for the block
*$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
}
```
All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once.
So, sometimes you might want to use symbolic references to manipulate the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global--you can't use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines-- you probably only want to use hard references.
###
What does "bad interpreter" mean?
(contributed by brian d foy)
The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings.
If you see "bad interpreter - no such file or directory", the first line in your perl script (the "shebang" line) does not contain the right path to perl (or any other program capable of running scripts). Sometimes this happens when you move the script from one machine to another and each machine has a different path to perl--/usr/bin/perl versus /usr/local/bin/perl for instance. It may also indicate that the source machine has CRLF line terminators and the destination machine has LF only: the shell tries to find /usr/bin/perl<CR>, but can't.
If you see "bad interpreter: Permission denied", you need to make your script executable.
In either case, you should still be able to run the scripts with perl explicitly:
```
% perl script.pl
```
If you get a message like "perl: command not found", perl is not in your PATH, which might also mean that the location of perl is not where you expect it so you need to adjust your shebang line.
###
Do I need to recompile XS modules when there is a change in the C library?
(contributed by Alex Beamish)
If the new version of the C library is ABI-compatible (that's Application Binary Interface compatible) with the version you're upgrading from, and if the shared library version didn't change, no re-compilation should be necessary.
AUTHOR AND COPYRIGHT
---------------------
Copyright (c) 1997-2013 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.
| programming_docs |
perl SelectSaver SelectSaver
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
SelectSaver - save and restore selected file handle
SYNOPSIS
--------
```
use SelectSaver;
{
my $saver = SelectSaver->new(FILEHANDLE);
# FILEHANDLE is selected
}
# previous handle is selected
{
my $saver = SelectSaver->new;
# new handle may be selected, or not
}
# previous handle is selected
```
DESCRIPTION
-----------
A `SelectSaver` object contains a reference to the file handle that was selected when it was created. If its `new` method gets an extra parameter, then that parameter is selected; otherwise, the selected file handle remains unchanged.
When a `SelectSaver` is destroyed, it re-selects the file handle that was selected when it was created.
perl Digest::MD5 Digest::MD5
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
* [METHODS](#METHODS)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
* [AUTHORS](#AUTHORS)
NAME
----
Digest::MD5 - Perl interface to the MD5 Algorithm
SYNOPSIS
--------
```
# Functional style
use Digest::MD5 qw(md5 md5_hex md5_base64);
$digest = md5($data);
$digest = md5_hex($data);
$digest = md5_base64($data);
# OO style
use Digest::MD5;
$ctx = Digest::MD5->new;
$ctx->add($data);
$ctx->addfile($file_handle);
$digest = $ctx->digest;
$digest = $ctx->hexdigest;
$digest = $ctx->b64digest;
```
DESCRIPTION
-----------
The `Digest::MD5` module allows you to use the RSA Data Security Inc. MD5 Message Digest algorithm from within Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input.
Note that the MD5 algorithm is not as strong as it used to be. It has since 2005 been easy to generate different messages that produce the same MD5 digest. It still seems hard to generate messages that produce a given digest, but it is probably wise to move to stronger algorithms for applications that depend on the digest to uniquely identify a message.
The `Digest::MD5` module provide a procedural interface for simple use, as well as an object oriented interface that can handle messages of arbitrary length and which can read files directly.
FUNCTIONS
---------
The following functions are provided by the `Digest::MD5` module. None of these functions are exported by default.
md5($data,...) This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form. The returned string will be 16 bytes long.
The result of md5("a", "b", "c") will be exactly the same as the result of md5("abc").
md5\_hex($data,...) Same as md5(), but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'.
md5\_base64($data,...) Same as md5(), but will return the digest as a base64 encoded string. The length of the returned string will be 22 and it will only contain characters from this set: 'A'..'Z', 'a'..'z', '0'..'9', '+' and '/'.
Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the redundant string "==" to the result.
METHODS
-------
The object oriented interface to `Digest::MD5` is described in this section. After a `Digest::MD5` object has been created, you will add data to it and finally ask for the digest in a suitable format. A single object can be used to calculate multiple digests.
The following methods are provided:
$md5 = Digest::MD5->new The constructor returns a new `Digest::MD5` object which encapsulate the state of the MD5 message-digest algorithm.
If called as an instance method (i.e. $md5->new) it will just reset the state the object to the state of a newly created object. No new object is created in this case.
$md5->reset This is just an alias for $md5->new.
$md5->clone This a copy of the $md5 object. It is useful when you do not want to destroy the digests state, but need an intermediate value of the digest, e.g. when calculating digests iteratively on a continuous data stream. Example:
```
my $md5 = Digest::MD5->new;
while (<>) {
$md5->add($_);
print "Line $.: ", $md5->clone->hexdigest, "\n";
}
```
$md5->add($data,...) The $data provided as argument are appended to the message we calculate the digest for. The return value is the $md5 object itself.
All these lines will have the same effect on the state of the $md5 object:
```
$md5->add("a"); $md5->add("b"); $md5->add("c");
$md5->add("a")->add("b")->add("c");
$md5->add("a", "b", "c");
$md5->add("abc");
```
$md5->addfile($io\_handle) The $io\_handle will be read until EOF and its content appended to the message we calculate the digest for. The return value is the $md5 object itself.
The addfile() method will croak() if it fails reading data for some reason. If it croaks it is unpredictable what the state of the $md5 object will be in. The addfile() method might have been able to read the file partially before it failed. It is probably wise to discard or reset the $md5 object if this occurs.
In most cases you want to make sure that the $io\_handle is in `binmode` before you pass it as argument to the addfile() method.
$md5->add\_bits($data, $nbits)
$md5->add\_bits($bitstring) Since the MD5 algorithm is byte oriented you might only add bits as multiples of 8, so you probably want to just use add() instead. The add\_bits() method is provided for compatibility with other digest implementations. See [Digest](digest) for description of the arguments that add\_bits() take.
$md5->digest Return the binary digest for the message. The returned string will be 16 bytes long.
Note that the `digest` operation is effectively a destructive, read-once operation. Once it has been performed, the `Digest::MD5` object is automatically `reset` and can be used to calculate another digest value. Call $md5->clone->digest if you want to calculate the digest without resetting the digest state.
$md5->hexdigest Same as $md5->digest, but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'.
$md5->b64digest Same as $md5->digest, but will return the digest as a base64 encoded string. The length of the returned string will be 22 and it will only contain characters from this set: 'A'..'Z', 'a'..'z', '0'..'9', '+' and '/'.
The base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the string "==" to the result.
@ctx = $md5->context
$md5->context(@ctx) Saves or restores the internal state. When called with no arguments, returns a list: number of blocks processed, a 16-byte internal state buffer, then optionally up to 63 bytes of unprocessed data if there are any. When passed those same arguments, restores the state. This is only useful for specialised operations.
EXAMPLES
--------
The simplest way to use this library is to import the md5\_hex() function (or one of its cousins):
```
use Digest::MD5 qw(md5_hex);
print "Digest is ", md5_hex("foobarbaz"), "\n";
```
The above example would print out the message:
```
Digest is 6df23dc03f9b54cc38a0fc1483df6e21
```
The same checksum can also be calculated in OO style:
```
use Digest::MD5;
$md5 = Digest::MD5->new;
$md5->add('foo', 'bar');
$md5->add('baz');
$digest = $md5->hexdigest;
print "Digest is $digest\n";
```
With OO style, you can break the message arbitrarily. This means that we are no longer limited to have space for the whole message in memory, i.e. we can handle messages of any size.
This is useful when calculating checksum for files:
```
use Digest::MD5;
my $filename = shift || "/etc/passwd";
open (my $fh, '<', $filename) or die "Can't open '$filename': $!";
binmode($fh);
$md5 = Digest::MD5->new;
while (<$fh>) {
$md5->add($_);
}
close($fh);
print $md5->b64digest, " $filename\n";
```
Or we can use the addfile method for more efficient reading of the file:
```
use Digest::MD5;
my $filename = shift || "/etc/passwd";
open (my $fh, '<', $filename) or die "Can't open '$filename': $!";
binmode ($fh);
print Digest::MD5->new->addfile($fh)->hexdigest, " $filename\n";
```
Since the MD5 algorithm is only defined for strings of bytes, it can not be used on strings that contains chars with ordinal number above 255 (Unicode strings). The MD5 functions and methods will croak if you try to feed them such input data:
```
use Digest::MD5 qw(md5_hex);
my $str = "abc\x{300}";
print md5_hex($str), "\n"; # croaks
# Wide character in subroutine entry
```
What you can do is calculate the MD5 checksum of the UTF-8 representation of such strings. This is achieved by filtering the string through encode\_utf8() function:
```
use Digest::MD5 qw(md5_hex);
use Encode qw(encode_utf8);
my $str = "abc\x{300}";
print md5_hex(encode_utf8($str)), "\n";
# 8c2d46911f3f5a326455f0ed7a8ed3b3
```
SEE ALSO
---------
[Digest](digest), <Digest::MD2>, <Digest::SHA>, <Digest::HMAC>
[md5sum(1)](http://man.he.net/man1/md5sum)
RFC 1321
http://en.wikipedia.org/wiki/MD5
The paper "How to Break MD5 and Other Hash Functions" by Xiaoyun Wang and Hongbo Yu.
COPYRIGHT
---------
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
```
Copyright 1998-2003 Gisle Aas.
Copyright 1995-1996 Neil Winton.
Copyright 1991-1992 RSA Data Security, Inc.
```
The MD5 algorithm is defined in RFC 1321. This implementation is derived from the reference C code in RFC 1321 which is covered by the following copyright statement:
* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved.
License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function.
License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this documentation and/or software.
This copyright does not prohibit distribution of any version of Perl containing this extension under the terms of the GNU or Artistic licenses.
AUTHORS
-------
The original `MD5` interface was written by Neil Winton (`[email protected]`).
The `Digest::MD5` module is written by Gisle Aas <[email protected]>.
perl PerlIO::encoding PerlIO::encoding
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
PerlIO::encoding - encoding layer
SYNOPSIS
--------
```
use PerlIO::encoding;
open($f, "<:encoding(foo)", "infoo");
open($f, ">:encoding(bar)", "outbar");
use Encode qw(:fallbacks);
$PerlIO::encoding::fallback = FB_PERLQQ;
```
DESCRIPTION
-----------
This PerlIO layer opens a filehandle with a transparent encoding filter.
On input, it converts the bytes expected to be in the specified character set and encoding to Perl string data (Unicode and Perl's internal Unicode encoding, UTF-8). On output, it converts Perl string data into the specified character set and encoding.
When the layer is pushed, the current value of `$PerlIO::encoding::fallback` is saved and used as the CHECK argument when calling the Encode methods encode() and decode().
SEE ALSO
---------
<open>, [Encode](encode), ["binmode" in perlfunc](perlfunc#binmode), <perluniintro>
perl pod2usage pod2usage
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS AND ARGUMENTS](#OPTIONS-AND-ARGUMENTS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
pod2usage - print usage messages from embedded pod docs in files
SYNOPSIS
--------
**pod2usage** [**-help**] [**-man**] [**-exit***exitval*] [**-output***outfile*] [**-verbose** *level*] [**-pathlist** *dirlist*] [**-formatter** *module*] [**-utf8**] *file*
OPTIONS AND ARGUMENTS
----------------------
**-help**
Print a brief help message and exit.
**-man**
Print this command's manual page and exit.
**-exit** *exitval*
The exit status value to return.
**-output** *outfile*
The output file to print to. If the special names "-" or ">&1" or ">&STDOUT" are used then standard output is used. If ">&2" or ">&STDERR" is used then standard error is used.
**-verbose** *level*
The desired level of verbosity to use:
```
1 : print SYNOPSIS only
2 : print SYNOPSIS sections and any OPTIONS/ARGUMENTS sections
3 : print the entire manpage (similar to running pod2text)
```
**-pathlist** *dirlist*
Specifies one or more directories to search for the input file if it was not supplied with an absolute path. Each directory path in the given list should be separated by a ':' on Unix (';' on MSWin32 and DOS).
**-formatter** *module*
Which text formatter to use. Default is <Pod::Text>, or for very old Perl versions <Pod::PlainText>. An alternative would be e.g. <Pod::Text::Termcap>.
**-utf8**
This option assumes that the formatter (see above) understands the option "utf8". It turns on generation of utf8 output.
*file* The pathname of a file containing pod documentation to be output in usage message format. If omitted, standard input is read - but the output is then formatted with <Pod::Text> only - unless a specific formatter has been specified with **-formatter**.
DESCRIPTION
-----------
**pod2usage** will read the given input file looking for pod documentation and will print the corresponding usage message. If no input file is specified then standard input is read.
**pod2usage** invokes the **pod2usage()** function in the **Pod::Usage** module. Please see ["pod2usage()" in Pod::Usage](Pod::Usage#pod2usage%28%29).
SEE ALSO
---------
<Pod::Usage>, <pod2text>, <Pod::Text>, <Pod::Text::Termcap>, <perldoc>
AUTHOR
------
Please report bugs using <http://rt.cpan.org>.
Brad Appleton <[email protected]>
Based on code for **pod2text(1)** written by Tom Christiansen <[email protected]>
perl modules modules
=======
CONTENTS
--------
* [Pragmatic Modules](#Pragmatic-Modules)
* [Standard Modules](#Standard-Modules)
###
Pragmatic Modules
They work somewhat like compiler directives (pragmata) in that they tend to affect the compilation of your program, and thus will usually work well only when used within a `use`, or `no`. Most of these are lexically scoped, so an inner BLOCK may countermand them by saying:
```
no integer;
no strict 'refs';
no warnings;
```
which lasts until the end of that BLOCK.
Some pragmas are lexically scoped--typically those that affect the `$^H` hints variable. Others affect the current package instead, like `use vars` and `use subs`, which allow you to predeclare a variables or subroutines within a particular *file* rather than just a block. Such declarations are effective for the entire file for which they were declared. You cannot rescind them with `no vars` or `no subs`.
The following pragmas are defined (and have their own documentation).
* **<attributes>** - Get/set subroutine or variable attributes
* **<autodie>** - Replace functions with ones that succeed or die with lexical scope
* **<autodie::exception>** - Exceptions from autodying functions.
* **<autodie::exception::system>** - Exceptions from autodying system().
* **<autodie::hints>** - Provide hints about user subroutines to autodie
* **<autodie::skip>** - Skip a package when throwing autodie exceptions
* **<autouse>** - Postpone load of modules until a function is used
* **<base>** - Establish an ISA relationship with base classes at compile time
* **<bigfloat>** - Transparent big floating point number support for Perl
* **<bigint>** - Transparent big integer support for Perl
* **<bignum>** - Transparent big number support for Perl
* **<bigrat>** - Transparent big rational number support for Perl
* **<blib>** - Use MakeMaker's uninstalled version of a package
* **<builtin>** - Import built-in utility functions
* **<bytes>** - Expose the individual bytes of characters
* **<charnames>** - Access to Unicode character names and named character sequences; also define character names
* **<constant>** - Declare constants
* **<deprecate>** - Perl pragma for deprecating the inclusion of a module in core
* **<diagnostics>** - Produce verbose warning diagnostics
* **<encoding>** - Allows you to write your script in non-ASCII and non-UTF-8
* **<encoding::warnings>** - Warn on implicit encoding conversions
* **<experimental>** - Experimental features made easy
* **<feature>** - Enable new features
* **<fields>** - Compile-time class fields
* **<filetest>** - Control the filetest permission operators
* **<if>** - `use` a Perl module if a condition holds
* **<integer>** - Use integer arithmetic instead of floating point
* **<less>** - Request less of something
* **<lib>** - Manipulate @INC at compile time
* **<locale>** - Use or avoid POSIX locales for built-in operations
* **<mro>** - Method Resolution Order
* **<ok>** - Alternative to Test::More::use\_ok
* **<open>** - Set default PerlIO layers for input and output
* **<ops>** - Restrict unsafe operations when compiling
* **<overload>** - Package for overloading Perl operations
* **<overloading>** - Lexically control overloading
* **<parent>** - Establish an ISA relationship with base classes at compile time
* **<re>** - Alter regular expression behaviour
* **<sigtrap>** - Enable simple signal handling
* **<sort>** - Control sort() behaviour
* **<strict>** - Restrict unsafe constructs
* **<subs>** - Predeclare subroutine names
* **<threads>** - Perl interpreter-based threads
* **<threads::shared>** - Perl extension for sharing data structures between threads
* **<utf8>** - Enable/disable UTF-8 (or UTF-EBCDIC) in source code
* **<vars>** - Predeclare global variable names
* **<version>** - Perl extension for Version Objects
* **<vmsish>** - Control VMS-specific language features
* **<warnings>** - Control optional warnings
* **<warnings::register>** - Warnings import function
###
Standard Modules
Standard, bundled modules are all expected to behave in a well-defined manner with respect to namespace pollution because they use the Exporter module. See their own documentation for details.
It's possible that not all modules listed below are installed on your system. For example, the GDBM\_File module will not be installed if you don't have the gdbm library.
* **<Amiga::ARexx>** - Perl extension for ARexx support
* **<Amiga::Exec>** - Perl extension for low level amiga support
* **[AnyDBM\_File](anydbm_file)** - Provide framework for multiple DBMs
* **<App::Cpan>** - Easily interact with CPAN from the command line
* **<App::Prove>** - Implements the `prove` command.
* **<App::Prove::State>** - State storage for the `prove` command.
* **<App::Prove::State::Result>** - Individual test suite results.
* **<App::Prove::State::Result::Test>** - Individual test results.
* **<Archive::Tar>** - Module for manipulations of tar archives
* **<Archive::Tar::File>** - A subclass for in-memory extracted file from Archive::Tar
* **<Attribute::Handlers>** - Simpler definition of attribute handlers
* **[AutoLoader](autoloader)** - Load subroutines only on demand
* **[AutoSplit](autosplit)** - Split a package for autoloading
* **[B](b)** - The Perl Compiler Backend
* **<B::Concise>** - Walk Perl syntax tree, printing concise info about ops
* **<B::Deparse>** - Perl compiler backend to produce perl code
* **<B::Op_private>** - OP op\_private flag definitions
* **<B::Showlex>** - Show lexical variables used in functions or files
* **<B::Terse>** - Walk Perl syntax tree, printing terse info about ops
* **<B::Xref>** - Generates cross reference reports for Perl programs
* **[Benchmark](benchmark)** - Benchmark running times of Perl code
* **[`IO::Socket::IP`](IO::Socket::IP)** - Family-neutral IP socket supporting both IPv4 and IPv6
* **[`Socket`](socket)** - Networking constants and support functions
* **[CORE](core)** - Namespace for Perl's core routines
* **[CPAN](cpan)** - Query, download and build perl modules from CPAN sites
* **<CPAN::API::HOWTO>** - A recipe book for programming with CPAN.pm
* **<CPAN::Debug>** - Internal debugging for CPAN.pm
* **<CPAN::Distroprefs>** - Read and match distroprefs
* **<CPAN::FirstTime>** - Utility for CPAN::Config file Initialization
* **<CPAN::HandleConfig>** - Internal configuration handling for CPAN.pm
* **<CPAN::Kwalify>** - Interface between CPAN.pm and Kwalify.pm
* **<CPAN::Meta>** - The distribution metadata for a CPAN dist
* **<CPAN::Meta::Converter>** - Convert CPAN distribution metadata structures
* **<CPAN::Meta::Feature>** - An optional feature provided by a CPAN distribution
* **<CPAN::Meta::History>** - History of CPAN Meta Spec changes
* **<CPAN::Meta::History::Meta_1_0>** - Version 1.0 metadata specification for META.yml
* **<CPAN::Meta::History::Meta_1_1>** - Version 1.1 metadata specification for META.yml
* **<CPAN::Meta::History::Meta_1_2>** - Version 1.2 metadata specification for META.yml
* **<CPAN::Meta::History::Meta_1_3>** - Version 1.3 metadata specification for META.yml
* **<CPAN::Meta::History::Meta_1_4>** - Version 1.4 metadata specification for META.yml
* **<CPAN::Meta::Merge>** - Merging CPAN Meta fragments
* **<CPAN::Meta::Prereqs>** - A set of distribution prerequisites by phase and type
* **<CPAN::Meta::Requirements>** - A set of version requirements for a CPAN dist
* **<CPAN::Meta::Spec>** - Specification for CPAN distribution metadata
* **<CPAN::Meta::Validator>** - Validate CPAN distribution metadata structures
* **<CPAN::Meta::YAML>** - Read and write a subset of YAML for CPAN Meta files
* **<CPAN::Nox>** - Wrapper around CPAN.pm without using any XS module
* **<CPAN::Plugin>** - Base class for CPAN shell extensions
* **<CPAN::Plugin::Specfile>** - Proof of concept implementation of a trivial CPAN::Plugin
* **<CPAN::Queue>** - Internal queue support for CPAN.pm
* **<CPAN::Tarzip>** - Internal handling of tar archives for CPAN.pm
* **<CPAN::Version>** - Utility functions to compare CPAN versions
* **[Carp](carp)** - Alternative warn and die for modules
* **<Class::Struct>** - Declare struct-like datatypes as Perl classes
* **<Compress::Raw::Bzip2>** - Low-Level Interface to bzip2 compression library
* **<Compress::Raw::Zlib>** - Low-Level Interface to zlib compression library
* **<Compress::Zlib>** - Interface to zlib compression library
* **[Config](config)** - Access Perl configuration information
* **<Config::Extensions>** - Hash lookup of which core extensions were built.
* **<Config::Perl::V>** - Structured data retrieval of perl -V output
* **[Cwd](cwd)** - Get pathname of current working directory
* **[DB](db)** - Programmatic interface to the Perl debugging API
* **[DBM\_Filter](dbm_filter)** - Filter DBM keys/values
* **<DBM_Filter::compress>** - Filter for DBM\_Filter
* **<DBM_Filter::encode>** - Filter for DBM\_Filter
* **<DBM_Filter::int32>** - Filter for DBM\_Filter
* **<DBM_Filter::null>** - Filter for DBM\_Filter
* **<DBM_Filter::utf8>** - Filter for DBM\_Filter
* **[DB\_File](db_file)** - Perl5 access to Berkeley DB version 1.x
* **<Data::Dumper>** - Stringified perl data structures, suitable for both printing and `eval`
* **<Devel::PPPort>** - Perl/Pollution/Portability
* **<Devel::Peek>** - A data debugging tool for the XS programmer
* **<Devel::SelfStubber>** - Generate stubs for a SelfLoading module
* **[Digest](digest)** - Modules that calculate message digests
* **<Digest::MD5>** - Perl interface to the MD5 Algorithm
* **<Digest::SHA>** - Perl extension for SHA-1/224/256/384/512
* **<Digest::base>** - Digest base class
* **<Digest::file>** - Calculate digests of files
* **[DirHandle](dirhandle)** - (obsolete) supply object methods for directory handles
* **[Dumpvalue](dumpvalue)** - Provides screen dump of Perl data.
* **[DynaLoader](dynaloader)** - Dynamically load C libraries into Perl code
* **[Encode](encode)** - Character encodings in Perl
* **<Encode::Alias>** - Alias definitions to encodings
* **<Encode::Byte>** - Single Byte Encodings
* **<Encode::CJKConstants>** - Internally used by Encode::??::ISO\_2022\_\*
* **<Encode::CN>** - China-based Chinese Encodings
* **<Encode::CN::HZ>** - Internally used by Encode::CN
* **<Encode::Config>** - Internally used by Encode
* **<Encode::EBCDIC>** - EBCDIC Encodings
* **<Encode::Encoder>** - Object Oriented Encoder
* **<Encode::Encoding>** - Encode Implementation Base Class
* **<Encode::GSM0338>** - ETSI GSM 03.38 Encoding
* **<Encode::Guess>** - Guesses encoding from data
* **<Encode::JP>** - Japanese Encodings
* **<Encode::JP::H2Z>** - Internally used by Encode::JP::2022\_JP\*
* **<Encode::JP::JIS7>** - Internally used by Encode::JP
* **<Encode::KR>** - Korean Encodings
* **<Encode::KR::2022_KR>** - Internally used by Encode::KR
* **<Encode::MIME::Header>** - MIME encoding for an unstructured email header
* **<Encode::MIME::Name>** - Internally used by Encode
* **<Encode::PerlIO>** - A detailed document on Encode and PerlIO
* **<Encode::Supported>** - Encodings supported by Encode
* **<Encode::Symbol>** - Symbol Encodings
* **<Encode::TW>** - Taiwan-based Chinese Encodings
* **<Encode::Unicode>** - Various Unicode Transformation Formats
* **<Encode::Unicode::UTF7>** - UTF-7 encoding
* **[English](english)** - Use nice English (or awk) names for ugly punctuation variables
* **[Env](env)** - Perl module that imports environment variables as scalars or arrays
* **[Errno](errno)** - System errno constants
* **[Exporter](exporter)** - Implements default import method for modules
* **<Exporter::Heavy>** - Exporter guts
* **<ExtUtils::CBuilder>** - Compile and link C code for Perl modules
* **<ExtUtils::CBuilder::Platform::Windows>** - Builder class for Windows platforms
* **<ExtUtils::Command>** - Utilities to replace common UNIX commands in Makefiles etc.
* **<ExtUtils::Command::MM>** - Commands for the MM's to use in Makefiles
* **<ExtUtils::Constant>** - Generate XS code to import C header constants
* **<ExtUtils::Constant::Base>** - Base class for ExtUtils::Constant objects
* **<ExtUtils::Constant::Utils>** - Helper functions for ExtUtils::Constant
* **<ExtUtils::Constant::XS>** - Generate C code for XS modules' constants.
* **<ExtUtils::Embed>** - Utilities for embedding Perl in C/C++ applications
* **<ExtUtils::Install>** - Install files from here to there
* **<ExtUtils::Installed>** - Inventory management of installed modules
* **<ExtUtils::Liblist>** - Determine libraries to use and how to use them
* **<ExtUtils::MM>** - OS adjusted ExtUtils::MakeMaker subclass
* **<ExtUtils::MM_AIX>** - AIX specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_Any>** - Platform-agnostic MM methods
* **<ExtUtils::MM_BeOS>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_Cygwin>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_DOS>** - DOS specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_Darwin>** - Special behaviors for OS X
* **<ExtUtils::MM_MacOS>** - Once produced Makefiles for MacOS Classic
* **<ExtUtils::MM_NW5>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_OS2>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_OS390>** - OS390 specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_QNX>** - QNX specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_UWIN>** - U/WIN specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_Unix>** - Methods used by ExtUtils::MakeMaker
* **<ExtUtils::MM_VMS>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_VOS>** - VOS specific subclass of ExtUtils::MM\_Unix
* **<ExtUtils::MM_Win32>** - Methods to override UN\*X behaviour in ExtUtils::MakeMaker
* **<ExtUtils::MM_Win95>** - Method to customize MakeMaker for Win9X
* **<ExtUtils::MY>** - ExtUtils::MakeMaker subclass for customization
* **<ExtUtils::MakeMaker>** - Create a module Makefile
* **<ExtUtils::MakeMaker::Config>** - Wrapper around Config.pm
* **<ExtUtils::MakeMaker::FAQ>** - Frequently Asked Questions About MakeMaker
* **<ExtUtils::MakeMaker::Locale>** - Bundled Encode::Locale
* **<ExtUtils::MakeMaker::Tutorial>** - Writing a module with MakeMaker
* **<ExtUtils::Manifest>** - Utilities to write and check a MANIFEST file
* **<ExtUtils::Miniperl>** - Write the C code for miniperlmain.c and perlmain.c
* **<ExtUtils::Mkbootstrap>** - Make a bootstrap file for use by DynaLoader
* **<ExtUtils::Mksymlists>** - Write linker options files for dynamic extension
* **<ExtUtils::PL2Bat>** - Batch file creation to run perl scripts on Windows
* **<ExtUtils::Packlist>** - Manage .packlist files
* **<ExtUtils::ParseXS>** - Converts Perl XS code into C code
* **<ExtUtils::ParseXS::Constants>** - Initialization values for some globals
* **<ExtUtils::ParseXS::Eval>** - Clean package to evaluate code in
* **<ExtUtils::ParseXS::Utilities>** - Subroutines used with ExtUtils::ParseXS
* **<ExtUtils::Typemaps>** - Read/Write/Modify Perl/XS typemap files
* **<ExtUtils::Typemaps::Cmd>** - Quick commands for handling typemaps
* **<ExtUtils::Typemaps::InputMap>** - Entry in the INPUT section of a typemap
* **<ExtUtils::Typemaps::OutputMap>** - Entry in the OUTPUT section of a typemap
* **<ExtUtils::Typemaps::Type>** - Entry in the TYPEMAP section of a typemap
* **<ExtUtils::XSSymSet>** - Keep sets of symbol names palatable to the VMS linker
* **<ExtUtils::testlib>** - Add blib/\* directories to @INC
* **[Fatal](fatal)** - Replace functions with equivalents which succeed or die
* **[Fcntl](fcntl)** - Load the C Fcntl.h defines
* **<File::Basename>** - Parse file paths into directory, filename and suffix.
* **<File::Compare>** - Compare files or filehandles
* **<File::Copy>** - Copy files or filehandles
* **<File::DosGlob>** - DOS like globbing and then some
* **<File::Fetch>** - A generic file fetching mechanism
* **<File::Find>** - Traverse a directory tree.
* **<File::Glob>** - Perl extension for BSD glob routine
* **<File::GlobMapper>** - Extend File Glob to Allow Input and Output Files
* **<File::Path>** - Create or remove directory trees
* **<File::Spec>** - Portably perform operations on file names
* **<File::Spec::AmigaOS>** - File::Spec for AmigaOS
* **<File::Spec::Cygwin>** - Methods for Cygwin file specs
* **<File::Spec::Epoc>** - Methods for Epoc file specs
* **<File::Spec::Functions>** - Portably perform operations on file names
* **<File::Spec::Mac>** - File::Spec for Mac OS (Classic)
* **<File::Spec::OS2>** - Methods for OS/2 file specs
* **<File::Spec::Unix>** - File::Spec for Unix, base for other File::Spec modules
* **<File::Spec::VMS>** - Methods for VMS file specs
* **<File::Spec::Win32>** - Methods for Win32 file specs
* **<File::Temp>** - Return name and handle of a temporary file safely
* **<File::stat>** - By-name interface to Perl's built-in stat() functions
* **[FileCache](filecache)** - Keep more files open than the system permits
* **[FileHandle](filehandle)** - Supply object methods for filehandles
* **<Filter::Simple>** - Simplified source filtering
* **<Filter::Util::Call>** - Perl Source Filter Utility Module
* **[FindBin](findbin)** - Locate directory of original perl script
* **[GDBM\_File](gdbm_file)** - Perl5 access to the gdbm library.
* **<Getopt::Long>** - Extended processing of command line options
* **<Getopt::Std>** - Process single-character switches with switch clustering
* **<HTTP::Tiny>** - A small, simple, correct HTTP/1.1 client
* **<Hash::Util>** - A selection of general-utility hash subroutines
* **<Hash::Util::FieldHash>** - Support for Inside-Out Classes
* **<I18N::Collate>** - Compare 8-bit scalar data according to the current locale
* **<I18N::LangTags>** - Functions for dealing with RFC3066-style language tags
* **<I18N::LangTags::Detect>** - Detect the user's language preferences
* **<I18N::LangTags::List>** - Tags and names for human languages
* **<I18N::Langinfo>** - Query locale information
* **[IO](io)** - Load various IO modules
* **<IO::Compress::Base>** - Base Class for IO::Compress modules
* **<IO::Compress::Bzip2>** - Write bzip2 files/buffers
* **<IO::Compress::Deflate>** - Write RFC 1950 files/buffers
* **<IO::Compress::FAQ>** - Frequently Asked Questions about IO::Compress
* **<IO::Compress::Gzip>** - Write RFC 1952 files/buffers
* **<IO::Compress::RawDeflate>** - Write RFC 1951 files/buffers
* **<IO::Compress::Zip>** - Write zip files/buffers
* **<IO::Dir>** - Supply object methods for directory handles
* **<IO::File>** - Supply object methods for filehandles
* **<IO::Handle>** - Supply object methods for I/O handles
* **<IO::Pipe>** - Supply object methods for pipes
* **<IO::Poll>** - Object interface to system poll call
* **<IO::Seekable>** - Supply seek based methods for I/O objects
* **<IO::Select>** - OO interface to the select system call
* **<IO::Socket>** - Object interface to socket communications
* **<IO::Socket::INET>** - Object interface for AF\_INET domain sockets
* **<IO::Socket::UNIX>** - Object interface for AF\_UNIX domain sockets
* **<IO::Uncompress::AnyInflate>** - Uncompress zlib-based (zip, gzip) file/buffer
* **<IO::Uncompress::AnyUncompress>** - Uncompress gzip, zip, bzip2, zstd, xz, lzma, lzip, lzf or lzop file/buffer
* **<IO::Uncompress::Base>** - Base Class for IO::Uncompress modules
* **<IO::Uncompress::Bunzip2>** - Read bzip2 files/buffers
* **<IO::Uncompress::Gunzip>** - Read RFC 1952 files/buffers
* **<IO::Uncompress::Inflate>** - Read RFC 1950 files/buffers
* **<IO::Uncompress::RawInflate>** - Read RFC 1951 files/buffers
* **<IO::Uncompress::Unzip>** - Read zip files/buffers
* **<IO::Zlib>** - IO:: style interface to <Compress::Zlib>
* **<IPC::Cmd>** - Finding and running system commands made easy
* **<IPC::Msg>** - SysV Msg IPC object class
* **<IPC::Open2>** - Open a process for both reading and writing using open2()
* **<IPC::Open3>** - Open a process for reading, writing, and error handling using open3()
* **<IPC::Semaphore>** - SysV Semaphore IPC object class
* **<IPC::SharedMem>** - SysV Shared Memory IPC object class
* **<IPC::SysV>** - System V IPC constants and system calls
* **[Internals](internals)** - Reserved special namespace for internals related functions
* **<JSON::PP>** - JSON::XS compatible pure-Perl module.
* **<JSON::PP::Boolean>** - Dummy module providing JSON::PP::Boolean
* **<List::Util>** - A selection of general-utility list subroutines
* **<List::Util::XS>** - Indicate if List::Util was compiled with a C compiler
* **<Locale::Maketext>** - Framework for localization
* **<Locale::Maketext::Cookbook>** - Recipes for using Locale::Maketext
* **<Locale::Maketext::Guts>** - Deprecated module to load Locale::Maketext utf8 code
* **<Locale::Maketext::GutsLoader>** - Deprecated module to load Locale::Maketext utf8 code
* **<Locale::Maketext::Simple>** - Simple interface to Locale::Maketext::Lexicon
* **<Locale::Maketext::TPJ13>** - Article about software localization
* **<MIME::Base64>** - Encoding and decoding of base64 strings
* **<MIME::QuotedPrint>** - Encoding and decoding of quoted-printable strings
* **<Math::BigFloat>** - Arbitrary size floating point math package
* **<Math::BigInt>** - Arbitrary size integer math package
* **<Math::BigInt::Calc>** - Pure Perl module to support Math::BigInt
* **<Math::BigInt::FastCalc>** - Math::BigInt::Calc with some XS for more speed
* **<Math::BigInt::Lib>** - Virtual parent class for Math::BigInt libraries
* **<Math::BigRat>** - Arbitrary size rational number math package
* **<Math::Complex>** - Complex numbers and associated mathematical functions
* **<Math::Trig>** - Trigonometric functions
* **[Memoize](memoize)** - Make functions faster by trading space for time
* **<Memoize::AnyDBM_File>** - Glue to provide EXISTS for AnyDBM\_File for Storable use
* **<Memoize::Expire>** - Plug-in module for automatic expiration of memoized values
* **<Memoize::ExpireFile>** - Test for Memoize expiration semantics
* **<Memoize::ExpireTest>** - Test for Memoize expiration semantics
* **<Memoize::NDBM_File>** - Glue to provide EXISTS for NDBM\_File for Storable use
* **<Memoize::SDBM_File>** - Glue to provide EXISTS for SDBM\_File for Storable use
* **<Memoize::Storable>** - Store Memoized data in Storable database
* **<Module::CoreList>** - What modules shipped with versions of perl
* **<Module::CoreList::Utils>** - What utilities shipped with versions of perl
* **<Module::Load>** - Runtime require of both modules and files
* **<Module::Load::Conditional>** - Looking up module information / loading at runtime
* **<Module::Loaded>** - Mark modules as loaded or unloaded
* **<Module::Metadata>** - Gather package and POD information from perl module files
* **[NDBM\_File](ndbm_file)** - Tied access to ndbm files
* **[NEXT](next)** - Provide a pseudo-class NEXT (et al) that allows method redispatch
* **<Net::Cmd>** - Network Command class (as used by FTP, SMTP etc)
* **<Net::Config>** - Local configuration data for libnet
* **<Net::Domain>** - Attempt to evaluate the current host's internet name and domain
* **<Net::FTP>** - FTP Client class
* **<Net::FTP::dataconn>** - FTP Client data connection class
* **<Net::NNTP>** - NNTP Client class
* **<Net::Netrc>** - OO interface to users netrc file
* **<Net::POP3>** - Post Office Protocol 3 Client class (RFC1939)
* **<Net::Ping>** - Check a remote host for reachability
* **<Net::SMTP>** - Simple Mail Transfer Protocol Client
* **<Net::Time>** - Time and daytime network client interface
* **<Net::hostent>** - By-name interface to Perl's built-in gethost\*() functions
* **<Net::libnetFAQ>** - Libnet Frequently Asked Questions
* **<Net::netent>** - By-name interface to Perl's built-in getnet\*() functions
* **<Net::protoent>** - By-name interface to Perl's built-in getproto\*() functions
* **<Net::servent>** - By-name interface to Perl's built-in getserv\*() functions
* **[O](o)** - Generic interface to Perl Compiler backends
* **[ODBM\_File](odbm_file)** - Tied access to odbm files
* **[Opcode](opcode)** - Disable named opcodes when compiling perl code
* **[POSIX](posix)** - Perl interface to IEEE Std 1003.1
* **<Params::Check>** - A generic input parsing/checking mechanism.
* **<Parse::CPAN::Meta>** - Parse META.yml and META.json CPAN metadata files
* **<Perl::OSType>** - Map Perl operating system names to generic types
* **[PerlIO](perlio)** - On demand loader for PerlIO layers and root of PerlIO::\* name space
* **<PerlIO::encoding>** - Encoding layer
* **<PerlIO::mmap>** - Memory mapped IO
* **<PerlIO::scalar>** - In-memory IO, scalar IO
* **<PerlIO::via>** - Helper class for PerlIO layers implemented in perl
* **<PerlIO::via::QuotedPrint>** - PerlIO layer for quoted-printable strings
* **<Pod::Checker>** - Check pod documents for syntax errors
* **<Pod::Escapes>** - For resolving Pod E<...> sequences
* **<Pod::Functions>** - Group Perl's functions a la perlfunc.pod
* **<Pod::Html>** - Module to convert pod files to HTML
* **<Pod::Html::Util>** - Helper functions for Pod-Html
* **<Pod::Man>** - Convert POD data to formatted \*roff input
* **<Pod::ParseLink>** - Parse an L<> formatting code in POD text
* **<Pod::Perldoc>** - Look up Perl documentation in Pod format.
* **<Pod::Perldoc::BaseTo>** - Base for Pod::Perldoc formatters
* **<Pod::Perldoc::GetOptsOO>** - Customized option parser for Pod::Perldoc
* **<Pod::Perldoc::ToANSI>** - Render Pod with ANSI color escapes
* **<Pod::Perldoc::ToChecker>** - Let Perldoc check Pod for errors
* **<Pod::Perldoc::ToMan>** - Let Perldoc render Pod as man pages
* **<Pod::Perldoc::ToNroff>** - Let Perldoc convert Pod to nroff
* **<Pod::Perldoc::ToPod>** - Let Perldoc render Pod as ... Pod!
* **<Pod::Perldoc::ToRtf>** - Let Perldoc render Pod as RTF
* **<Pod::Perldoc::ToTerm>** - Render Pod with terminal escapes
* **<Pod::Perldoc::ToText>** - Let Perldoc render Pod as plaintext
* **<Pod::Perldoc::ToTk>** - Let Perldoc use Tk::Pod to render Pod
* **<Pod::Perldoc::ToXml>** - Let Perldoc render Pod as XML
* **<Pod::Simple>** - Framework for parsing Pod
* **<Pod::Simple::Checker>** - Check the Pod syntax of a document
* **<Pod::Simple::Debug>** - Put Pod::Simple into trace/debug mode
* **<Pod::Simple::DumpAsText>** - Dump Pod-parsing events as text
* **<Pod::Simple::DumpAsXML>** - Turn Pod into XML
* **<Pod::Simple::HTML>** - Convert Pod to HTML
* **<Pod::Simple::HTMLBatch>** - Convert several Pod files to several HTML files
* **<Pod::Simple::JustPod>** - Just the Pod, the whole Pod, and nothing but the Pod
* **<Pod::Simple::LinkSection>** - Represent "section" attributes of L codes
* **<Pod::Simple::Methody>** - Turn Pod::Simple events into method calls
* **<Pod::Simple::PullParser>** - A pull-parser interface to parsing Pod
* **<Pod::Simple::PullParserEndToken>** - End-tokens from Pod::Simple::PullParser
* **<Pod::Simple::PullParserStartToken>** - Start-tokens from Pod::Simple::PullParser
* **<Pod::Simple::PullParserTextToken>** - Text-tokens from Pod::Simple::PullParser
* **<Pod::Simple::PullParserToken>** - Tokens from Pod::Simple::PullParser
* **<Pod::Simple::RTF>** - Format Pod as RTF
* **<Pod::Simple::Search>** - Find POD documents in directory trees
* **<Pod::Simple::SimpleTree>** - Parse Pod into a simple parse tree
* **<Pod::Simple::Subclassing>** - Write a formatter as a Pod::Simple subclass
* **<Pod::Simple::Text>** - Format Pod as plaintext
* **<Pod::Simple::TextContent>** - Get the text content of Pod
* **<Pod::Simple::XHTML>** - Format Pod as validating XHTML
* **<Pod::Simple::XMLOutStream>** - Turn Pod into XML
* **<Pod::Text>** - Convert POD data to formatted text
* **<Pod::Text::Color>** - Convert POD data to formatted color ASCII text
* **<Pod::Text::Overstrike>** - Convert POD data to formatted overstrike text
* **<Pod::Text::Termcap>** - Convert POD data to ASCII text with format escapes
* **<Pod::Usage>** - Extracts POD documentation and shows usage information
* **[SDBM\_File](sdbm_file)** - Tied access to sdbm files
* **[Safe](safe)** - Compile and execute code in restricted compartments
* **<Scalar::Util>** - A selection of general-utility scalar subroutines
* **<Search::Dict>** - Look - search for key in dictionary file
* **[SelectSaver](selectsaver)** - Save and restore selected file handle
* **[SelfLoader](selfloader)** - Load functions only on demand
* **[Storable](storable)** - Persistence for Perl data structures
* **<Sub::Util>** - A selection of utility subroutines for subs and CODE references
* **[Symbol](symbol)** - Manipulate Perl symbols and their names
* **<Sys::Hostname>** - Try every conceivable way to get hostname
* **<Sys::Syslog>** - Perl interface to the UNIX syslog(3) calls
* **<Sys::Syslog::Win32>** - Win32 support for Sys::Syslog
* **<TAP::Base>** - Base class that provides common functionality to <TAP::Parser>
* **<TAP::Formatter::Base>** - Base class for harness output delegates
* **<TAP::Formatter::Color>** - Run Perl test scripts with color
* **<TAP::Formatter::Console>** - Harness output delegate for default console output
* **<TAP::Formatter::Console::ParallelSession>** - Harness output delegate for parallel console output
* **<TAP::Formatter::Console::Session>** - Harness output delegate for default console output
* **<TAP::Formatter::File>** - Harness output delegate for file output
* **<TAP::Formatter::File::Session>** - Harness output delegate for file output
* **<TAP::Formatter::Session>** - Abstract base class for harness output delegate
* **<TAP::Harness>** - Run test scripts with statistics
* **<TAP::Harness::Env>** - Parsing harness related environmental variables where appropriate
* **<TAP::Object>** - Base class that provides common functionality to all `TAP::*` modules
* **<TAP::Parser>** - Parse [TAP](Test::Harness::TAP) output
* **<TAP::Parser::Aggregator>** - Aggregate TAP::Parser results
* **<TAP::Parser::Grammar>** - A grammar for the Test Anything Protocol.
* **<TAP::Parser::Iterator>** - Base class for TAP source iterators
* **<TAP::Parser::Iterator::Array>** - Iterator for array-based TAP sources
* **<TAP::Parser::Iterator::Process>** - Iterator for process-based TAP sources
* **<TAP::Parser::Iterator::Stream>** - Iterator for filehandle-based TAP sources
* **<TAP::Parser::IteratorFactory>** - Figures out which SourceHandler objects to use for a given Source
* **<TAP::Parser::Multiplexer>** - Multiplex multiple TAP::Parsers
* **<TAP::Parser::Result>** - Base class for TAP::Parser output objects
* **<TAP::Parser::Result::Bailout>** - Bailout result token.
* **<TAP::Parser::Result::Comment>** - Comment result token.
* **<TAP::Parser::Result::Plan>** - Plan result token.
* **<TAP::Parser::Result::Pragma>** - TAP pragma token.
* **<TAP::Parser::Result::Test>** - Test result token.
* **<TAP::Parser::Result::Unknown>** - Unknown result token.
* **<TAP::Parser::Result::Version>** - TAP syntax version token.
* **<TAP::Parser::Result::YAML>** - YAML result token.
* **<TAP::Parser::ResultFactory>** - Factory for creating TAP::Parser output objects
* **<TAP::Parser::Scheduler>** - Schedule tests during parallel testing
* **<TAP::Parser::Scheduler::Job>** - A single testing job.
* **<TAP::Parser::Scheduler::Spinner>** - A no-op job.
* **<TAP::Parser::Source>** - A TAP source & meta data about it
* **<TAP::Parser::SourceHandler>** - Base class for different TAP source handlers
* **<TAP::Parser::SourceHandler::Executable>** - Stream output from an executable TAP source
* **<TAP::Parser::SourceHandler::File>** - Stream TAP from a text file.
* **<TAP::Parser::SourceHandler::Handle>** - Stream TAP from an IO::Handle or a GLOB.
* **<TAP::Parser::SourceHandler::Perl>** - Stream TAP from a Perl executable
* **<TAP::Parser::SourceHandler::RawTAP>** - Stream output from raw TAP in a scalar/array ref.
* **<TAP::Parser::YAMLish::Reader>** - Read YAMLish data from iterator
* **<TAP::Parser::YAMLish::Writer>** - Write YAMLish data
* **<Term::ANSIColor>** - Color screen output using ANSI escape sequences
* **<Term::Cap>** - Perl termcap interface
* **<Term::Complete>** - Perl word completion module
* **<Term::ReadLine>** - Perl interface to various `readline` packages.
* **[Test](test)** - Provides a simple framework for writing test scripts
* **[Test2](test2)** - Framework for writing test tools that all work together.
* **<Test2::API>** - Primary interface for writing Test2 based testing tools.
* **<Test2::API::Breakage>** - What breaks at what version
* **<Test2::API::Context>** - Object to represent a testing context.
* **<Test2::API::Instance>** - Object used by Test2::API under the hood
* **<Test2::API::InterceptResult>** - Representation of a list of events.
* **<Test2::API::InterceptResult::Event>** - Representation of an event for use in
* **<Test2::API::InterceptResult::Hub>** - Hub used by InterceptResult.
* **<Test2::API::InterceptResult::Squasher>** - Encapsulation of the algorithm that
* **<Test2::API::Stack>** - Object to manage a stack of <Test2::Hub>
* **<Test2::Event>** - Base class for events
* **<Test2::Event::Bail>** - Bailout!
* **<Test2::Event::Diag>** - Diag event type
* **<Test2::Event::Encoding>** - Set the encoding for the output stream
* **<Test2::Event::Exception>** - Exception event
* **<Test2::Event::Fail>** - Event for a simple failed assertion
* **<Test2::Event::Generic>** - Generic event type.
* **<Test2::Event::Note>** - Note event type
* **<Test2::Event::Ok>** - Ok event type
* **<Test2::Event::Pass>** - Event for a simple passing assertion
* **<Test2::Event::Plan>** - The event of a plan
* **<Test2::Event::Skip>** - Skip event type
* **<Test2::Event::Subtest>** - Event for subtest types
* **<Test2::Event::TAP::Version>** - Event for TAP version.
* **<Test2::Event::V2>** - Second generation event.
* **<Test2::Event::Waiting>** - Tell all procs/threads it is time to be done
* **<Test2::EventFacet>** - Base class for all event facets.
* **<Test2::EventFacet::About>** - Facet with event details.
* **<Test2::EventFacet::Amnesty>** - Facet for assertion amnesty.
* **<Test2::EventFacet::Assert>** - Facet representing an assertion.
* **<Test2::EventFacet::Control>** - Facet for hub actions and behaviors.
* **<Test2::EventFacet::Error>** - Facet for errors that need to be shown.
* **<Test2::EventFacet::Hub>** - Facet for the hubs an event passes through.
* **<Test2::EventFacet::Info>** - Facet for information a developer might care about.
* **<Test2::EventFacet::Info::Table>** - Intermediary representation of a table.
* **<Test2::EventFacet::Meta>** - Facet for meta-data
* **<Test2::EventFacet::Parent>** - Facet for events contains other events
* **<Test2::EventFacet::Plan>** - Facet for setting the plan
* **<Test2::EventFacet::Render>** - Facet that dictates how to render an event.
* **<Test2::EventFacet::Trace>** - Debug information for events
* **<Test2::Formatter>** - Namespace for formatters.
* **<Test2::Formatter::TAP>** - Standard TAP formatter
* **<Test2::Hub>** - The conduit through which all events flow.
* **<Test2::Hub::Interceptor>** - Hub used by interceptor to grab results.
* **<Test2::Hub::Interceptor::Terminator>** - Exception class used by
* **<Test2::Hub::Subtest>** - Hub used by subtests
* **<Test2::IPC>** - Turn on IPC for threading or forking support.
* **<Test2::IPC::Driver>** - Base class for Test2 IPC drivers.
* **<Test2::IPC::Driver::Files>** - Temp dir + Files concurrency model.
* **<Test2::Tools::Tiny>** - Tiny set of tools for unfortunate souls who cannot use
* **<Test2::Transition>** - Transition notes when upgrading to Test2
* **<Test2::Util>** - Tools used by Test2 and friends.
* **<Test2::Util::ExternalMeta>** - Allow third party tools to safely attach meta-data
* **<Test2::Util::Facets2Legacy>** - Convert facet data to the legacy event API.
* **<Test2::Util::HashBase>** - Build hash based classes.
* **<Test2::Util::Trace>** - Legacy wrapper fro <Test2::EventFacet::Trace>.
* **<Test::Builder>** - Backend for building test libraries
* **<Test::Builder::Formatter>** - Test::Builder subclass of Test2::Formatter::TAP
* **<Test::Builder::IO::Scalar>** - A copy of IO::Scalar for Test::Builder
* **<Test::Builder::Module>** - Base class for test modules
* **<Test::Builder::Tester>** - Test testsuites that have been built with
* **<Test::Builder::Tester::Color>** - Turn on colour in Test::Builder::Tester
* **<Test::Builder::TodoDiag>** - Test::Builder subclass of Test2::Event::Diag
* **<Test::Harness>** - Run Perl standard test scripts with statistics
* **<Test::Harness::Beyond>** - Beyond make test
* **<Test::More>** - Yet another framework for writing test scripts
* **<Test::Simple>** - Basic utilities for writing tests.
* **<Test::Tester>** - Ease testing test modules built with Test::Builder
* **<Test::Tester::Capture>** - Help testing test modules built with Test::Builder
* **<Test::Tester::CaptureRunner>** - Help testing test modules built with Test::Builder
* **<Test::Tutorial>** - A tutorial about writing really basic tests
* **<Test::use::ok>** - Alternative to Test::More::use\_ok
* **<Text::Abbrev>** - Abbrev - create an abbreviation table from a list
* **<Text::Balanced>** - Extract delimited text sequences from strings.
* **<Text::ParseWords>** - Parse text into an array of tokens or array of arrays
* **<Text::Tabs>** - Expand and unexpand tabs like unix expand(1) and unexpand(1)
* **<Text::Wrap>** - Line wrapping to form simple paragraphs
* **[Thread](thread)** - Manipulate threads in Perl (for old code only)
* **<Thread::Queue>** - Thread-safe queues
* **<Thread::Semaphore>** - Thread-safe semaphores
* **<Tie::Array>** - Base class for tied arrays
* **<Tie::File>** - Access the lines of a disk file via a Perl array
* **<Tie::Handle>** - Base class definitions for tied handles
* **<Tie::Hash>** - Base class definitions for tied hashes
* **<Tie::Hash::NamedCapture>** - Named regexp capture buffers
* **<Tie::Memoize>** - Add data to hash when needed
* **<Tie::RefHash>** - Use references as hash keys
* **<Tie::Scalar>** - Base class definitions for tied scalars
* **<Tie::StdHandle>** - Base class definitions for tied handles
* **<Tie::SubstrHash>** - Fixed-table-size, fixed-key-length hashing
* **<Time::HiRes>** - High resolution alarm, sleep, gettimeofday, interval timers
* **<Time::Local>** - Efficiently compute time from local and GMT time
* **<Time::Piece>** - Object Oriented time objects
* **<Time::Seconds>** - A simple API to convert seconds to other date values
* **<Time::gmtime>** - By-name interface to Perl's built-in gmtime() function
* **<Time::localtime>** - By-name interface to Perl's built-in localtime() function
* **<Time::tm>** - Internal object used by Time::gmtime and Time::localtime
* **[UNIVERSAL](universal)** - Base class for ALL classes (blessed references)
* **<Unicode::Collate>** - Unicode Collation Algorithm
* **<Unicode::Collate::CJK::Big5>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::CJK::GB2312>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::CJK::JISX0208>** - Weighting JIS KANJI for Unicode::Collate
* **<Unicode::Collate::CJK::Korean>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::CJK::Pinyin>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::CJK::Stroke>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::CJK::Zhuyin>** - Weighting CJK Unified Ideographs
* **<Unicode::Collate::Locale>** - Linguistic tailoring for DUCET via Unicode::Collate
* **<Unicode::Normalize>** - Unicode Normalization Forms
* **<Unicode::UCD>** - Unicode character database
* **<User::grent>** - By-name interface to Perl's built-in getgr\*() functions
* **<User::pwent>** - By-name interface to Perl's built-in getpw\*() functions
* **<VMS::DCLsym>** - Perl extension to manipulate DCL symbols
* **<VMS::Filespec>** - Convert between VMS and Unix file specification syntax
* **<VMS::Stdio>** - Standard I/O functions via VMS extensions
* **[Win32](win32)** - Interfaces to some Win32 API Functions
* **<Win32API::File>** - Low-level access to Win32 system API calls for files/dirs.
* **[Win32CORE](win32core)** - Win32 CORE function stubs
* **<XS::APItest>** - Test the perl C API
* **<XS::Typemap>** - Module to test the XS typemaps distributed with perl
* **[XSLoader](xsloader)** - Dynamically load C libraries into Perl code
* **<autodie::Scope::Guard>** - Wrapper class for calling subs at end of scope
* **<autodie::Scope::GuardStack>** - Hook stack for managing scopes via %^H
* **<autodie::Util>** - Internal Utility subroutines for autodie and Fatal
* **<version::Internals>** - Perl extension for Version Objects
| programming_docs |
perl B::Terse B::Terse
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
NAME
----
B::Terse - Walk Perl syntax tree, printing terse info about ops
SYNOPSIS
--------
```
perl -MO=Terse[,OPTIONS] foo.pl
```
DESCRIPTION
-----------
This module prints the contents of the parse tree, but without as much information as CPAN module B::Debug. For comparison, `print "Hello, world."` produced 96 lines of output from B::Debug, but only 6 from B::Terse.
This module is useful for people who are writing their own back end, or who are learning about the Perl internals. It's not useful to the average programmer.
This version of B::Terse is really just a wrapper that calls <B::Concise> with the **-terse** option. It is provided for compatibility with old scripts (and habits) but using B::Concise directly is now recommended instead.
For compatibility with the old B::Terse, this module also adds a method named `terse` to B::OP and B::SV objects. The B::SV method is largely compatible with the old one, though authors of new software might be advised to choose a more user-friendly output format. The B::OP `terse` method, however, doesn't work well. Since B::Terse was first written, much more information in OPs has migrated to the scratchpad datastructure, but the `terse` interface doesn't have any way of getting to the correct pad. As a kludge, the new version will always use the pad for the main program, but for OPs in subroutines this will give the wrong answer or crash.
AUTHOR
------
The original version of B::Terse was written by Malcolm Beattie, <[email protected]>. This wrapper was written by Stephen McCamant, <[email protected]>.
perl autodie::Scope::GuardStack autodie::Scope::GuardStack
==========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods](#Methods)
- [new](#new)
- [push\_hook](#push_hook)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
autodie::Scope::GuardStack - Hook stack for managing scopes via %^H
SYNOPSIS
--------
```
use autodie::Scope::GuardStack;
my $stack = autodie::Scope::GuardStack->new
$^H{'my-key'} = $stack;
$stack->push_hook(sub {});
```
DESCRIPTION
-----------
This class is a stack of hooks to be called in the right order as scopes go away. The stack is only useful when inserted into `%^H` and will pop hooks as their "scope" is popped. This is useful for uninstalling or reinstalling subs in a namespace as a pragma goes out of scope.
Due to how `%^H` works, this class is only useful during the compilation phase of a perl module and relies on the internals of how perl handles references in `%^H`. This module is not a part of autodie's public API.
### Methods
#### new
```
my $stack = autodie::Scope::GuardStack->new;
```
Creates a new `autodie::Scope::GuardStack`. The stack is initially empty and must be inserted into `%^H` by the creator.
#### push\_hook
```
$stack->push_hook(sub {});
```
Add a sub to the stack. The sub will be called once the current compile-time "scope" is left. Multiple hooks can be added per scope
AUTHOR
------
Copyright 2013, Niels Thykier <[email protected]>
LICENSE
-------
This module is free software. You may distribute it under the same terms as Perl itself.
perl Unicode::Collate::CJK::GB2312 Unicode::Collate::CJK::GB2312
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::GB2312 - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::GB2312;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::GB2312::weightGB2312
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::GB2312` provides `weightGB2312()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's gb2312han ordering.
CAVEAT
------
The gb2312han ordering includes 5 code points in private use area (E2D8..E2DC), that can't utilize `weightGB2312()` for collation. For them, use `entry` instead.
SEE ALSO
---------
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
<Unicode::Collate>
<Unicode::Collate::Locale>
perl perlos2 perlos2
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Target](#Target)
+ [Other OSes](#Other-OSes)
+ [Prerequisites](#Prerequisites)
+ [Starting Perl programs under OS/2 (and DOS and...)](#Starting-Perl-programs-under-OS/2-(and-DOS-and...))
+ [Starting OS/2 (and DOS) programs under Perl](#Starting-OS/2-(and-DOS)-programs-under-Perl)
* [Frequently asked questions](#Frequently-asked-questions)
+ ["It does not work"](#%22It-does-not-work%22)
+ [I cannot run external programs](#I-cannot-run-external-programs)
+ [I cannot embed perl into my program, or use perl.dll from my program.](#I-cannot-embed-perl-into-my-program,-or-use-perl.dll-from-my-program.)
+ [`` and pipe-open do not work under DOS.](#%60%60-and-pipe-open-do-not-work-under-DOS.)
+ [Cannot start find.exe "pattern" file](#Cannot-start-find.exe-%22pattern%22-file)
* [INSTALLATION](#INSTALLATION)
+ [Automatic binary installation](#Automatic-binary-installation)
+ [Manual binary installation](#Manual-binary-installation)
+ [Warning](#Warning)
* [Accessing documentation](#Accessing-documentation)
+ [OS/2 .INF file](#OS/2-.INF-file)
+ [Plain text](#Plain-text)
+ [Manpages](#Manpages2)
+ [HTML](#HTML)
+ [GNU info files](#GNU-info-files)
+ [PDF files](#PDF-files)
+ [LaTeX docs](#LaTeX-docs)
* [BUILD](#BUILD)
+ [The short story](#The-short-story)
+ [Prerequisites](#Prerequisites1)
+ [Getting perl source](#Getting-perl-source)
+ [Application of the patches](#Application-of-the-patches)
+ [Hand-editing](#Hand-editing)
+ [Making](#Making)
+ [Testing](#Testing)
+ [Installing the built perl](#Installing-the-built-perl)
+ [a.out-style build](#a.out-style-build)
* [Building a binary distribution](#Building-a-binary-distribution)
* [Building custom .EXE files](#Building-custom-.EXE-files)
+ [Making executables with a custom collection of statically loaded extensions](#Making-executables-with-a-custom-collection-of-statically-loaded-extensions)
+ [Making executables with a custom search-paths](#Making-executables-with-a-custom-search-paths)
* [Build FAQ](#Build-FAQ)
+ [Some / became \ in pdksh.](#Some-/-became-%5C-in-pdksh.)
+ ['errno' - unresolved external](#'errno'-unresolved-external)
+ [Problems with tr or sed](#Problems-with-tr-or-sed)
+ [Some problem (forget which ;-)](#Some-problem-(forget-which-;-))
+ [Library ... not found](#Library-...-not-found)
+ [Segfault in make](#Segfault-in-make)
+ [op/sprintf test failure](#op/sprintf-test-failure)
* [Specific (mis)features of OS/2 port](#Specific-(mis)features-of-OS/2-port)
+ [setpriority, getpriority](#setpriority,-getpriority)
+ [system()](#system())
+ [extproc on the first line](#extproc-on-the-first-line)
+ [Additional modules:](#Additional-modules:)
+ [Prebuilt methods:](#Prebuilt-methods:)
+ [Prebuilt variables:](#Prebuilt-variables:)
+ [Misfeatures](#Misfeatures)
+ [Modifications](#Modifications)
+ [Identifying DLLs](#Identifying-DLLs)
+ [Centralized management of resources](#Centralized-management-of-resources)
* [Perl flavors](#Perl-flavors)
+ [perl.exe](#perl.exe)
+ [perl\_.exe](#perl_.exe)
+ [perl\_\_.exe](#perl__.exe)
+ [perl\_\_\_.exe](#perl___.exe)
+ [Why strange names?](#Why-strange-names?)
+ [Why dynamic linking?](#Why-dynamic-linking?)
+ [Why chimera build?](#Why-chimera-build?)
* [ENVIRONMENT](#ENVIRONMENT)
+ [PERLLIB\_PREFIX](#PERLLIB_PREFIX)
+ [PERL\_BADLANG](#PERL_BADLANG1)
+ [PERL\_BADFREE](#PERL_BADFREE1)
+ [PERL\_SH\_DIR](#PERL_SH_DIR)
+ [USE\_PERL\_FLOCK](#USE_PERL_FLOCK)
+ [TMP or TEMP](#TMP-or-TEMP)
* [Evolution](#Evolution)
+ [Text-mode filehandles](#Text-mode-filehandles)
+ [Priorities](#Priorities)
+ [DLL name mangling: pre 5.6.2](#DLL-name-mangling:-pre-5.6.2)
+ [DLL name mangling: 5.6.2 and beyond](#DLL-name-mangling:-5.6.2-and-beyond)
+ [DLL forwarder generation](#DLL-forwarder-generation)
+ [Threading](#Threading)
+ [Calls to external programs](#Calls-to-external-programs)
+ [Memory allocation](#Memory-allocation)
+ [Threads](#Threads)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlos2 - Perl under OS/2, DOS, Win0.3\*, Win0.95 and WinNT.
SYNOPSIS
--------
One can read this document in the following formats:
```
man perlos2
view perl perlos2
explorer perlos2.html
info perlos2
```
to list some (not all may be available simultaneously), or it may be read *as is*: either as *README.os2*, or *pod/perlos2.pod*.
To read the *.INF* version of documentation (**very** recommended) outside of OS/2, one needs an IBM's reader (may be available on IBM ftp sites (?) (URL anyone?)) or shipped with PC DOS 7.0 and IBM's Visual Age C++ 3.5.
A copy of a Win\* viewer is contained in the "Just add OS/2 Warp" package
```
ftp://ftp.software.ibm.com/ps/products/os2/tools/jaow/jaow.zip
```
in *?:\JUST\_ADD\view.exe*. This gives one an access to EMX's *.INF* docs as well (text form is available in */emx/doc* in EMX's distribution). There is also a different viewer named xview.
Note that if you have *lynx.exe* or *netscape.exe* installed, you can follow WWW links from this document in *.INF* format. If you have EMX docs installed correctly, you can follow library links (you need to have `view emxbook` working by setting `EMXBOOK` environment variable as it is described in EMX docs).
DESCRIPTION
-----------
### Target
The target is to make OS/2 one of the best supported platform for using/building/developing Perl and *Perl applications*, as well as make Perl the best language to use under OS/2. The secondary target is to try to make this work under DOS and Win\* as well (but not **too** hard).
The current state is quite close to this target. Known limitations:
* Some \*nix programs use fork() a lot; with the mostly useful flavors of perl for OS/2 (there are several built simultaneously) this is supported; but some flavors do not support this (e.g., when Perl is called from inside REXX). Using fork() after *use*ing dynamically loading extensions would not work with *very* old versions of EMX.
* You need a separate perl executable *perl\_\_.exe* (see ["perl\_\_.exe"](#perl__.exe)) if you want to use PM code in your application (as Perl/Tk or OpenGL Perl modules do) without having a text-mode window present.
While using the standard *perl.exe* from a text-mode window is possible too, I have seen cases when this causes degradation of the system stability. Using *perl\_\_.exe* avoids such a degradation.
* There is no simple way to access WPS objects. The only way I know is via `OS2::REXX` and `SOM` extensions (see <OS2::REXX>, [SOM](som)). However, we do not have access to convenience methods of Object-REXX. (Is it possible at all? I know of no Object-REXX API.) The `SOM` extension (currently in alpha-text) may eventually remove this shortcoming; however, due to the fact that DII is not supported by the `SOM` module, using `SOM` is not as convenient as one would like it.
Please keep this list up-to-date by informing me about other items.
###
Other OSes
Since OS/2 port of perl uses a remarkable EMX environment, it can run (and build extensions, and - possibly - be built itself) under any environment which can run EMX. The current list is DOS, DOS-inside-OS/2, Win0.3\*, Win0.95 and WinNT. Out of many perl flavors, only one works, see ["*perl\_.exe*"](#perl_.exe).
Note that not all features of Perl are available under these environments. This depends on the features the *extender* - most probably RSX - decided to implement.
Cf. ["Prerequisites"](#Prerequisites).
### Prerequisites
EMX EMX runtime is required (may be substituted by RSX). Note that it is possible to make *perl\_.exe* to run under DOS without any external support by binding *emx.exe*/*rsx.exe* to it, see [emxbind(1)](http://man.he.net/man1/emxbind). Note that under DOS for best results one should use RSX runtime, which has much more functions working (like `fork`, `popen` and so on). In fact RSX is required if there is no VCPI present. Note the RSX requires DPMI. Many implementations of DPMI are known to be very buggy, beware!
Only the latest runtime is supported, currently `0.9d fix 03`. Perl may run under earlier versions of EMX, but this is not tested.
One can get different parts of EMX from, say
```
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/
http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2/dev/emx/v0.9d/
```
The runtime component should have the name *emxrt.zip*.
**NOTE**. When using *emx.exe*/*rsx.exe*, it is enough to have them on your path. One does not need to specify them explicitly (though this
```
emx perl_.exe -de 0
```
will work as well.)
RSX To run Perl on DPMI platforms one needs RSX runtime. This is needed under DOS-inside-OS/2, Win0.3\*, Win0.95 and WinNT (see ["Other OSes"](#Other-OSes)). RSX would not work with VCPI only, as EMX would, it requires DMPI.
Having RSX and the latest *sh.exe* one gets a fully functional **\*nix**-ish environment under DOS, say, `fork`, ```` and pipe-`open` work. In fact, MakeMaker works (for static build), so one can have Perl development environment under DOS.
One can get RSX from, say
```
http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/contrib/
```
Contact the author on `[email protected]`.
The latest *sh.exe* with DOS hooks is available in
```
http://www.ilyaz.org/software/os2/
```
as *sh\_dos.zip* or under similar names starting with `sh`, `pdksh` etc.
HPFS Perl does not care about file systems, but the perl library contains many files with long names, so to install it intact one needs a file system which supports long file names.
Note that if you do not plan to build the perl itself, it may be possible to fool EMX to truncate file names. This is not supported, read EMX docs to see how to do it.
pdksh To start external programs with complicated command lines (like with pipes in between, and/or quoting of arguments), Perl uses an external shell. With EMX port such shell should be named *sh.exe*, and located either in the wired-in-during-compile locations (usually *F:/bin*), or in configurable location (see ["`PERL_SH_DIR`"](#PERL_SH_DIR)).
For best results use EMX pdksh. The standard binary (5.2.14 or later) runs under DOS (with ["RSX"](#RSX)) as well, see
```
http://www.ilyaz.org/software/os2/
```
###
Starting Perl programs under OS/2 (and DOS and...)
Start your Perl program *foo.pl* with arguments `arg1 arg2 arg3` the same way as on any other platform, by
```
perl foo.pl arg1 arg2 arg3
```
If you want to specify perl options `-my_opts` to the perl itself (as opposed to your program), use
```
perl -my_opts foo.pl arg1 arg2 arg3
```
Alternately, if you use OS/2-ish shell, like CMD or 4os2, put the following at the start of your perl script:
```
extproc perl -S -my_opts
```
rename your program to *foo.cmd*, and start it by typing
```
foo arg1 arg2 arg3
```
Note that because of stupid OS/2 limitations the full path of the perl script is not available when you use `extproc`, thus you are forced to use `-S` perl switch, and your script should be on the `PATH`. As a plus side, if you know a full path to your script, you may still start it with
```
perl ../../blah/foo.cmd arg1 arg2 arg3
```
(note that the argument `-my_opts` is taken care of by the `extproc` line in your script, see `["extproc"](#extproc)` on the first line).
To understand what the above *magic* does, read perl docs about `-S` switch - see <perlrun>, and cmdref about `extproc`:
```
view perl perlrun
man perlrun
view cmdref extproc
help extproc
```
or whatever method you prefer.
There are also endless possibilities to use *executable extensions* of 4os2, *associations* of WPS and so on... However, if you use \*nixish shell (like *sh.exe* supplied in the binary distribution), you need to follow the syntax specified in ["Command Switches" in perlrun](perlrun#Command-Switches).
Note that **-S** switch supports scripts with additional extensions *.cmd*, *.btm*, *.bat*, *.pl* as well.
###
Starting OS/2 (and DOS) programs under Perl
This is what system() (see ["system" in perlfunc](perlfunc#system)), ```` (see ["I/O Operators" in perlop](perlop#I%2FO-Operators)), and *open pipe* (see ["open" in perlfunc](perlfunc#open)) are for. (Avoid exec() (see ["exec" in perlfunc](perlfunc#exec)) unless you know what you do).
Note however that to use some of these operators you need to have a sh-syntax shell installed (see ["Pdksh"](#Pdksh), ["Frequently asked questions"](#Frequently-asked-questions)), and perl should be able to find it (see ["`PERL_SH_DIR`"](#PERL_SH_DIR)).
The cases when the shell is used are:
1. One-argument system() (see ["system" in perlfunc](perlfunc#system)), exec() (see ["exec" in perlfunc](perlfunc#exec)) with redirection or shell meta-characters;
2. Pipe-open (see ["open" in perlfunc](perlfunc#open)) with the command which contains redirection or shell meta-characters;
3. Backticks ```` (see ["I/O Operators" in perlop](perlop#I%2FO-Operators)) with the command which contains redirection or shell meta-characters;
4. If the executable called by system()/exec()/pipe-open()/```` is a script with the "magic" `#!` line or `extproc` line which specifies shell;
5. If the executable called by system()/exec()/pipe-open()/```` is a script without "magic" line, and `$ENV{EXECSHELL}` is set to shell;
6. If the executable called by system()/exec()/pipe-open()/```` is not found (is not this remark obsolete?);
7. For globbing (see ["glob" in perlfunc](perlfunc#glob), ["I/O Operators" in perlop](perlop#I%2FO-Operators)) (obsolete? Perl uses builtin globbing nowadays...).
For the sake of speed for a common case, in the above algorithms backslashes in the command name are not considered as shell metacharacters.
Perl starts scripts which begin with cookies `extproc` or `#!` directly, without an intervention of shell. Perl uses the same algorithm to find the executable as *pdksh*: if the path on `#!` line does not work, and contains `/`, then the directory part of the executable is ignored, and the executable is searched in *.* and on `PATH`. To find arguments for these scripts Perl uses a different algorithm than *pdksh*: up to 3 arguments are recognized, and trailing whitespace is stripped.
If a script does not contain such a cooky, then to avoid calling *sh.exe*, Perl uses the same algorithm as *pdksh*: if `$ENV{EXECSHELL}` is set, the script is given as the first argument to this command, if not set, then `$ENV{COMSPEC} /c` is used (or a hardwired guess if `$ENV{COMSPEC}` is not set).
When starting scripts directly, Perl uses exactly the same algorithm as for the search of script given by **-S** command-line option: it will look in the current directory, then on components of `$ENV{PATH}` using the following order of appended extensions: no extension, *.cmd*, *.btm*, *.bat*, *.pl*.
Note that Perl will start to look for scripts only if OS/2 cannot start the specified application, thus `system 'blah'` will not look for a script if there is an executable file *blah.exe* *anywhere* on `PATH`. In other words, `PATH` is essentially searched twice: once by the OS for an executable, then by Perl for scripts.
Note also that executable files on OS/2 can have an arbitrary extension, but *.exe* will be automatically appended if no dot is present in the name. The workaround is as simple as that: since *blah.* and *blah* denote the same file (at list on FAT and HPFS file systems), to start an executable residing in file *n:/bin/blah* (no extension) give an argument `n:/bin/blah.` (dot appended) to system().
Perl will start PM programs from VIO (=text-mode) Perl process in a separate PM session; the opposite is not true: when you start a non-PM program from a PM Perl process, Perl would not run it in a separate session. If a separate session is desired, either ensure that shell will be used, as in `system 'cmd /c myprog'`, or start it using optional arguments to system() documented in `OS2::Process` module. This is considered to be a feature.
Frequently asked questions
---------------------------
###
"It does not work"
Perl binary distributions come with a *testperl.cmd* script which tries to detect common problems with misconfigured installations. There is a pretty large chance it will discover which step of the installation you managed to goof. `;-)`
###
I cannot run external programs
* Did you run your programs with `-w` switch? See ["Starting OS/2 (and DOS) programs under Perl"](#Starting-OS%2F2-%28and-DOS%29-programs-under-Perl).
* Do you try to run *internal* shell commands, like ``copy a b`` (internal for *cmd.exe*), or ``glob a*b`` (internal for ksh)? You need to specify your shell explicitly, like ``cmd /c copy a b``, since Perl cannot deduce which commands are internal to your shell.
###
I cannot embed perl into my program, or use *perl.dll* from my program.
Is your program EMX-compiled with `-Zmt -Zcrtdll`? Well, nowadays Perl DLL should be usable from a differently compiled program too... If you can run Perl code from REXX scripts (see <OS2::REXX>), then there are some other aspect of interaction which are overlooked by the current hackish code to support differently-compiled principal programs.
If everything else fails, you need to build a stand-alone DLL for perl. Contact me, I did it once. Sockets would not work, as a lot of other stuff.
Did you use <ExtUtils::Embed>? Some time ago I had reports it does not work. Nowadays it is checked in the Perl test suite, so grep *./t* subdirectory of the build tree (as well as *\*.t* files in the *./lib* subdirectory) to find how it should be done "correctly".
###
```` and pipe-`open` do not work under DOS.
This may a variant of just ["I cannot run external programs"](#I-cannot-run-external-programs), or a deeper problem. Basically: you *need* RSX (see ["Prerequisites"](#Prerequisites)) for these commands to work, and you may need a port of *sh.exe* which understands command arguments. One of such ports is listed in ["Prerequisites"](#Prerequisites) under RSX. Do not forget to set variable ["`PERL_SH_DIR`"](#PERL_SH_DIR) as well.
DPMI is required for RSX.
###
Cannot start `find.exe "pattern" file`
The whole idea of the "standard C API to start applications" is that the forms `foo` and `"foo"` of program arguments are completely interchangeable. *find* breaks this paradigm;
```
find "pattern" file
find pattern file
```
are not equivalent; *find* cannot be started directly using the above API. One needs a way to surround the doublequotes in some other quoting construction, necessarily having an extra non-Unixish shell in between.
Use one of
```
system 'cmd', '/c', 'find "pattern" file';
`cmd /c 'find "pattern" file'`
```
This would start *find.exe* via *cmd.exe* via `sh.exe` via `perl.exe`, but this is a price to pay if you want to use non-conforming program.
INSTALLATION
------------
###
Automatic binary installation
The most convenient way of installing a binary distribution of perl is via perl installer *install.exe*. Just follow the instructions, and 99% of the installation blues would go away.
Note however, that you need to have *unzip.exe* on your path, and EMX environment *running*. The latter means that if you just installed EMX, and made all the needed changes to *Config.sys*, you may need to reboot in between. Check EMX runtime by running
```
emxrev
```
Binary installer also creates a folder on your desktop with some useful objects. If you need to change some aspects of the work of the binary installer, feel free to edit the file *Perl.pkg*. This may be useful e.g., if you need to run the installer many times and do not want to make many interactive changes in the GUI.
**Things not taken care of by automatic binary installation:**
`PERL_BADLANG` may be needed if you change your codepage *after* perl installation, and the new value is not supported by EMX. See ["`PERL_BADLANG`"](#PERL_BADLANG).
`PERL_BADFREE` see ["`PERL_BADFREE`"](#PERL_BADFREE).
*Config.pm*
This file resides somewhere deep in the location you installed your perl library, find it out by
```
perl -MConfig -le "print $INC{'Config.pm'}"
```
While most important values in this file *are* updated by the binary installer, some of them may need to be hand-edited. I know no such data, please keep me informed if you find one. Moreover, manual changes to the installed version may need to be accompanied by an edit of this file.
**NOTE**. Because of a typo the binary installer of 5.00305 would install a variable `PERL_SHPATH` into *Config.sys*. Please remove this variable and put `["PERL\_SH\_DIR"](#PERL_SH_DIR)` instead.
###
Manual binary installation
As of version 5.00305, OS/2 perl binary distribution comes split into 11 components. Unfortunately, to enable configurable binary installation, the file paths in the zip files are not absolute, but relative to some directory.
Note that the extraction with the stored paths is still necessary (default with unzip, specify `-d` to pkunzip). However, you need to know where to extract the files. You need also to manually change entries in *Config.sys* to reflect where did you put the files. Note that if you have some primitive unzipper (like `pkunzip`), you may get a lot of warnings/errors during unzipping. Upgrade to `(w)unzip`.
Below is the sample of what to do to reproduce the configuration on my machine. In *VIEW.EXE* you can press `Ctrl-Insert` now, and cut-and-paste from the resulting file - created in the directory you started *VIEW.EXE* from.
For each component, we mention environment variables related to each installation directory. Either choose directories to match your values of the variables, or create/append-to variables to take into account the directories.
Perl VIO and PM executables (dynamically linked)
```
unzip perl_exc.zip *.exe *.ico -d f:/emx.add/bin
unzip perl_exc.zip *.dll -d f:/emx.add/dll
```
(have the directories with `*.exe` on PATH, and `*.dll` on LIBPATH);
Perl\_ VIO executable (statically linked)
```
unzip perl_aou.zip -d f:/emx.add/bin
```
(have the directory on PATH);
Executables for Perl utilities
```
unzip perl_utl.zip -d f:/emx.add/bin
```
(have the directory on PATH);
Main Perl library
```
unzip perl_mlb.zip -d f:/perllib/lib
```
If this directory is exactly the same as the prefix which was compiled into *perl.exe*, you do not need to change anything. However, for perl to find the library if you use a different path, you need to `set PERLLIB_PREFIX` in *Config.sys*, see ["`PERLLIB_PREFIX`"](#PERLLIB_PREFIX).
Additional Perl modules
```
unzip perl_ste.zip -d f:/perllib/lib/site_perl/5.36.0/
```
Same remark as above applies. Additionally, if this directory is not one of directories on @INC (and @INC is influenced by `PERLLIB_PREFIX`), you need to put this directory and subdirectory *./os2* in `PERLLIB` or `PERL5LIB` variable. Do not use `PERL5LIB` unless you have it set already. See ["ENVIRONMENT" in perl](perl#ENVIRONMENT).
**[Check whether this extraction directory is still applicable with the new directory structure layout!]**
Tools to compile Perl modules
```
unzip perl_blb.zip -d f:/perllib/lib
```
Same remark as for *perl\_ste.zip*.
Manpages for Perl and utilities
```
unzip perl_man.zip -d f:/perllib/man
```
This directory should better be on `MANPATH`. You need to have a working *man* to access these files.
Manpages for Perl modules
```
unzip perl_mam.zip -d f:/perllib/man
```
This directory should better be on `MANPATH`. You need to have a working man to access these files.
Source for Perl documentation
```
unzip perl_pod.zip -d f:/perllib/lib
```
This is used by the `perldoc` program (see <perldoc>), and may be used to generate HTML documentation usable by WWW browsers, and documentation in zillions of other formats: `info`, `LaTeX`, `Acrobat`, `FrameMaker` and so on. [Use programs such as *pod2latex* etc.]
Perl manual in *.INF* format
```
unzip perl_inf.zip -d d:/os2/book
```
This directory should better be on `BOOKSHELF`.
Pdksh
```
unzip perl_sh.zip -d f:/bin
```
This is used by perl to run external commands which explicitly require shell, like the commands using *redirection* and *shell metacharacters*. It is also used instead of explicit */bin/sh*.
Set `PERL_SH_DIR` (see ["`PERL_SH_DIR`"](#PERL_SH_DIR)) if you move *sh.exe* from the above location.
**Note.** It may be possible to use some other sh-compatible shell (untested).
After you installed the components you needed and updated the *Config.sys* correspondingly, you need to hand-edit *Config.pm*. This file resides somewhere deep in the location you installed your perl library, find it out by
```
perl -MConfig -le "print $INC{'Config.pm'}"
```
You need to correct all the entries which look like file paths (they currently start with `f:/`).
### **Warning**
The automatic and manual perl installation leave precompiled paths inside perl executables. While these paths are overwritable (see ["`PERLLIB_PREFIX`"](#PERLLIB_PREFIX), ["`PERL_SH_DIR`"](#PERL_SH_DIR)), some people may prefer binary editing of paths inside the executables/DLLs.
Accessing documentation
------------------------
Depending on how you built/installed perl you may have (otherwise identical) Perl documentation in the following formats:
###
OS/2 *.INF* file
Most probably the most convenient form. Under OS/2 view it as
```
view perl
view perl perlfunc
view perl less
view perl ExtUtils::MakeMaker
```
(currently the last two may hit a wrong location, but this may improve soon). Under Win\* see ["SYNOPSIS"](#SYNOPSIS).
If you want to build the docs yourself, and have *OS/2 toolkit*, run
```
pod2ipf > perl.ipf
```
in */perllib/lib/pod* directory, then
```
ipfc /inf perl.ipf
```
(Expect a lot of errors during the both steps.) Now move it on your BOOKSHELF path.
###
Plain text
If you have perl documentation in the source form, perl utilities installed, and GNU groff installed, you may use
```
perldoc perlfunc
perldoc less
perldoc ExtUtils::MakeMaker
```
to access the perl documentation in the text form (note that you may get better results using perl manpages).
Alternately, try running pod2text on *.pod* files.
### Manpages
If you have *man* installed on your system, and you installed perl manpages, use something like this:
```
man perlfunc
man 3 less
man ExtUtils.MakeMaker
```
to access documentation for different components of Perl. Start with
```
man perl
```
Note that dot (*.*) is used as a package separator for documentation for packages, and as usual, sometimes you need to give the section - `3` above - to avoid shadowing by the *less(1) manpage*.
Make sure that the directory **above** the directory with manpages is on our `MANPATH`, like this
```
set MANPATH=c:/man;f:/perllib/man
```
for Perl manpages in `f:/perllib/man/man1/` etc.
### HTML
If you have some WWW browser available, installed the Perl documentation in the source form, and Perl utilities, you can build HTML docs. Cd to directory with *.pod* files, and do like this
```
cd f:/perllib/lib/pod
pod2html
```
After this you can direct your browser the file *perl.html* in this directory, and go ahead with reading docs, like this:
```
explore file:///f:/perllib/lib/pod/perl.html
```
Alternatively you may be able to get these docs prebuilt from CPAN.
###
GNU `info` files
Users of Emacs would appreciate it very much, especially with `CPerl` mode loaded. You need to get latest `pod2texi` from `CPAN`, or, alternately, the prebuilt info pages.
###
*PDF* files
for `Acrobat` are available on CPAN (may be for slightly older version of perl).
###
`LaTeX` docs
can be constructed using `pod2latex`.
BUILD
-----
Here we discuss how to build Perl under OS/2.
###
The short story
Assume that you are a seasoned porter, so are sure that all the necessary tools are already present on your system, and you know how to get the Perl source distribution. Untar it, change to the extract directory, and
```
gnupatch -p0 < os2\diff.configure
sh Configure -des -D prefix=f:/perllib
make
make test
make install
make aout_test
make aout_install
```
This puts the executables in f:/perllib/bin. Manually move them to the `PATH`, manually move the built *perl\*.dll* to `LIBPATH` (here for Perl DLL *\** is a not-very-meaningful hex checksum), and run
```
make installcmd INSTALLCMDDIR=d:/ir/on/path
```
Assuming that the `man`-files were put on an appropriate location, this completes the installation of minimal Perl system. (The binary distribution contains also a lot of additional modules, and the documentation in INF format.)
What follows is a detailed guide through these steps.
### Prerequisites
You need to have the latest EMX development environment, the full GNU tool suite (gawk renamed to awk, and GNU *find.exe* earlier on path than the OS/2 *find.exe*, same with *sort.exe*, to check use
```
find --version
sort --version
```
). You need the latest version of *pdksh* installed as *sh.exe*.
Check that you have **BSD** libraries and headers installed, and - optionally - Berkeley DB headers and libraries, and crypt.
Possible locations to get the files:
```
ftp://ftp.uni-heidelberg.de/pub/os2/unix/
http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2
http://cd.textfiles.com/hobbesos29804/disk1/DEV32/
http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/
```
It is reported that the following archives contain enough utils to build perl: *gnufutil.zip*, *gnusutil.zip*, *gnututil.zip*, *gnused.zip*, *gnupatch.zip*, *gnuawk.zip*, *gnumake.zip*, *gnugrep.zip*, *bsddev.zip* and *ksh527rt.zip* (or a later version). Note that all these utilities are known to be available from LEO:
```
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/
```
Note also that the *db.lib* and *db.a* from the EMX distribution are not suitable for multi-threaded compile (even single-threaded flavor of Perl uses multi-threaded C RTL, for compatibility with XFree86-OS/2). Get a corrected one from
```
http://www.ilyaz.org/software/os2/db_mt.zip
```
If you have *exactly the same version of Perl* installed already, make sure that no copies or perl are currently running. Later steps of the build may fail since an older version of *perl.dll* loaded into memory may be found. Running `make test` becomes meaningless, since the test are checking a previous build of perl (this situation is detected and reported by *os2/os2\_base.t* test). Do not forget to unset `PERL_EMXLOAD_SEC` in environment.
Also make sure that you have */tmp* directory on the current drive, and *.* directory in your `LIBPATH`. One may try to correct the latter condition by
```
set BEGINLIBPATH .\.
```
if you use something like *CMD.EXE* or latest versions of *4os2.exe*. (Setting BEGINLIBPATH to just `.` is ignored by the OS/2 kernel.)
Make sure your gcc is good for `-Zomf` linking: run `omflibs` script in */emx/lib* directory.
Check that you have link386 installed. It comes standard with OS/2, but may be not installed due to customization. If typing
```
link386
```
shows you do not have it, do *Selective install*, and choose `Link object modules` in *Optional system utilities/More*. If you get into link386 prompts, press `Ctrl-C` to exit.
###
Getting perl source
You need to fetch the latest perl source (including developers releases). With some probability it is located in
```
http://www.cpan.org/src/
http://www.cpan.org/src/unsupported
```
If not, you may need to dig in the indices to find it in the directory of the current maintainer.
Quick cycle of developers release may break the OS/2 build time to time, looking into
```
http://www.cpan.org/ports/os2/
```
may indicate the latest release which was publicly released by the maintainer. Note that the release may include some additional patches to apply to the current source of perl.
Extract it like this
```
tar vzxf perl5.00409.tar.gz
```
You may see a message about errors while extracting *Configure*. This is because there is a conflict with a similarly-named file *configure*.
Change to the directory of extraction.
###
Application of the patches
You need to apply the patches in *./os2/diff.\** like this:
```
gnupatch -p0 < os2\diff.configure
```
You may also need to apply the patches supplied with the binary distribution of perl. It also makes sense to look on the perl5-porters mailing list for the latest OS/2-related patches (see <http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/>). Such patches usually contain strings `/os2/` and `patch`, so it makes sense looking for these strings.
###
Hand-editing
You may look into the file *./hints/os2.sh* and correct anything wrong you find there. I do not expect it is needed anywhere.
### Making
```
sh Configure -des -D prefix=f:/perllib
```
`prefix` means: where to install the resulting perl library. Giving correct prefix you may avoid the need to specify `PERLLIB_PREFIX`, see ["`PERLLIB_PREFIX`"](#PERLLIB_PREFIX).
*Ignore the message about missing `ln`, and about `-c` option to tr*. The latter is most probably already fixed, if you see it and can trace where the latter spurious warning comes from, please inform me.
Now
```
make
```
At some moment the built may die, reporting a *version mismatch* or *unable to run *perl**. This means that you do not have *.* in your LIBPATH, so *perl.exe* cannot find the needed *perl67B2.dll* (treat these hex digits as line noise). After this is fixed the build should finish without a lot of fuss.
### Testing
Now run
```
make test
```
All tests should succeed (with some of them skipped). If you have the same version of Perl installed, it is crucial that you have `.` early in your LIBPATH (or in BEGINLIBPATH), otherwise your tests will most probably test the wrong version of Perl.
Some tests may generate extra messages similar to
A lot of `bad free`
in database tests related to Berkeley DB. *This should be fixed already.* If it persists, you may disable this warnings, see ["`PERL_BADFREE`"](#PERL_BADFREE).
Process terminated by SIGTERM/SIGINT This is a standard message issued by OS/2 applications. \*nix applications die in silence. It is considered to be a feature. One can easily disable this by appropriate sighandlers.
However the test engine bleeds these message to screen in unexpected moments. Two messages of this kind *should* be present during testing.
To get finer test reports, call
```
perl t/harness
```
The report with *io/pipe.t* failing may look like this:
```
Failed Test Status Wstat Total Fail Failed List of failed
------------------------------------------------------------
io/pipe.t 12 1 8.33% 9
7 tests skipped, plus 56 subtests skipped.
Failed 1/195 test scripts, 99.49% okay. 1/6542 subtests failed,
99.98% okay.
```
The reasons for most important skipped tests are:
*op/fs.t*
18 Checks `atime` and `mtime` of `stat()` - unfortunately, HPFS provides only 2sec time granularity (for compatibility with FAT?).
25 Checks `truncate()` on a filehandle just opened for write - I do not know why this should or should not work.
*op/stat.t*
Checks `stat()`. Tests:
4 Checks `atime` and `mtime` of `stat()` - unfortunately, HPFS provides only 2sec time granularity (for compatibility with FAT?).
###
Installing the built perl
If you haven't yet moved `perl*.dll` onto LIBPATH, do it now.
Run
```
make install
```
It would put the generated files into needed locations. Manually put *perl.exe*, *perl\_\_.exe* and *perl\_\_\_.exe* to a location on your PATH, *perl.dll* to a location on your LIBPATH.
Run
```
make installcmd INSTALLCMDDIR=d:/ir/on/path
```
to convert perl utilities to *.cmd* files and put them on PATH. You need to put *.EXE*-utilities on path manually. They are installed in `$prefix/bin`, here `$prefix` is what you gave to *Configure*, see ["Making"](#Making).
If you use `man`, either move the installed *\*/man/* directories to your `MANPATH`, or modify `MANPATH` to match the location. (One could have avoided this by providing a correct `manpath` option to *./Configure*, or editing *./config.sh* between configuring and making steps.)
###
`a.out`-style build
Proceed as above, but make *perl\_.exe* (see ["*perl\_.exe*"](#perl_.exe)) by
```
make perl_
```
test and install by
```
make aout_test
make aout_install
```
Manually put *perl\_.exe* to a location on your PATH.
**Note.** The build process for `perl_` *does not know* about all the dependencies, so you should make sure that anything is up-to-date, say, by doing
```
make perl_dll
```
first.
Building a binary distribution
-------------------------------
[This section provides a short overview only...]
Building should proceed differently depending on whether the version of perl you install is already present and used on your system, or is a new version not yet used. The description below assumes that the version is new, so installing its DLLs and *.pm* files will not disrupt the operation of your system even if some intermediate steps are not yet fully working.
The other cases require a little bit more convoluted procedures. Below I suppose that the current version of Perl is `5.8.2`, so the executables are named accordingly.
1. Fully build and test the Perl distribution. Make sure that no tests are failing with `test` and `aout_test` targets; fix the bugs in Perl and the Perl test suite detected by these tests. Make sure that `all_test` make target runs as clean as possible. Check that *os2/perlrexx.cmd* runs fine.
2. Fully install Perl, including `installcmd` target. Copy the generated DLLs to `LIBPATH`; copy the numbered Perl executables (as in *perl5.8.2.exe*) to `PATH`; copy `perl_.exe` to `PATH` as `perl_5.8.2.exe`. Think whether you need backward-compatibility DLLs. In most cases you do not need to install them yet; but sometime this may simplify the following steps.
3. Make sure that `CPAN.pm` can download files from CPAN. If not, you may need to manually install `Net::FTP`.
4. Install the bundle `Bundle::OS2_default`
```
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_1
```
This may take a couple of hours on 1GHz processor (when run the first time). And this should not be necessarily a smooth procedure. Some modules may not specify required dependencies, so one may need to repeat this procedure several times until the results stabilize.
```
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_2
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_3
```
Even after they stabilize, some tests may fail.
Fix as many discovered bugs as possible. Document all the bugs which are not fixed, and all the failures with unknown reasons. Inspect the produced logs *00cpan\_i\_1* to find suspiciously skipped tests, and other fishy events.
Keep in mind that *installation* of some modules may fail too: for example, the DLLs to update may be already loaded by *CPAN.pm*. Inspect the `install` logs (in the example above *00cpan\_i\_1* etc) for errors, and install things manually, as in
```
cd $CPANHOME/.cpan/build/Digest-MD5-2.31
make install
```
Some distributions may fail some tests, but you may want to install them anyway (as above, or via `force install` command of `CPAN.pm` shell-mode).
Since this procedure may take quite a long time to complete, it makes sense to "freeze" your CPAN configuration by disabling periodic updates of the local copy of CPAN index: set `index_expire` to some big value (I use 365), then save the settings
```
CPAN> o conf index_expire 365
CPAN> o conf commit
```
Reset back to the default value `1` when you are finished.
5. When satisfied with the results, rerun the `installcmd` target. Now you can copy `perl5.8.2.exe` to `perl.exe`, and install the other OMF-build executables: `perl__.exe` etc. They are ready to be used.
6. Change to the `./pod` directory of the build tree, download the Perl logo *CamelGrayBig.BMP*, and run
```
( perl2ipf > perl.ipf ) |& tee 00ipf
ipfc /INF perl.ipf |& tee 00inf
```
This produces the Perl docs online book `perl.INF`. Install in on `BOOKSHELF` path.
7. Now is the time to build statically linked executable *perl\_.exe* which includes newly-installed via `Bundle::OS2_default` modules. Doing testing via `CPAN.pm` is going to be painfully slow, since it statically links a new executable per XS extension.
Here is a possible workaround: create a toplevel *Makefile.PL* in *$CPANHOME/.cpan/build/* with contents being (compare with ["Making executables with a custom collection of statically loaded extensions"](#Making-executables-with-a-custom-collection-of-statically-loaded-extensions))
```
use ExtUtils::MakeMaker;
WriteMakefile NAME => 'dummy';
```
execute this as
```
perl_5.8.2.exe Makefile.PL <nul |& tee 00aout_c1
make -k all test <nul |& 00aout_t1
```
Again, this procedure should not be absolutely smooth. Some `Makefile.PL`'s in subdirectories may be buggy, and would not run as "child" scripts. The interdependency of modules can strike you; however, since non-XS modules are already installed, the prerequisites of most modules have a very good chance to be present.
If you discover some glitches, move directories of problematic modules to a different location; if these modules are non-XS modules, you may just ignore them - they are already installed; the remaining, XS, modules you need to install manually one by one.
After each such removal you need to rerun the `Makefile.PL`/`make` process; usually this procedure converges soon. (But be sure to convert all the necessary external C libraries from *.lib* format to *.a* format: run one of
```
emxaout foo.lib
emximp -o foo.a foo.lib
```
whichever is appropriate.) Also, make sure that the DLLs for external libraries are usable with executables compiled without `-Zmtd` options.
When you are sure that only a few subdirectories lead to failures, you may want to add `-j4` option to `make` to speed up skipping subdirectories with already finished build.
When you are satisfied with the results of tests, install the build C libraries for extensions:
```
make install |& tee 00aout_i
```
Now you can rename the file *./perl.exe* generated during the last phase to *perl\_5.8.2.exe*; place it on `PATH`; if there is an inter-dependency between some XS modules, you may need to repeat the `test`/`install` loop with this new executable and some excluded modules - until the procedure converges.
Now you have all the necessary *.a* libraries for these Perl modules in the places where Perl builder can find it. Use the perl builder: change to an empty directory, create a "dummy" *Makefile.PL* again, and run
```
perl_5.8.2.exe Makefile.PL |& tee 00c
make perl |& tee 00p
```
This should create an executable *./perl.exe* with all the statically loaded extensions built in. Compare the generated *perlmain.c* files to make sure that during the iterations the number of loaded extensions only increases. Rename *./perl.exe* to *perl\_5.8.2.exe* on `PATH`.
When it converges, you got a functional variant of *perl\_5.8.2.exe*; copy it to `perl_.exe`. You are done with generation of the local Perl installation.
8. Make sure that the installed modules are actually installed in the location of the new Perl, and are not inherited from entries of @INC given for inheritance from the older versions of Perl: set `PERLLIB_582_PREFIX` to redirect the new version of Perl to a new location, and copy the installed files to this new location. Redo the tests to make sure that the versions of modules inherited from older versions of Perl are not needed.
Actually, the log output of [pod2ipf(1)](http://man.he.net/man1/pod2ipf) during the step 6 gives a very detailed info about which modules are loaded from which place; so you may use it as an additional verification tool.
Check that some temporary files did not make into the perl install tree. Run something like this
```
pfind . -f "!(/\.(pm|pl|ix|al|h|a|lib|txt|pod|imp|bs|dll|ld|bs|inc|xbm|yml|cgi|uu|e2x|skip|packlist|eg|cfg|html|pub|enc|all|ini|po|pot)$/i or /^\w+$/") | less
```
in the install tree (both top one and *sitelib* one).
Compress all the DLLs with *lxlite*. The tiny *.exe* can be compressed with `/c:max` (the bug only appears when there is a fixup in the last 6 bytes of a page (?); since the tiny executables are much smaller than a page, the bug will not hit). Do not compress `perl_.exe` - it would not work under DOS.
9. Now you can generate the binary distribution. This is done by running the test of the CPAN distribution `OS2::SoftInstaller`. Tune up the file *test.pl* to suit the layout of current version of Perl first. Do not forget to pack the necessary external DLLs accordingly. Include the description of the bugs and test suite failures you could not fix. Include the small-stack versions of Perl executables from Perl build directory.
Include *perl5.def* so that people can relink the perl DLL preserving the binary compatibility, or can create compatibility DLLs. Include the diff files (`diff -pu old new`) of fixes you did so that people can rebuild your version. Include *perl5.map* so that one can use remote debugging.
10. Share what you did with the other people. Relax. Enjoy fruits of your work.
11. Brace yourself for thanks, bug reports, hate mail and spam coming as result of the previous step. No good deed should remain unpunished!
Building custom *.EXE* files
-----------------------------
The Perl executables can be easily rebuilt at any moment. Moreover, one can use the *embedding* interface (see <perlembed>) to make very customized executables.
###
Making executables with a custom collection of statically loaded extensions
It is a little bit easier to do so while *decreasing* the list of statically loaded extensions. We discuss this case only here.
1. Change to an empty directory, and create a placeholder <Makefile.PL>:
```
use ExtUtils::MakeMaker;
WriteMakefile NAME => 'dummy';
```
2. Run it with the flavor of Perl (*perl.exe* or *perl\_.exe*) you want to rebuild.
```
perl_ Makefile.PL
```
3. Ask it to create new Perl executable:
```
make perl
```
(you may need to manually add `PERLTYPE=-DPERL_CORE` to this commandline on some versions of Perl; the symptom is that the command-line globbing does not work from OS/2 shells with the newly-compiled executable; check with
```
.\perl.exe -wle "print for @ARGV" *
```
).
4. The previous step created *perlmain.c* which contains a list of newXS() calls near the end. Removing unnecessary calls, and rerunning
```
make perl
```
will produce a customized executable.
###
Making executables with a custom search-paths
The default perl executable is flexible enough to support most usages. However, one may want something yet more flexible; for example, one may want to find Perl DLL relatively to the location of the EXE file; or one may want to ignore the environment when setting the Perl-library search patch, etc.
If you fill comfortable with *embedding* interface (see <perlembed>), such things are easy to do repeating the steps outlined in ["Making executables with a custom collection of statically loaded extensions"](#Making-executables-with-a-custom-collection-of-statically-loaded-extensions), and doing more comprehensive edits to main() of *perlmain.c*. The people with little desire to understand Perl can just rename main(), and do necessary modification in a custom main() which calls the renamed function in appropriate time.
However, there is a third way: perl DLL exports the main() function and several callbacks to customize the search path. Below is a complete example of a "Perl loader" which
1. Looks for Perl DLL in the directory `$exedir/../dll`;
2. Prepends the above directory to `BEGINLIBPATH`;
3. Fails if the Perl DLL found via `BEGINLIBPATH` is different from what was loaded on step 1; e.g., another process could have loaded it from `LIBPATH` or from a different value of `BEGINLIBPATH`. In these cases one needs to modify the setting of the system so that this other process either does not run, or loads the DLL from `BEGINLIBPATH` with `LIBPATHSTRICT=T` (available with kernels after September 2000).
4. Loads Perl library from `$exedir/../dll/lib/`.
5. Uses Bourne shell from `$exedir/../dll/sh/ksh.exe`.
For best results compile the C file below with the same options as the Perl DLL. However, a lot of functionality will work even if the executable is not an EMX applications, e.g., if compiled with
```
gcc -Wall -DDOSISH -DOS2=1 -O2 -s -Zomf -Zsys perl-starter.c \
-DPERL_DLL_BASENAME=\"perl312F\" -Zstack 8192 -Zlinker /PM:VIO
```
Here is the sample C file:
```
#define INCL_DOS
#define INCL_NOPM
/* These are needed for compile if os2.h includes os2tk.h, not
* os2emx.h */
#define INCL_DOSPROCESS
#include <os2.h>
#include "EXTERN.h"
#define PERL_IN_MINIPERLMAIN_C
#include "perl.h"
static char *me;
HMODULE handle;
static void
die_with(char *msg1, char *msg2, char *msg3, char *msg4)
{
ULONG c;
char *s = " error: ";
DosWrite(2, me, strlen(me), &c);
DosWrite(2, s, strlen(s), &c);
DosWrite(2, msg1, strlen(msg1), &c);
DosWrite(2, msg2, strlen(msg2), &c);
DosWrite(2, msg3, strlen(msg3), &c);
DosWrite(2, msg4, strlen(msg4), &c);
DosWrite(2, "\r\n", 2, &c);
exit(255);
}
typedef ULONG (*fill_extLibpath_t)(int type,
char *pre,
char *post,
int replace,
char *msg);
typedef int (*main_t)(int type, char *argv[], char *env[]);
typedef int (*handler_t)(void* data, int which);
#ifndef PERL_DLL_BASENAME
# define PERL_DLL_BASENAME "perl"
#endif
static HMODULE
load_perl_dll(char *basename)
{
char buf[300], fail[260];
STRLEN l, dirl;
fill_extLibpath_t f;
ULONG rc_fullname;
HMODULE handle, handle1;
if (_execname(buf, sizeof(buf) - 13) != 0)
die_with("Can't find full path: ", strerror(errno), "", "");
/* XXXX Fill 'me' with new value */
l = strlen(buf);
while (l && buf[l-1] != '/' && buf[l-1] != '\\')
l--;
dirl = l - 1;
strcpy(buf + l, basename);
l += strlen(basename);
strcpy(buf + l, ".dll");
if ( (rc_fullname = DosLoadModule(fail, sizeof fail, buf, &handle))
!= 0
&& DosLoadModule(fail, sizeof fail, basename, &handle) != 0 )
die_with("Can't load DLL ", buf, "", "");
if (rc_fullname)
return handle; /* was loaded with short name; all is fine */
if (DosQueryProcAddr(handle, 0, "fill_extLibpath", (PFN*)&f))
die_with(buf,
": DLL exports no symbol ",
"fill_extLibpath",
"");
buf[dirl] = 0;
if (f(0 /*BEGINLIBPATH*/, buf /* prepend */, NULL /* append */,
0 /* keep old value */, me))
die_with(me, ": prepending BEGINLIBPATH", "", "");
if (DosLoadModule(fail, sizeof fail, basename, &handle1) != 0)
die_with(me,
": finding perl DLL again via BEGINLIBPATH",
"",
"");
buf[dirl] = '\\';
if (handle1 != handle) {
if (DosQueryModuleName(handle1, sizeof(fail), fail))
strcpy(fail, "???");
die_with(buf,
":\n\tperl DLL via BEGINLIBPATH is different: \n\t",
fail,
"\n\tYou may need to manipulate global BEGINLIBPATH"
" and LIBPATHSTRICT"
"\n\tso that the other copy is loaded via"
BEGINLIBPATH.");
}
return handle;
}
int
main(int argc, char **argv, char **env)
{
main_t f;
handler_t h;
me = argv[0];
/**/
handle = load_perl_dll(PERL_DLL_BASENAME);
if (DosQueryProcAddr(handle,
0,
"Perl_OS2_handler_install",
(PFN*)&h))
die_with(PERL_DLL_BASENAME,
": DLL exports no symbol ",
"Perl_OS2_handler_install",
"");
if ( !h((void *)"~installprefix", Perlos2_handler_perllib_from)
|| !h((void *)"~dll", Perlos2_handler_perllib_to)
|| !h((void *)"~dll/sh/ksh.exe", Perlos2_handler_perl_sh) )
die_with(PERL_DLL_BASENAME,
": Can't install @INC manglers",
"",
"");
if (DosQueryProcAddr(handle, 0, "dll_perlmain", (PFN*)&f))
die_with(PERL_DLL_BASENAME,
": DLL exports no symbol ",
"dll_perlmain",
"");
return f(argc, argv, env);
}
```
Build FAQ
----------
###
Some `/` became `\` in pdksh.
You have a very old pdksh. See ["Prerequisites"](#Prerequisites).
###
`'errno'` - unresolved external
You do not have MT-safe *db.lib*. See ["Prerequisites"](#Prerequisites).
###
Problems with tr or sed
reported with very old version of tr and sed.
###
Some problem (forget which ;-)
You have an older version of *perl.dll* on your LIBPATH, which broke the build of extensions.
###
Library ... not found
You did not run `omflibs`. See ["Prerequisites"](#Prerequisites).
###
Segfault in make
You use an old version of GNU make. See ["Prerequisites"](#Prerequisites).
###
op/sprintf test failure
This can result from a bug in emx sprintf which was fixed in 0.9d fix 03.
Specific (mis)features of OS/2 port
------------------------------------
###
`setpriority`, `getpriority`
Note that these functions are compatible with \*nix, not with the older ports of '94 - 95. The priorities are absolute, go from 32 to -95, lower is quicker. 0 is the default priority.
**WARNING**. Calling `getpriority` on a non-existing process could lock the system before Warp3 fixpak22. Starting with Warp3, Perl will use a workaround: it aborts getpriority() if the process is not present. This is not possible on older versions `2.*`, and has a race condition anyway.
###
`system()`
Multi-argument form of `system()` allows an additional numeric argument. The meaning of this argument is described in <OS2::Process>.
When finding a program to run, Perl first asks the OS to look for executables on `PATH` (OS/2 adds extension *.exe* if no extension is present). If not found, it looks for a script with possible extensions added in this order: no extension, *.cmd*, *.btm*, *.bat*, *.pl*. If found, Perl checks the start of the file for magic strings `"#!"` and `"extproc "`. If found, Perl uses the rest of the first line as the beginning of the command line to run this script. The only mangling done to the first line is extraction of arguments (currently up to 3), and ignoring of the path-part of the "interpreter" name if it can't be found using the full path.
E.g., `system 'foo', 'bar', 'baz'` may lead Perl to finding *C:/emx/bin/foo.cmd* with the first line being
```
extproc /bin/bash -x -c
```
If */bin/bash.exe* is not found, then Perl looks for an executable *bash.exe* on `PATH`. If found in *C:/emx.add/bin/bash.exe*, then the above system() is translated to
```
system qw(C:/emx.add/bin/bash.exe -x -c C:/emx/bin/foo.cmd bar baz)
```
One additional translation is performed: instead of */bin/sh* Perl uses the hardwired-or-customized shell (see ["`PERL_SH_DIR`"](#PERL_SH_DIR)).
The above search for "interpreter" is recursive: if *bash* executable is not found, but *bash.btm* is found, Perl will investigate its first line etc. The only hardwired limit on the recursion depth is implicit: there is a limit 4 on the number of additional arguments inserted before the actual arguments given to system(). In particular, if no additional arguments are specified on the "magic" first lines, then the limit on the depth is 4.
If Perl finds that the found executable is of PM type when the current session is not, it will start the new process in a separate session of necessary type. Call via `OS2::Process` to disable this magic.
**WARNING**. Due to the described logic, you need to explicitly specify *.com* extension if needed. Moreover, if the executable *perl5.6.1* is requested, Perl will not look for *perl5.6.1.exe*. [This may change in the future.]
###
`extproc` on the first line
If the first chars of a Perl script are `"extproc "`, this line is treated as `#!`-line, thus all the switches on this line are processed (twice if script was started via cmd.exe). See ["DESCRIPTION" in perlrun](perlrun#DESCRIPTION).
###
Additional modules:
<OS2::Process>, <OS2::DLL>, <OS2::REXX>, <OS2::PrfDB>, <OS2::ExtAttr>. These modules provide access to additional numeric argument for `system` and to the information about the running process, to DLLs having functions with REXX signature and to the REXX runtime, to OS/2 databases in the *.INI* format, and to Extended Attributes.
Two additional extensions by Andreas Kaiser, `OS2::UPM`, and `OS2::FTP`, are included into `ILYAZ` directory, mirrored on CPAN. Other OS/2-related extensions are available too.
###
Prebuilt methods:
`File::Copy::syscopy`
used by `File::Copy::copy`, see <File::Copy>.
`DynaLoader::mod2fname`
used by `DynaLoader` for DLL name mangling.
`Cwd::current_drive()`
Self explanatory.
`Cwd::sys_chdir(name)`
leaves drive as it is.
`Cwd::change_drive(name)`
changes the "current" drive.
`Cwd::sys_is_absolute(name)`
means has drive letter and is\_rooted.
`Cwd::sys_is_rooted(name)`
means has leading `[/\\]` (maybe after a drive-letter:).
`Cwd::sys_is_relative(name)`
means changes with current dir.
`Cwd::sys_cwd(name)`
Interface to cwd from EMX. Used by `Cwd::cwd`.
`Cwd::sys_abspath(name, dir)`
Really really odious function to implement. Returns absolute name of file which would have `name` if CWD were `dir`. `Dir` defaults to the current dir.
`Cwd::extLibpath([type])`
Get current value of extended library search path. If `type` is present and positive, works with `END_LIBPATH`, if negative, works with `LIBPATHSTRICT`, otherwise with `BEGIN_LIBPATH`.
`Cwd::extLibpath_set( path [, type ] )`
Set current value of extended library search path. If `type` is present and positive, works with <END\_LIBPATH>, if negative, works with `LIBPATHSTRICT`, otherwise with `BEGIN_LIBPATH`.
`OS2::Error(do_harderror,do_exception)`
Returns `undef` if it was not called yet, otherwise bit 1 is set if on the previous call do\_harderror was enabled, bit 2 is set if on previous call do\_exception was enabled.
This function enables/disables error popups associated with hardware errors (Disk not ready etc.) and software exceptions.
I know of no way to find out the state of popups *before* the first call to this function.
`OS2::Errors2Drive(drive)`
Returns `undef` if it was not called yet, otherwise return false if errors were not requested to be written to a hard drive, or the drive letter if this was requested.
This function may redirect error popups associated with hardware errors (Disk not ready etc.) and software exceptions to the file POPUPLOG.OS2 at the root directory of the specified drive. Overrides OS2::Error() specified by individual programs. Given argument undef will disable redirection.
Has global effect, persists after the application exits.
I know of no way to find out the state of redirection of popups to the disk *before* the first call to this function.
OS2::SysInfo() Returns a hash with system information. The keys of the hash are
```
MAX_PATH_LENGTH, MAX_TEXT_SESSIONS, MAX_PM_SESSIONS,
MAX_VDM_SESSIONS, BOOT_DRIVE, DYN_PRI_VARIATION,
MAX_WAIT, MIN_SLICE, MAX_SLICE, PAGE_SIZE,
VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION,
MS_COUNT, TIME_LOW, TIME_HIGH, TOTPHYSMEM, TOTRESMEM,
TOTAVAILMEM, MAXPRMEM, MAXSHMEM, TIMER_INTERVAL,
MAX_COMP_LENGTH, FOREGROUND_FS_SESSION,
FOREGROUND_PROCESS
```
OS2::BootDrive() Returns a letter without colon.
`OS2::MorphPM(serve)`, `OS2::UnMorphPM(serve)`
Transforms the current application into a PM application and back. The argument true means that a real message loop is going to be served. OS2::MorphPM() returns the PM message queue handle as an integer.
See ["Centralized management of resources"](#Centralized-management-of-resources) for additional details.
`OS2::Serve_Messages(force)`
Fake on-demand retrieval of outstanding PM messages. If `force` is false, will not dispatch messages if a real message loop is known to be present. Returns number of messages retrieved.
Dies with "QUITing..." if WM\_QUIT message is obtained.
`OS2::Process_Messages(force [, cnt])`
Retrieval of PM messages until window creation/destruction. If `force` is false, will not dispatch messages if a real message loop is known to be present.
Returns change in number of windows. If `cnt` is given, it is incremented by the number of messages retrieved.
Dies with "QUITing..." if WM\_QUIT message is obtained.
`OS2::_control87(new,mask)`
the same as [\_control87(3)](http://man.he.net/man3/_control87) of EMX. Takes integers as arguments, returns the previous coprocessor control word as an integer. Only bits in `new` which are present in `mask` are changed in the control word.
OS2::get\_control87() gets the coprocessor control word as an integer.
`OS2::set_control87_em(new=MCW_EM,mask=MCW_EM)`
The variant of OS2::\_control87() with default values good for handling exception mask: if no `mask`, uses exception mask part of `new` only. If no `new`, disables all the floating point exceptions.
See ["Misfeatures"](#Misfeatures) for details.
`OS2::DLLname([how [, \&xsub]])`
Gives the information about the Perl DLL or the DLL containing the C function bound to by `&xsub`. The meaning of `how` is: default (2): full name; 0: handle; 1: module name.
(Note that some of these may be moved to different libraries - eventually).
###
Prebuilt variables:
$OS2::emx\_rev numeric value is the same as \_emx\_rev of EMX, a string value the same as \_emx\_vprt (similar to `0.9c`).
$OS2::emx\_env same as \_emx\_env of EMX, a number similar to 0x8001.
$OS2::os\_ver a number `OS_MAJOR + 0.001 * OS_MINOR`.
$OS2::is\_aout true if the Perl library was compiled in AOUT format.
$OS2::can\_fork true if the current executable is an AOUT EMX executable, so Perl can fork. Do not use this, use the portable check for $Config::Config{dfork}.
$OS2::nsyserror This variable (default is 1) controls whether to enforce the contents of $^E to start with `SYS0003`-like id. If set to 0, then the string value of $^E is what is available from the OS/2 message file. (Some messages in this file have an `SYS0003`-like id prepended, some not.)
### Misfeatures
* Since [flock(3)](http://man.he.net/man3/flock) is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable `USE_PERL_FLOCK=0`.
* Here is the list of things which may be "broken" on EMX (from EMX docs):
+ The functions [recvmsg(3)](http://man.he.net/man3/recvmsg), [sendmsg(3)](http://man.he.net/man3/sendmsg), and [socketpair(3)](http://man.he.net/man3/socketpair) are not implemented.
+ [sock\_init(3)](http://man.he.net/man3/sock_init) is not required and not implemented.
+ [flock(3)](http://man.he.net/man3/flock) is not yet implemented (dummy function). (Perl has a workaround.)
+ [kill(3)](http://man.he.net/man3/kill): Special treatment of PID=0, PID=1 and PID=-1 is not implemented.
+ [waitpid(3)](http://man.he.net/man3/waitpid):
```
WUNTRACED
Not implemented.
waitpid() is not implemented for negative values of PID.
```Note that `kill -9` does not work with the current version of EMX.
* See ["Text-mode filehandles"](#Text-mode-filehandles).
* Unix-domain sockets on OS/2 live in a pseudo-file-system `/sockets/...`. To avoid a failure to create a socket with a name of a different form, `"/socket/"` is prepended to the socket name (unless it starts with this already).
This may lead to problems later in case the socket is accessed via the "usual" file-system calls using the "initial" name.
* Apparently, IBM used a compiler (for some period of time around '95?) which changes FP mask right and left. This is not *that* bad for IBM's programs, but the same compiler was used for DLLs which are used with general-purpose applications. When these DLLs are used, the state of floating-point flags in the application is not predictable.
What is much worse, some DLLs change the floating point flags when in \_DLLInitTerm() (e.g., *TCP32IP*). This means that even if you do not *call* any function in the DLL, just the act of loading this DLL will reset your flags. What is worse, the same compiler was used to compile some HOOK DLLs. Given that HOOK dlls are executed in the context of *all* the applications in the system, this means a complete unpredictability of floating point flags on systems using such HOOK DLLs. E.g., *GAMESRVR.DLL* of **DIVE** origin changes the floating point flags on each write to the TTY of a VIO (windowed text-mode) applications.
Some other (not completely debugged) situations when FP flags change include some video drivers (?), and some operations related to creation of the windows. People who code **OpenGL** may have more experience on this.
Perl is generally used in the situation when all the floating-point exceptions are ignored, as is the default under EMX. If they are not ignored, some benign Perl programs would get a `SIGFPE` and would die a horrible death.
To circumvent this, Perl uses two hacks. They help against *one* type of damage only: FP flags changed when loading a DLL.
One of the hacks is to disable floating point exceptions on Perl startup (as is the default with EMX). This helps only with compile-time-linked DLLs changing the flags before main() had a chance to be called.
The other hack is to restore FP flags after a call to dlopen(). This helps against similar damage done by DLLs \_DLLInitTerm() at runtime. Currently no way to switch these hacks off is provided.
### Modifications
Perl modifies some standard C library calls in the following ways:
`popen` `my_popen` uses *sh.exe* if shell is required, cf. ["`PERL_SH_DIR`"](#PERL_SH_DIR).
`tmpnam` is created using `TMP` or `TEMP` environment variable, via `tempnam`.
`tmpfile` If the current directory is not writable, file is created using modified `tmpnam`, so there may be a race condition.
`ctermid` a dummy implementation.
`stat` `os2_stat` special-cases */dev/tty* and */dev/con*.
`mkdir`, `rmdir`
these EMX functions do not work if the path contains a trailing `/`. Perl contains a workaround for this.
`flock` Since [flock(3)](http://man.he.net/man3/flock) is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable `USE_PERL_FLOCK=0`.
###
Identifying DLLs
All the DLLs built with the current versions of Perl have ID strings identifying the name of the extension, its version, and the version of Perl required for this DLL. Run `bldlevel DLL-name` to find this info.
###
Centralized management of resources
Since to call certain OS/2 API one needs to have a correctly initialized `Win` subsystem, OS/2-specific extensions may require getting `HAB`s and `HMQ`s. If an extension would do it on its own, another extension could fail to initialize.
Perl provides a centralized management of these resources:
`HAB` To get the HAB, the extension should call `hab = perl_hab_GET()` in C. After this call is performed, `hab` may be accessed as `Perl_hab`. There is no need to release the HAB after it is used.
If by some reasons *perl.h* cannot be included, use
```
extern int Perl_hab_GET(void);
```
instead.
`HMQ` There are two cases:
* the extension needs an `HMQ` only because some API will not work otherwise. Use `serve = 0` below.
* the extension needs an `HMQ` since it wants to engage in a PM event loop. Use `serve = 1` below.
To get an `HMQ`, the extension should call `hmq = perl_hmq_GET(serve)` in C. After this call is performed, `hmq` may be accessed as `Perl_hmq`.
To signal to Perl that HMQ is not needed any more, call `perl_hmq_UNSET(serve)`. Perl process will automatically morph/unmorph itself into/from a PM process if HMQ is needed/not-needed. Perl will automatically enable/disable `WM_QUIT` message during shutdown if the message queue is served/not-served.
**NOTE**. If during a shutdown there is a message queue which did not disable WM\_QUIT, and which did not process the received WM\_QUIT message, the shutdown will be automatically cancelled. Do not call `perl_hmq_GET(1)` unless you are going to process messages on an orderly basis.
Treating errors reported by OS/2 API There are two principal conventions (it is useful to call them `Dos*` and `Win*` - though this part of the function signature is not always determined by the name of the API) of reporting the error conditions of OS/2 API. Most of `Dos*` APIs report the error code as the result of the call (so 0 means success, and there are many types of errors). Most of `Win*` API report success/fail via the result being `TRUE`/`FALSE`; to find the reason for the failure one should call WinGetLastError() API.
Some `Win*` entry points also overload a "meaningful" return value with the error indicator; having a 0 return value indicates an error. Yet some other `Win*` entry points overload things even more, and 0 return value may mean a successful call returning a valid value 0, as well as an error condition; in the case of a 0 return value one should call WinGetLastError() API to distinguish a successful call from a failing one.
By convention, all the calls to OS/2 API should indicate their failures by resetting $^E. All the Perl-accessible functions which call OS/2 API may be broken into two classes: some die()s when an API error is encountered, the other report the error via a false return value (of course, this does not concern Perl-accessible functions which *expect* a failure of the OS/2 API call, having some workarounds coded).
Obviously, in the situation of the last type of the signature of an OS/2 API, it is must more convenient for the users if the failure is indicated by die()ing: one does not need to check $^E to know that something went wrong. If, however, this solution is not desirable by some reason, the code in question should reset $^E to 0 before making this OS/2 API call, so that the caller of this Perl-accessible function has a chance to distinguish a success-but-0-return value from a failure. (One may return undef as an alternative way of reporting an error.)
The macros to simplify this type of error propagation are
`CheckOSError(expr)`
Returns true on error, sets $^E. Expects expr() be a call of `Dos*`-style API.
`CheckWinError(expr)`
Returns true on error, sets $^E. Expects expr() be a call of `Win*`-style API.
`SaveWinError(expr)`
Returns `expr`, sets $^E from WinGetLastError() if `expr` is false.
`SaveCroakWinError(expr,die,name1,name2)`
Returns `expr`, sets $^E from WinGetLastError() if `expr` is false, and die()s if `die` and $^E are true. The message to die is the concatenated strings `name1` and `name2`, separated by `": "` from the contents of $^E.
`WinError_2_Perl_rc` Sets `Perl_rc` to the return value of WinGetLastError().
`FillWinError` Sets `Perl_rc` to the return value of WinGetLastError(), and sets $^E to the corresponding value.
`FillOSError(rc)`
Sets `Perl_rc` to `rc`, and sets $^E to the corresponding value.
Loading DLLs and ordinals in DLLs Some DLLs are only present in some versions of OS/2, or in some configurations of OS/2. Some exported entry points are present only in DLLs shipped with some versions of OS/2. If these DLLs and entry points were linked directly for a Perl executable/DLL or from a Perl extensions, this binary would work only with the specified versions/setups. Even if these entry points were not needed, the *load* of the executable (or DLL) would fail.
For example, many newer useful APIs are not present in OS/2 v2; many PM-related APIs require DLLs not available on floppy-boot setup.
To make these calls fail *only when the calls are executed*, one should call these API via a dynamic linking API. There is a subsystem in Perl to simplify such type of calls. A large number of entry points available for such linking is provided (see `entries_ordinals` - and also `PMWIN_entries` - in *os2ish.h*). These ordinals can be accessed via the APIs:
```
CallORD(), DeclFuncByORD(), DeclVoidFuncByORD(),
DeclOSFuncByORD(), DeclWinFuncByORD(), AssignFuncPByORD(),
DeclWinFuncByORD_CACHE(), DeclWinFuncByORD_CACHE_survive(),
DeclWinFuncByORD_CACHE_resetError_survive(),
DeclWinFunc_CACHE(), DeclWinFunc_CACHE_resetError(),
DeclWinFunc_CACHE_survive(), DeclWinFunc_CACHE_resetError_survive()
```
See the header files and the C code in the supplied OS/2-related modules for the details on usage of these functions.
Some of these functions also combine dynaloading semantic with the error-propagation semantic discussed above.
Perl flavors
-------------
Because of idiosyncrasies of OS/2 one cannot have all the eggs in the same basket (though EMX environment tries hard to overcome this limitations, so the situation may somehow improve). There are 4 executables for Perl provided by the distribution:
###
*perl.exe*
The main workhorse. This is a chimera executable: it is compiled as an `a.out`-style executable, but is linked with `omf`-style dynamic library *perl.dll*, and with dynamic CRT DLL. This executable is a VIO application.
It can load perl dynamic extensions, and it can fork().
**Note.** Keep in mind that fork() is needed to open a pipe to yourself.
###
*perl\_.exe*
This is a statically linked `a.out`-style executable. It cannot load dynamic Perl extensions. The executable supplied in binary distributions has a lot of extensions prebuilt, thus the above restriction is important only if you use custom-built extensions. This executable is a VIO application.
*This is the only executable with does not require OS/2.* The friends locked into `M$` world would appreciate the fact that this executable runs under DOS, Win0.3\*, Win0.95 and WinNT with an appropriate extender. See ["Other OSes"](#Other-OSes).
###
*perl\_\_.exe*
This is the same executable as *perl\_\_\_.exe*, but it is a PM application.
**Note.** Usually (unless explicitly redirected during the startup) STDIN, STDERR, and STDOUT of a PM application are redirected to *nul*. However, it is possible to *see* them if you start `perl__.exe` from a PM program which emulates a console window, like *Shell mode* of Emacs or EPM. Thus it *is possible* to use Perl debugger (see <perldebug>) to debug your PM application (but beware of the message loop lockups - this will not work if you have a message queue to serve, unless you hook the serving into the getc() function of the debugger).
Another way to see the output of a PM program is to run it as
```
pm_prog args 2>&1 | cat -
```
with a shell *different* from *cmd.exe*, so that it does not create a link between a VIO session and the session of `pm_porg`. (Such a link closes the VIO window.) E.g., this works with *sh.exe* - or with Perl!
```
open P, 'pm_prog args 2>&1 |' or die;
print while <P>;
```
The flavor *perl\_\_.exe* is required if you want to start your program without a VIO window present, but not `detach`ed (run `help detach` for more info). Very useful for extensions which use PM, like `Perl/Tk` or `OpenGL`.
Note also that the differences between PM and VIO executables are only in the *default* behaviour. One can start *any* executable in *any* kind of session by using the arguments `/fs`, `/pm` or `/win` switches of the command `start` (of *CMD.EXE* or a similar shell). Alternatively, one can use the numeric first argument of the `system` Perl function (see <OS2::Process>).
###
*perl\_\_\_.exe*
This is an `omf`-style executable which is dynamically linked to *perl.dll* and CRT DLL. I know no advantages of this executable over `perl.exe`, but it cannot fork() at all. Well, one advantage is that the build process is not so convoluted as with `perl.exe`.
It is a VIO application.
###
Why strange names?
Since Perl processes the `#!`-line (cf. ["DESCRIPTION" in perlrun](perlrun#DESCRIPTION), ["Command Switches" in perlrun](perlrun#Command-Switches), ["No Perl script found in input" in perldiag](perldiag#No-Perl-script-found-in-input)), it should know when a program *is a Perl*. There is some naming convention which allows Perl to distinguish correct lines from wrong ones. The above names are almost the only names allowed by this convention which do not contain digits (which have absolutely different semantics).
###
Why dynamic linking?
Well, having several executables dynamically linked to the same huge library has its advantages, but this would not substantiate the additional work to make it compile. The reason is the complicated-to-developers but very quick and convenient-to-users "hard" dynamic linking used by OS/2.
There are two distinctive features of the dyna-linking model of OS/2: first, all the references to external functions are resolved at the compile time; second, there is no runtime fixup of the DLLs after they are loaded into memory. The first feature is an enormous advantage over other models: it avoids conflicts when several DLLs used by an application export entries with the same name. In such cases "other" models of dyna-linking just choose between these two entry points using some random criterion - with predictable disasters as results. But it is the second feature which requires the build of *perl.dll*.
The address tables of DLLs are patched only once, when they are loaded. The addresses of the entry points into DLLs are guaranteed to be the same for all the programs which use the same DLL. This removes the runtime fixup - once DLL is loaded, its code is read-only.
While this allows some (significant?) performance advantages, this makes life much harder for developers, since the above scheme makes it impossible for a DLL to be "linked" to a symbol in the *.EXE* file. Indeed, this would need a DLL to have different relocations tables for the (different) executables which use this DLL.
However, a dynamically loaded Perl extension is forced to use some symbols from the perl executable, e.g., to know how to find the arguments to the functions: the arguments live on the perl internal evaluation stack. The solution is to put the main code of the interpreter into a DLL, and make the *.EXE* file which just loads this DLL into memory and supplies command-arguments. The extension DLL cannot link to symbols in *.EXE*, but it has no problem linking to symbols in the *.DLL*.
This *greatly* increases the load time for the application (as well as complexity of the compilation). Since interpreter is in a DLL, the C RTL is basically forced to reside in a DLL as well (otherwise extensions would not be able to use CRT). There are some advantages if you use different flavors of perl, such as running *perl.exe* and *perl\_\_.exe* simultaneously: they share the memory of *perl.dll*.
**NOTE**. There is one additional effect which makes DLLs more wasteful: DLLs are loaded in the shared memory region, which is a scarse resource given the 512M barrier of the "standard" OS/2 virtual memory. The code of *.EXE* files is also shared by all the processes which use the particular *.EXE*, but they are "shared in the private address space of the process"; this is possible because the address at which different sections of the *.EXE* file are loaded is decided at compile-time, thus all the processes have these sections loaded at same addresses, and no fixup of internal links inside the *.EXE* is needed.
Since DLLs may be loaded at run time, to have the same mechanism for DLLs one needs to have the address range of *any of the loaded* DLLs in the system to be available *in all the processes* which did not load a particular DLL yet. This is why the DLLs are mapped to the shared memory region.
###
Why chimera build?
Current EMX environment does not allow DLLs compiled using Unixish `a.out` format to export symbols for data (or at least some types of data). This forces `omf`-style compile of *perl.dll*.
Current EMX environment does not allow *.EXE* files compiled in `omf` format to fork(). fork() is needed for exactly three Perl operations:
* explicit fork() in the script,
* `open FH, "|-"`
* `open FH, "-|"`, in other words, opening pipes to itself.
While these operations are not questions of life and death, they are needed for a lot of useful scripts. This forces `a.out`-style compile of *perl.exe*.
ENVIRONMENT
-----------
Here we list environment variables with are either OS/2- and DOS- and Win\*-specific, or are more important under OS/2 than under other OSes.
### `PERLLIB_PREFIX`
Specific for EMX port. Should have the form
```
path1;path2
```
or
```
path1 path2
```
If the beginning of some prebuilt path matches *path1*, it is substituted with *path2*.
Should be used if the perl library is moved from the default location in preference to `PERL(5)LIB`, since this would not leave wrong entries in @INC. For example, if the compiled version of perl looks for @INC in *f:/perllib/lib*, and you want to install the library in *h:/opt/gnu*, do
```
set PERLLIB_PREFIX=f:/perllib/lib;h:/opt/gnu
```
This will cause Perl with the prebuilt @INC of
```
f:/perllib/lib/5.00553/os2
f:/perllib/lib/5.00553
f:/perllib/lib/site_perl/5.00553/os2
f:/perllib/lib/site_perl/5.00553
.
```
to use the following @INC:
```
h:/opt/gnu/5.00553/os2
h:/opt/gnu/5.00553
h:/opt/gnu/site_perl/5.00553/os2
h:/opt/gnu/site_perl/5.00553
.
```
### `PERL_BADLANG`
If 0, perl ignores setlocale() failing. May be useful with some strange *locale*s.
### `PERL_BADFREE`
If 0, perl would not warn of in case of unwarranted free(). With older perls this might be useful in conjunction with the module DB\_File, which was buggy when dynamically linked and OMF-built.
Should not be set with newer Perls, since this may hide some *real* problems.
### `PERL_SH_DIR`
Specific for EMX port. Gives the directory part of the location for *sh.exe*.
### `USE_PERL_FLOCK`
Specific for EMX port. Since [flock(3)](http://man.he.net/man3/flock) is present in EMX, but is not functional, it is emulated by perl. To disable the emulations, set environment variable `USE_PERL_FLOCK=0`.
###
`TMP` or `TEMP`
Specific for EMX port. Used as storage place for temporary files.
Evolution
---------
Here we list major changes which could make you by surprise.
###
Text-mode filehandles
Starting from version 5.8, Perl uses a builtin translation layer for text-mode files. This replaces the efficient well-tested EMX layer by some code which should be best characterized as a "quick hack".
In addition to possible bugs and an inability to follow changes to the translation policy with off/on switches of TERMIO translation, this introduces a serious incompatible change: before sysread() on text-mode filehandles would go through the translation layer, now it would not.
### Priorities
`setpriority` and `getpriority` are not compatible with earlier ports by Andreas Kaiser. See ["setpriority, getpriority"](#setpriority%2C-getpriority).
###
DLL name mangling: pre 5.6.2
With the release 5.003\_01 the dynamically loadable libraries should be rebuilt when a different version of Perl is compiled. In particular, DLLs (including *perl.dll*) are now created with the names which contain a checksum, thus allowing workaround for OS/2 scheme of caching DLLs.
It may be possible to code a simple workaround which would
* find the old DLLs looking through the old @INC;
* mangle the names according to the scheme of new perl and copy the DLLs to these names;
* edit the internal `LX` tables of DLL to reflect the change of the name (probably not needed for Perl extension DLLs, since the internally coded names are not used for "specific" DLLs, they used only for "global" DLLs).
* edit the internal `IMPORT` tables and change the name of the "old" *perl????.dll* to the "new" *perl????.dll*.
###
DLL name mangling: 5.6.2 and beyond
In fact mangling of *extension* DLLs was done due to misunderstanding of the OS/2 dynaloading model. OS/2 (effectively) maintains two different tables of loaded DLL:
Global DLLs those loaded by the base name from `LIBPATH`; including those associated at link time;
specific DLLs loaded by the full name.
When resolving a request for a global DLL, the table of already-loaded specific DLLs is (effectively) ignored; moreover, specific DLLs are *always* loaded from the prescribed path.
There is/was a minor twist which makes this scheme fragile: what to do with DLLs loaded from
`BEGINLIBPATH` and `ENDLIBPATH`
(which depend on the process)
*.* from `LIBPATH`
which *effectively* depends on the process (although `LIBPATH` is the same for all the processes).
Unless `LIBPATHSTRICT` is set to `T` (and the kernel is after 2000/09/01), such DLLs are considered to be global. When loading a global DLL it is first looked in the table of already-loaded global DLLs. Because of this the fact that one executable loaded a DLL from `BEGINLIBPATH` and `ENDLIBPATH`, or *.* from `LIBPATH` may affect *which* DLL is loaded when *another* executable requests a DLL with the same name. *This* is the reason for version-specific mangling of the DLL name for perl DLL.
Since the Perl extension DLLs are always loaded with the full path, there is no need to mangle their names in a version-specific ways: their directory already reflects the corresponding version of perl, and @INC takes into account binary compatibility with older version. Starting from `5.6.2` the name mangling scheme is fixed to be the same as for Perl 5.005\_53 (same as in a popular binary release). Thus new Perls will be able to *resolve the names* of old extension DLLs if @INC allows finding their directories.
However, this still does not guarantee that these DLL may be loaded. The reason is the mangling of the name of the *Perl DLL*. And since the extension DLLs link with the Perl DLL, extension DLLs for older versions would load an older Perl DLL, and would most probably segfault (since the data in this DLL is not properly initialized).
There is a partial workaround (which can be made complete with newer OS/2 kernels): create a forwarder DLL with the same name as the DLL of the older version of Perl, which forwards the entry points to the newer Perl's DLL. Make this DLL accessible on (say) the `BEGINLIBPATH` of the new Perl executable. When the new executable accesses old Perl's extension DLLs, they would request the old Perl's DLL by name, get the forwarder instead, so effectively will link with the currently running (new) Perl DLL.
This may break in two ways:
* Old perl executable is started when a new executable is running has loaded an extension compiled for the old executable (ouph!). In this case the old executable will get a forwarder DLL instead of the old perl DLL, so would link with the new perl DLL. While not directly fatal, it will behave the same as new executable. This beats the whole purpose of explicitly starting an old executable.
* A new executable loads an extension compiled for the old executable when an old perl executable is running. In this case the extension will not pick up the forwarder - with fatal results.
With support for `LIBPATHSTRICT` this may be circumvented - unless one of DLLs is started from *.* from `LIBPATH` (I do not know whether `LIBPATHSTRICT` affects this case).
**REMARK**. Unless newer kernels allow *.* in `BEGINLIBPATH` (older do not), this mess cannot be completely cleaned. (It turns out that as of the beginning of 2002, *.* is not allowed, but *.\.* is - and it has the same effect.)
**REMARK**. `LIBPATHSTRICT`, `BEGINLIBPATH` and `ENDLIBPATH` are not environment variables, although *cmd.exe* emulates them on `SET ...` lines. From Perl they may be accessed by [Cwd::extLibpath](#Cwd%3A%3AextLibpath%28%5Btype%5D%29) and [Cwd::extLibpath\_set](#Cwd%3A%3AextLibpath_set%28-path-%5B%2C-type-%5D-%29).
###
DLL forwarder generation
Assume that the old DLL is named *perlE0AC.dll* (as is one for 5.005\_53), and the new version is 5.6.1. Create a file *perl5shim.def-leader* with
```
LIBRARY 'perlE0AC' INITINSTANCE TERMINSTANCE
DESCRIPTION '@#[email protected]:5.006001#@ Perl module for 5.00553 -> Perl 5.6.1 forwarder'
CODE LOADONCALL
DATA LOADONCALL NONSHARED MULTIPLE
EXPORTS
```
modifying the versions/names as needed. Run
```
perl -wnle "next if 0../EXPORTS/; print qq( \"$1\")
if /\"(\w+)\"/" perl5.def >lst
```
in the Perl build directory (to make the DLL smaller replace perl5.def with the definition file for the older version of Perl if present).
```
cat perl5shim.def-leader lst >perl5shim.def
gcc -Zomf -Zdll -o perlE0AC.dll perl5shim.def -s -llibperl
```
(ignore multiple `warning L4085`).
### Threading
As of release 5.003\_01 perl is linked to multithreaded C RTL DLL. If perl itself is not compiled multithread-enabled, so will not be perl's malloc(). However, extensions may use multiple thread on their own risk.
This was needed to compile `Perl/Tk` for XFree86-OS/2 out-of-the-box, and link with DLLs for other useful libraries, which typically are compiled with `-Zmt -Zcrtdll`.
###
Calls to external programs
Due to a popular demand the perl external program calling has been changed wrt Andreas Kaiser's port. *If* perl needs to call an external program *via shell*, the *f:/bin/sh.exe* will be called, or whatever is the override, see ["`PERL_SH_DIR`"](#PERL_SH_DIR).
Thus means that you need to get some copy of a *sh.exe* as well (I use one from pdksh). The path *F:/bin* above is set up automatically during the build to a correct value on the builder machine, but is overridable at runtime,
**Reasons:** a consensus on `perl5-porters` was that perl should use one non-overridable shell per platform. The obvious choices for OS/2 are *cmd.exe* and *sh.exe*. Having perl build itself would be impossible with *cmd.exe* as a shell, thus I picked up `sh.exe`. This assures almost 100% compatibility with the scripts coming from \*nix. As an added benefit this works as well under DOS if you use DOS-enabled port of pdksh (see ["Prerequisites"](#Prerequisites)).
**Disadvantages:** currently *sh.exe* of pdksh calls external programs via fork()/exec(), and there is *no* functioning exec() on OS/2. exec() is emulated by EMX by an asynchronous call while the caller waits for child completion (to pretend that the `pid` did not change). This means that 1 *extra* copy of *sh.exe* is made active via fork()/exec(), which may lead to some resources taken from the system (even if we do not count extra work needed for fork()ing).
Note that this a lesser issue now when we do not spawn *sh.exe* unless needed (metachars found).
One can always start *cmd.exe* explicitly via
```
system 'cmd', '/c', 'mycmd', 'arg1', 'arg2', ...
```
If you need to use *cmd.exe*, and do not want to hand-edit thousands of your scripts, the long-term solution proposed on p5-p is to have a directive
```
use OS2::Cmd;
```
which will override system(), exec(), ````, and `open(,'...|')`. With current perl you may override only system(), readpipe() - the explicit version of ````, and maybe exec(). The code will substitute the one-argument call to system() by `CORE::system('cmd.exe', '/c', shift)`.
If you have some working code for `OS2::Cmd`, please send it to me, I will include it into distribution. I have no need for such a module, so cannot test it.
For the details of the current situation with calling external programs, see ["Starting OS/2 (and DOS) programs under Perl"](#Starting-OS%2F2-%28and-DOS%29-programs-under-Perl). Set us mention a couple of features:
* External scripts may be called by their basename. Perl will try the same extensions as when processing **-S** command-line switch.
* External scripts starting with `#!` or `extproc` will be executed directly, without calling the shell, by calling the program specified on the rest of the first line.
###
Memory allocation
Perl uses its own malloc() under OS/2 - interpreters are usually malloc-bound for speed, but perl is not, since its malloc is lightning-fast. Perl-memory-usage-tuned benchmarks show that Perl's malloc is 5 times quicker than EMX one. I do not have convincing data about memory footprint, but a (pretty random) benchmark showed that Perl's one is 5% better.
Combination of perl's malloc() and rigid DLL name resolution creates a special problem with library functions which expect their return value to be free()d by system's free(). To facilitate extensions which need to call such functions, system memory-allocation functions are still available with the prefix `emx_` added. (Currently only DLL perl has this, it should propagate to *perl\_.exe* shortly.)
### Threads
One can build perl with thread support enabled by providing `-D usethreads` option to *Configure*. Currently OS/2 support of threads is very preliminary.
Most notable problems:
`COND_WAIT` may have a race condition (but probably does not due to edge-triggered nature of OS/2 Event semaphores). (Needs a reimplementation (in terms of chaining waiting threads, with the linked list stored in per-thread structure?)?)
*os2.c*
has a couple of static variables used in OS/2-specific functions. (Need to be moved to per-thread structure, or serialized?)
Note that these problems should not discourage experimenting, since they have a low probability of affecting small programs.
BUGS
----
This description is not updated often (since 5.6.1?), see *./os2/Changes* for more info.
AUTHOR
------
Ilya Zakharevich, [email protected]
SEE ALSO
---------
perl(1).
| programming_docs |
perl File::Spec File::Spec
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
File::Spec - portably perform operations on file names
SYNOPSIS
--------
```
use File::Spec;
$x=File::Spec->catfile('a', 'b', 'c');
```
which returns 'a/b/c' under Unix. Or:
```
use File::Spec::Functions;
$x = catfile('a', 'b', 'c');
```
DESCRIPTION
-----------
This module is designed to support operations commonly performed on file specifications (usually called "file names", but not to be confused with the contents of a file, or Perl's file handles), such as concatenating several directory and file names into a single path, or determining whether a path is rooted. It is based on code directly taken from MakeMaker 5.17, code written by Andreas König, Andy Dougherty, Charles Bailey, Ilya Zakharevich, Paul Schinder, and others.
Since these functions are different for most operating systems, each set of OS specific routines is available in a separate module, including:
```
File::Spec::Unix
File::Spec::Mac
File::Spec::OS2
File::Spec::Win32
File::Spec::VMS
```
The module appropriate for the current OS is automatically loaded by File::Spec. Since some modules (like VMS) make use of facilities available only under that OS, it may not be possible to load all modules under all operating systems.
Since File::Spec is object oriented, subroutines should not be called directly, as in:
```
File::Spec::catfile('a','b');
```
but rather as class methods:
```
File::Spec->catfile('a','b');
```
For simple uses, <File::Spec::Functions> provides convenient functional forms of these methods.
METHODS
-------
canonpath No physical check on the filesystem, but a logical cleanup of a path.
```
$cpath = File::Spec->canonpath( $path ) ;
```
Note that this does \*not\* collapse *x/../y* sections into *y*. This is by design. If */foo* on your system is a symlink to */bar/baz*, then */foo/../quux* is actually */bar/quux*, not */quux* as a naive *../*-removal would give you. If you want to do this kind of processing, you probably want `Cwd`'s `realpath()` function to actually traverse the filesystem cleaning up paths like this.
catdir Concatenate two or more directory names to form a complete path ending with a directory. But remove the trailing slash from the resulting string, because it doesn't look good, isn't necessary and confuses OS/2. Of course, if this is the root directory, don't cut off the trailing slash :-)
```
$path = File::Spec->catdir( @directories );
```
catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename
```
$path = File::Spec->catfile( @directories, $filename );
```
curdir Returns a string representation of the current directory.
```
$curdir = File::Spec->curdir();
```
devnull Returns a string representation of the null device.
```
$devnull = File::Spec->devnull();
```
rootdir Returns a string representation of the root directory.
```
$rootdir = File::Spec->rootdir();
```
tmpdir Returns a string representation of the first writable directory from a list of possible temporary directories. Returns the current directory if no writable temporary directories are found. The list of directories checked depends on the platform; e.g. File::Spec::Unix checks `$ENV{TMPDIR}` (unless taint is on) and */tmp*.
```
$tmpdir = File::Spec->tmpdir();
```
updir Returns a string representation of the parent directory.
```
$updir = File::Spec->updir();
```
no\_upwards Given a list of files in a directory (such as from `readdir()`), strip out `'.'` and `'..'`.
**SECURITY NOTE:** This does NOT filter paths containing `'..'`, like `'../../../../etc/passwd'`, only literal matches to `'.'` and `'..'`.
```
@paths = File::Spec->no_upwards( readdir $dirhandle );
```
case\_tolerant Returns a true or false value indicating, respectively, that alphabetic case is not or is significant when comparing file specifications. Cygwin and Win32 accept an optional drive argument.
```
$is_case_tolerant = File::Spec->case_tolerant();
```
file\_name\_is\_absolute Takes as its argument a path, and returns true if it is an absolute path.
```
$is_absolute = File::Spec->file_name_is_absolute( $path );
```
This does not consult the local filesystem on Unix, Win32, OS/2, or Mac OS (Classic). It does consult the working environment for VMS (see ["file\_name\_is\_absolute" in File::Spec::VMS](File::Spec::VMS#file_name_is_absolute)).
path Takes no argument. Returns the environment variable `PATH` (or the local platform's equivalent) as a list.
```
@PATH = File::Spec->path();
```
join join is the same as catfile.
splitpath Splits a path in to volume, directory, and filename portions. On systems with no concept of volume, returns '' for volume.
```
($volume,$directories,$file) =
File::Spec->splitpath( $path );
($volume,$directories,$file) =
File::Spec->splitpath( $path, $no_file );
```
For systems with no syntax differentiating filenames from directories, assumes that the last file is a path unless `$no_file` is true or a trailing separator or */.* or */..* is present. On Unix, this means that `$no_file` true makes this return ( '', $path, '' ).
The directory portion may or may not be returned with a trailing '/'.
The results can be passed to ["catpath()"](#catpath%28%29) to get back a path equivalent to (usually identical to) the original path.
splitdir The opposite of ["catdir"](#catdir).
```
@dirs = File::Spec->splitdir( $directories );
```
`$directories` must be only the directory portion of the path on systems that have the concept of a volume or that have path syntax that differentiates files from directories.
Unlike just splitting the directories on the separator, empty directory names (`''`) can be returned, because these are significant on some OSes.
catpath() Takes volume, directory and file portions and returns an entire path. Under Unix, `$volume` is ignored, and directory and file are concatenated. A '/' is inserted if need be. On other OSes, `$volume` is significant.
```
$full_path = File::Spec->catpath( $volume, $directory, $file );
```
abs2rel Takes a destination path and an optional base path returns a relative path from the base path to the destination path:
```
$rel_path = File::Spec->abs2rel( $path ) ;
$rel_path = File::Spec->abs2rel( $path, $base ) ;
```
If `$base` is not present or '', then [Cwd::cwd()](cwd) is used. If `$base` is relative, then it is converted to absolute form using ["rel2abs()"](#rel2abs%28%29). This means that it is taken to be relative to [Cwd::cwd()](cwd).
On systems with the concept of volume, if `$path` and `$base` appear to be on two different volumes, we will not attempt to resolve the two paths, and we will instead simply return `$path`. Note that previous versions of this module ignored the volume of `$base`, which resulted in garbage results part of the time.
On systems that have a grammar that indicates filenames, this ignores the `$base` filename as well. Otherwise all path components are assumed to be directories.
If `$path` is relative, it is converted to absolute form using ["rel2abs()"](#rel2abs%28%29). This means that it is taken to be relative to [Cwd::cwd()](cwd).
No checks against the filesystem are made. On VMS, there is interaction with the working environment, as logicals and macros are expanded.
Based on code written by Shigio Yamaguchi.
rel2abs() Converts a relative path to an absolute path.
```
$abs_path = File::Spec->rel2abs( $path ) ;
$abs_path = File::Spec->rel2abs( $path, $base ) ;
```
If `$base` is not present or '', then [Cwd::cwd()](cwd) is used. If `$base` is relative, then it is converted to absolute form using ["rel2abs()"](#rel2abs%28%29). This means that it is taken to be relative to [Cwd::cwd()](cwd).
On systems with the concept of volume, if `$path` and `$base` appear to be on two different volumes, we will not attempt to resolve the two paths, and we will instead simply return `$path`. Note that previous versions of this module ignored the volume of `$base`, which resulted in garbage results part of the time.
On systems that have a grammar that indicates filenames, this ignores the `$base` filename as well. Otherwise all path components are assumed to be directories.
If `$path` is absolute, it is cleaned up and returned using ["canonpath"](#canonpath).
No checks against the filesystem are made. On VMS, there is interaction with the working environment, as logicals and macros are expanded.
Based on code written by Shigio Yamaguchi.
For further information, please see <File::Spec::Unix>, <File::Spec::Mac>, <File::Spec::OS2>, <File::Spec::Win32>, or <File::Spec::VMS>.
SEE ALSO
---------
<File::Spec::Unix>, <File::Spec::Mac>, <File::Spec::OS2>, <File::Spec::Win32>, <File::Spec::VMS>, <File::Spec::Functions>, <ExtUtils::MakeMaker>
AUTHOR
------
Maintained by perl5-porters <*[email protected]*>.
The vast majority of the code was written by Kenneth Albanowski `<[email protected]>`, Andy Dougherty `<[email protected]>`, Andreas König `<[email protected]>`, Tim Bunce `<[email protected]>`. VMS support by Charles Bailey `<[email protected]>`. OS/2 support by Ilya Zakharevich `<[email protected]>`. Mac support by Paul Schinder `<[email protected]>`, and Thomas Wegner `<[email protected]>`. abs2rel() and rel2abs() written by Shigio Yamaguchi `<[email protected]>`, modified by Barrie Slaymaker `<[email protected]>`. splitpath(), splitdir(), catpath() and catdir() by Barrie Slaymaker.
COPYRIGHT
---------
Copyright (c) 2004-2013 by the Perl 5 Porters. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Test2 Test2
=====
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [WHAT IS NEW?](#WHAT-IS-NEW?)
* [GETTING STARTED](#GETTING-STARTED)
* [NAMESPACE LAYOUT](#NAMESPACE-LAYOUT)
+ [Test2::Tools::](#Test2::Tools::)
+ [Test2::Plugin::](#Test2::Plugin::)
+ [Test2::Bundle::](#Test2::Bundle::)
+ [Test2::Require::](#Test2::Require::)
+ [Test2::Formatter::](#Test2::Formatter::)
+ [Test2::Event::](#Test2::Event::)
+ [Test2::Hub::](#Test2::Hub::)
+ [Test2::IPC::](#Test2::IPC::)
- [Test2::IPC::Driver::](#Test2::IPC::Driver::)
+ [Test2::Util::](#Test2::Util::)
+ [Test2::API::](#Test2::API::)
+ [Test2::](#Test2::)
* [SEE ALSO](#SEE-ALSO)
* [CONTACTING US](#CONTACTING-US)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2 - Framework for writing test tools that all work together.
DESCRIPTION
-----------
Test2 is a new testing framework produced by forking <Test::Builder>, completely refactoring it, adding many new features and capabilities.
###
WHAT IS NEW?
Easier to test new testing tools. From the beginning Test2 was built with introspection capabilities. With Test::Builder it was difficult at best to capture test tool output for verification. Test2 Makes it easy with `Test2::API::intercept()`.
Better diagnostics capabilities. Test2 uses an <Test2::API::Context> object to track filename, line number, and tool details. This object greatly simplifies tracking for where errors should be reported.
Event driven. Test2 based tools produce events which get passed through a processing system before being output by a formatter. This event system allows for rich plugin and extension support.
More complete API. Test::Builder only provided a handful of methods for generating lines of TAP. Test2 took inventory of everything people were doing with Test::Builder that required hacking it up. Test2 made public API functions for nearly all the desired functionality people didn't previously have.
Support for output other than TAP. Test::Builder assumed everything would end up as TAP. Test2 makes no such assumption. Test2 provides ways for you to specify alternative and custom formatters.
Subtest implementation is more sane. The Test::Builder implementation of subtests was certifiably insane. Test2 uses a stacked event hub system that greatly improves how subtests are implemented.
Support for threading/forking. Test2 support for forking and threading can be turned on using <Test2::IPC>. Once turned on threading and forking operate sanely and work as one would expect.
GETTING STARTED
----------------
If you are interested in writing tests using new tools then you should look at <Test2::Suite>. <Test2::Suite> is a separate cpan distribution that contains many tools implemented on Test2.
If you are interested in writing new tools you should take a look at <Test2::API> first.
NAMESPACE LAYOUT
-----------------
This describes the namespace layout for the Test2 ecosystem. Not all the namespaces listed here are part of the Test2 distribution, some are implemented in <Test2::Suite>.
###
Test2::Tools::
This namespace is for sets of tools. Modules in this namespace should export tools like `ok()` and `is()`. Most things written for Test2 should go here. Modules in this namespace **MUST NOT** export subs from other tools. See the ["Test2::Bundle::"](#Test2%3A%3ABundle%3A%3A) namespace if you want to do that.
###
Test2::Plugin::
This namespace is for plugins. Plugins are modules that change or enhance the behavior of Test2. An example of a plugin is a module that sets the encoding to utf8 globally. Another example is a module that causes a bail-out event after the first test failure.
###
Test2::Bundle::
This namespace is for bundles of tools and plugins. Loading one of these may load multiple tools and plugins. Modules in this namespace should not implement tools directly. In general modules in this namespace should load tools and plugins, then re-export things into the consumers namespace.
###
Test2::Require::
This namespace is for modules that cause a test to be skipped when conditions do not allow it to run. Examples would be modules that skip the test on older perls, or when non-essential modules have not been installed.
###
Test2::Formatter::
Formatters live under this namespace. <Test2::Formatter::TAP> is the only formatter currently. It is acceptable for third party distributions to create new formatters under this namespace.
###
Test2::Event::
Events live under this namespace. It is considered acceptable for third party distributions to add new event types in this namespace.
###
Test2::Hub::
Hub subclasses (and some hub utility objects) live under this namespace. It is perfectly reasonable for third party distributions to add new hub subclasses in this namespace.
###
Test2::IPC::
The IPC subsystem lives in this namespace. There are not many good reasons to add anything to this namespace, with exception of IPC drivers.
####
Test2::IPC::Driver::
IPC drivers live in this namespace. It is fine to create new IPC drivers and to put them in this namespace.
###
Test2::Util::
This namespace is for general utilities used by testing tools. Please be considerate when adding new modules to this namespace.
###
Test2::API::
This is for Test2 API and related packages.
###
Test2::
The Test2:: namespace is intended for extensions and frameworks. Tools, Plugins, etc should not go directly into this namespace. However extensions that are used to build tools and plugins may go here.
In short: If the module exports anything that should be run directly by a test script it should probably NOT go directly into `Test2::XXX`.
SEE ALSO
---------
<Test2::API> - Primary API functions.
<Test2::API::Context> - Detailed documentation of the context object.
<Test2::IPC> - The IPC system used for threading/fork support.
<Test2::Formatter> - Formatters such as TAP live here.
<Test2::Event> - Events live in this namespace.
<Test2::Hub> - All events eventually funnel through a hub. Custom hubs are how `intercept()` and `run_subtest()` are implemented.
CONTACTING US
--------------
Many Test2 developers and users lurk on <irc://irc.perl.org/#perl-qa> and <irc://irc.perl.org/#toolchain>. We also have a slack team that can be joined by anyone with an `@cpan.org` email address <https://perl-test2.slack.com/> If you do not have an `@cpan.org` email you can ask for a slack invite by emailing Chad Granum <[email protected]>.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl TAP::Parser::Scheduler::Job TAP::Parser::Scheduler::Job
===========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [on\_finish](#on_finish)
- [finish](#finish)
+ [Attributes](#Attributes)
- [filename](#filename)
- [description](#description)
- [context](#context)
- [as\_array\_ref](#as_array_ref)
- [is\_spinner](#is_spinner)
NAME
----
TAP::Parser::Scheduler::Job - A single testing job.
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Scheduler::Job;
```
DESCRIPTION
-----------
Represents a single test 'job'.
METHODS
-------
###
Class Methods
#### `new`
```
my $job = TAP::Parser::Scheduler::Job->new(
$filename, $description
);
```
Given the filename and description of a test as scalars, returns a new <TAP::Parser::Scheduler::Job> object.
###
Instance Methods
#### `on_finish`
```
$self->on_finish(\&method).
```
Register a closure to be called when this job is destroyed. The callback will be passed the `TAP::Parser::Scheduler::Job` object as it's only argument.
#### `finish`
```
$self->finish;
```
Called when a job is complete to unlock it. If a callback has been registered with `on_finish`, it calls it. Otherwise, it does nothing.
### Attributes
```
$self->filename;
$self->description;
$self->context;
```
These are all "getters" which return the data set for these attributes during object construction.
#### `filename`
#### `description`
#### `context`
#### `as_array_ref`
For backwards compatibility in callbacks.
#### `is_spinner`
```
$self->is_spinner;
```
Returns false indicating that this is a real job rather than a 'spinner'. Spinners are returned when the scheduler still has pending jobs but can't (because of locking) return one right now.
perl Errno Errno
=====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Errno - System errno constants
SYNOPSIS
--------
```
use Errno qw(EINTR EIO :POSIX);
```
DESCRIPTION
-----------
`Errno` defines and conditionally exports all the error constants defined in your system *errno.h* include file. It has a single export tag, `:POSIX`, which will export all POSIX defined error numbers.
On Windows, `Errno` also defines and conditionally exports all the Winsock error constants defined in your system *WinError.h* include file. These are included in a second export tag, `:WINSOCK`.
`Errno` also makes `%!` magic such that each element of `%!` has a non-zero value only if `$!` is set to that value. For example:
```
my $fh;
unless (open($fh, "<", "/fangorn/spouse")) {
if ($!{ENOENT}) {
warn "Get a wife!\n";
} else {
warn "This path is barred: $!";
}
}
```
If a specified constant `EFOO` does not exist on the system, `$!{EFOO}` returns `""`. You may use `exists $!{EFOO}` to check whether the constant is available on the system.
Perl automatically loads `Errno` the first time you use `%!`, so you don't need an explicit `use`.
CAVEATS
-------
Importing a particular constant may not be very portable, because the import will fail on platforms that do not have that constant. A more portable way to set `$!` to a valid value is to use:
```
if (exists &Errno::EFOO) {
$! = &Errno::EFOO;
}
```
AUTHOR
------
Graham Barr <[email protected]>
COPYRIGHT
---------
Copyright (c) 1997-8 Graham Barr. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Test2::Event Test2::Event
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [GENERAL](#GENERAL)
+ [NEW API](#NEW-API)
- [WHAT ARE FACETS?](#WHAT-ARE-FACETS?)
+ [LEGACY API](#LEGACY-API)
* [THIRD PARTY META-DATA](#THIRD-PARTY-META-DATA)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event - Base class for events
DESCRIPTION
-----------
Base class for all event objects that get passed through [Test2](test2).
SYNOPSIS
--------
```
package Test2::Event::MyEvent;
use strict;
use warnings;
# This will make our class an event subclass (required)
use base 'Test2::Event';
# Add some accessors (optional)
# You are not obligated to use HashBase, you can use any object tool you
# want, or roll your own accessors.
use Test2::Util::HashBase qw/foo bar baz/;
# Use this if you want the legacy API to be written for you, for this to
# work you will need to implement a facet_data() method.
use Test2::Util::Facets2Legacy;
# Chance to initialize some defaults
sub init {
my $self = shift;
# no other args in @_
$self->set_foo('xxx') unless defined $self->foo;
...
}
# This is the new way for events to convey data to the Test2 system
sub facet_data {
my $self = shift;
# Get common facets such as 'about', 'trace' 'amnesty', and 'meta'
my $facet_data = $self->common_facet_data();
# Are you making an assertion?
$facet_data->{assert} = {pass => 1, details => 'my assertion'};
...
return $facet_data;
}
1;
```
METHODS
-------
### GENERAL
$trace = $e->trace Get a snapshot of the <Test2::EventFacet::Trace> as it was when this event was generated
$bool\_or\_undef = $e->related($e2) Check if 2 events are related. In this case related means their traces share a signature meaning they were created with the same context (or at the very least by contexts which share an id, which is the same thing unless someone is doing something very bad).
This can be used to reliably link multiple events created by the same tool. For instance a failing test like `ok(0, "fail"` will generate 2 events, one being a <Test2::Event::Ok>, the other being a <Test2::Event::Diag>, both of these events are related having been created under the same context and by the same initial tool (though multiple tools may have been nested under the initial one).
This will return `undef` if the relationship cannot be checked, which happens if either event has an incomplete or missing trace. This will return `0` if the traces are complete, but do not match. `1` will be returned if there is a match.
$e->add\_amnesty({tag => $TAG, details => $DETAILS}); This can be used to add amnesty to this event. Amnesty only effects failing assertions in most cases, but some formatters may display them for passing assertions, or even non-assertions as well.
Amnesty will prevent a failed assertion from causing the overall test to fail. In other words it marks a failure as expected and allowed.
**Note:** This is how 'TODO' is implemented under the hood. TODO is essentially amnesty with the 'TODO' tag. The details are the reason for the TODO.
$uuid = $e->uuid If UUID tagging is enabled (See <Test::API>) then any event that has made its way through a hub will be tagged with a UUID. A newly created event will not yet be tagged in most cases.
$class = $e->load\_facet($name) This method is used to load a facet by name (or key). It will attempt to load the facet class, if it succeeds it will return the class it loaded. If it fails it will return `undef`. This caches the result at the class level so that future calls will be faster.
The `$name` variable should be the key used to access the facet in a facets hashref. For instance the assertion facet has the key 'assert', the information facet has the 'info' key, and the error facet has the key 'errors'. You may include or omit the 's' at the end of the name, the method is smart enough to try both the 's' and no-'s' forms, it will check what you provided first, and if that is not found it will add or strip the 's and try again.
@classes = $e->FACET\_TYPES()
@classes = Test2::Event->FACET\_TYPES() This returns a list of all facets that have been loaded using the `load_facet()` method. This will not return any classes that have not been loaded, or have been loaded directly without a call to `load_facet()`.
**Note:** The core facet types are automatically loaded and populated in this list.
###
NEW API
$hashref = $e->common\_facet\_data(); This can be used by subclasses to generate a starting facet data hashref. This will populate the hashref with the trace, meta, amnesty, and about facets. These facets are nearly always produced the same way for all events.
$hashref = $e->facet\_data() If you do not override this then the default implementation will attempt to generate facets from the legacy API. This generation is limited only to what the legacy API can provide. It is recommended that you override this method and write out explicit facet data.
$hashref = $e->facets() This takes the hashref from `facet_data()` and blesses each facet into the proper `Test2::EventFacet::*` subclass. If no class can be found for any given facet it will be passed along unchanged.
@errors = $e->validate\_facet\_data();
@errors = $e->validate\_facet\_data(%params);
@errors = $e->validate\_facet\_data(\%facets, %params);
@errors = Test2::Event->validate\_facet\_data(%params);
@errors = Test2::Event->validate\_facet\_data(\%facets, %params); This method will validate facet data and return a list of errors. If no errors are found this will return an empty list.
This can be called as an object method with no arguments, in which case the `facet_data()` method will be called to get the facet data to be validated.
When used as an object method the `\%facet_data` argument may be omitted.
When used as a class method the `\%facet_data` argument is required.
Remaining arguments will be slurped into a `%params` hash.
Currently only 1 parameter is defined:
require\_facet\_class => $BOOL When set to true (default is false) this will reject any facets where a facet class cannot be found. Normally facets without classes are assumed to be custom and are ignored.
####
WHAT ARE FACETS?
Facets are how events convey their purpose to the Test2 internals and formatters. An event without facets will have no intentional effect on the overall test state, and will not be displayed at all by most formatters, except perhaps to say that an event of an unknown type was seen.
Facets are produced by the `facet_data()` subroutine, which you should nearly-always override. `facet_data()` is expected to return a hashref where each key is the facet type, and the value is either a hashref with the data for that facet, or an array of hashrefs. Some facets must be defined as single hashrefs, some must be defined as an array of hashrefs, No facets allow both.
`facet_data()` **MUST NOT** bless the data it returns, the main hashref, and nested facet hashrefs **MUST** be bare, though items contained within each facet may be blessed. The data returned by this method **should** also be copies of the internal data in order to prevent accidental state modification.
`facets()` takes the data from `facet_data()` and blesses it into the `Test2::EventFacet::*` packages. This is rarely used however, the EventFacet packages are primarily for convenience and documentation. The EventFacet classes are not used at all internally, instead the raw data is used.
Here is a list of facet types by package. The packages are not used internally, but are where the documentation for each type is kept.
**Note:** Every single facet type has the `'details'` field. This field is always intended for human consumption, and when provided, should explain the 'why' for the facet. All other fields are facet specific.
about => {...} <Test2::EventFacet::About>
This contains information about the event itself such as the event package name. The `details` field for this facet is an overall summary of the event.
assert => {...} <Test2::EventFacet::Assert>
This facet is used if an assertion was made. The `details` field of this facet is the description of the assertion.
control => {...} <Test2::EventFacet::Control>
This facet is used to tell the <Test2::Event::Hub> about special actions the event causes. Things like halting all testing, terminating the current test, etc. In this facet the `details` field explains why any special action was taken.
**Note:** This is how bail-out is implemented.
meta => {...} <Test2::EventFacet::Meta>
The meta facet contains all the meta-data attached to the event. In this case the `details` field has no special meaning, but may be present if something sets the 'details' meta-key on the event.
parent => {...} <Test2::EventFacet::Parent>
This facet contains nested events and similar details for subtests. In this facet the `details` field will typically be the name of the subtest.
plan => {...} <Test2::EventFacet::Plan>
This facet tells the system that a plan has been set. The `details` field of this is usually left empty, but when present explains why the plan is what it is, this is most useful if the plan is to skip-all.
trace => {...} <Test2::EventFacet::Trace>
This facet contains information related to when and where the event was generated. This is how the test file and line number of a failure is known. This facet can also help you to tell if tests are related.
In this facet the `details` field overrides the "failed at test\_file.t line 42." message provided on assertion failure.
amnesty => [{...}, ...] <Test2::EventFacet::Amnesty>
The amnesty facet is a list instead of a single item, this is important as amnesty can come from multiple places at once.
For each instance of amnesty the `details` field explains why amnesty was granted.
**Note:** Outside of formatters amnesty only acts to forgive a failing assertion.
errors => [{...}, ...] <Test2::EventFacet::Error>
The errors facet is a list instead of a single item, any number of errors can be listed. In this facet `details` describes the error, or may contain the raw error message itself (such as an exception). In perl exception may be blessed objects, as such the raw data for this facet may contain nested items which are blessed.
Not all errors are considered fatal, there is a `fail` field that must be set for an error to cause the test to fail.
**Note:** This facet is unique in that the field name is 'errors' while the package is 'Error'. This is because this is the only facet type that is both a list, and has a name where the plural is not the same as the singular. This may cause some confusion, but I feel it will be less confusing than the alternative.
info => [{...}, ...] <Test2::EventFacet::Info>
The 'info' facet is a list instead of a single item, any quantity of extra information can be attached to an event. Some information may be critical diagnostics, others may be simply commentary in nature, this is determined by the `debug` flag.
For this facet the `details` flag is the info itself. This info may be a string, or it may be a data structure to display. This is one of the few facet types that may contain blessed items.
###
LEGACY API
$bool = $e->causes\_fail Returns true if this event should result in a test failure. In general this should be false.
$bool = $e->increments\_count Should be true if this event should result in a test count increment.
$e->callback($hub) If your event needs to have extra effects on the <Test2::Hub> you can override this method.
This is called **BEFORE** your event is passed to the formatter.
$num = $e->nested If this event is nested inside of other events, this should be the depth of nesting. (This is mainly for subtests)
$bool = $e->global Set this to true if your event is global, that is ALL threads and processes should see it no matter when or where it is generated. This is not a common thing to want, it is used by bail-out and skip\_all to end testing.
$code = $e->terminate This is called **AFTER** your event has been passed to the formatter. This should normally return undef, only change this if your event should cause the test to exit immediately.
If you want this event to cause the test to exit you should return the exit code here. Exit code of 0 means exit success, any other integer means exit with failure.
This is used by <Test2::Event::Plan> to exit 0 when the plan is 'skip\_all'. This is also used by <Test2::Event:Bail> to force the test to exit with a failure.
This is called after the event has been sent to the formatter in order to ensure the event is seen and understood.
$msg = $e->summary This is intended to be a human readable summary of the event. This should ideally only be one line long, but you can use multiple lines if necessary. This is intended for human consumption. You do not need to make it easy for machines to understand.
The default is to simply return the event package name.
($count, $directive, $reason) = $e->sets\_plan() Check if this event sets the testing plan. It will return an empty list if it does not. If it does set the plan it will return a list of 1 to 3 items in order: Expected Test Count, Test Directive, Reason for directive.
$bool = $e->diagnostics True if the event contains diagnostics info. This is useful because a non-verbose harness may choose to hide events that are not in this category. Some formatters may choose to send these to STDERR instead of STDOUT to ensure they are seen.
$bool = $e->no\_display False by default. This will return true on events that should not be displayed by formatters.
$id = $e->in\_subtest If the event is inside a subtest this should have the subtest ID.
$id = $e->subtest\_id If the event is a final subtest event, this should contain the subtest ID.
THIRD PARTY META-DATA
----------------------
This object consumes <Test2::Util::ExternalMeta> which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Math::BigInt::Lib Math::BigInt::Lib
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [General Notes](#General-Notes)
- [API version](#API-version)
- [Constructors](#Constructors)
- [Mathematical functions](#Mathematical-functions)
- [Bitwise operators](#Bitwise-operators)
- [Boolean operators](#Boolean-operators)
- [String conversion](#String-conversion)
- [Numeric conversion](#Numeric-conversion)
- [Miscellaneous](#Miscellaneous)
+ [API version 2](#API-version-2)
- [Constructors](#Constructors1)
- [Mathematical functions](#Mathematical-functions1)
- [Miscellaneous](#Miscellaneous1)
* [WRAP YOUR OWN](#WRAP-YOUR-OWN)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [LICENSE](#LICENSE)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Math::BigInt::Lib - virtual parent class for Math::BigInt libraries
SYNOPSIS
--------
```
# In the backend library for Math::BigInt et al.
package Math::BigInt::MyBackend;
use Math::BigInt::Lib;
our @ISA = qw< Math::BigInt::Lib >;
sub _new { ... }
sub _str { ... }
sub _add { ... }
str _sub { ... }
...
# In your main program.
use Math::BigInt lib => 'MyBackend';
```
DESCRIPTION
-----------
This module provides support for big integer calculations. It is not intended to be used directly, but rather as a parent class for backend libraries used by Math::BigInt, Math::BigFloat, Math::BigRat, and related modules.
Other backend libraries include Math::BigInt::Calc, Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
In order to allow for multiple big integer libraries, Math::BigInt was rewritten to use a plug-in library for core math routines. Any module which conforms to the API can be used by Math::BigInt by using this in your program:
```
use Math::BigInt lib => 'libname';
```
'libname' is either the long name, like 'Math::BigInt::Pari', or only the short version, like 'Pari'.
###
General Notes
A library only needs to deal with unsigned big integers. Testing of input parameter validity is done by the caller, so there is no need to worry about underflow (e.g., in `_sub()` and `_dec()`) or about division by zero (e.g., in `_div()` and `_mod()`)) or similar cases.
Some libraries use methods that don't modify their argument, and some libraries don't even use objects, but rather unblessed references. Because of this, liberary methods are always called as class methods, not instance methods:
```
$x = Class -> method($x, $y); # like this
$x = $x -> method($y); # not like this ...
$x -> method($y); # ... or like this
```
And with boolean methods
```
$bool = Class -> method($x, $y); # like this
$bool = $x -> method($y); # not like this
```
Return values are always objects, strings, Perl scalars, or true/false for comparison routines.
####
API version
CLASS->api\_version() This method is no longer used and can be omitted. Methods that are not implemented by a subclass will be inherited from this class.
#### Constructors
The following methods are mandatory: \_new(), \_str(), \_add(), and \_sub(). However, computations will be very slow without \_mul() and \_div().
CLASS->\_new(STR) Convert a string representing an unsigned decimal number to an object representing the same number. The input is normalized, i.e., it matches `^(0|[1-9]\d*)$`.
CLASS->\_zero() Return an object representing the number zero.
CLASS->\_one() Return an object representing the number one.
CLASS->\_two() Return an object representing the number two.
CLASS->\_ten() Return an object representing the number ten.
CLASS->\_from\_bin(STR) Return an object given a string representing a binary number. The input has a '0b' prefix and matches the regular expression `^0[bB](0|1[01]*)$`.
CLASS->\_from\_oct(STR) Return an object given a string representing an octal number. The input has a '0' prefix and matches the regular expression `^0[1-7]*$`.
CLASS->\_from\_hex(STR) Return an object given a string representing a hexadecimal number. The input has a '0x' prefix and matches the regular expression `^0x(0|[1-9a-fA-F][\da-fA-F]*)$`.
CLASS->\_from\_bytes(STR) Returns an object given a byte string representing the number. The byte string is in big endian byte order, so the two-byte input string "\x01\x00" should give an output value representing the number 256.
CLASS->\_from\_base(STR, BASE, COLLSEQ) Returns an object given a string STR, a base BASE, and a collation sequence COLLSEQ. Each character in STR represents a numerical value identical to the character's position in COLLSEQ. All characters in STR must be present in COLLSEQ.
If BASE is less than or equal to 94, and a collation sequence is not specified, the following default collation sequence is used. It contains of all the 94 printable ASCII characters except space/blank:
```
0123456789 # ASCII 48 to 57
ABCDEFGHIJKLMNOPQRSTUVWXYZ # ASCII 65 to 90
abcdefghijklmnopqrstuvwxyz # ASCII 97 to 122
!"#$%&'()*+,-./ # ASCII 33 to 47
:;<=>?@ # ASCII 58 to 64
[\]^_` # ASCII 91 to 96
{|}~ # ASCII 123 to 126
```
If the default collation sequence is used, and the BASE is less than or equal to 36, the letter case in STR is ignored.
For instance, with base 3 and collation sequence "-/|", the character "-" represents 0, "/" represents 1, and "|" represents 2. So if STR is "/|-", the output is 1 \* 3\*\*2 + 2 \* 3\*\*1 + 0 \* 3\*\*0 = 15.
The following examples show standard binary, octal, decimal, and hexadecimal conversion. All examples return 250.
```
$x = $class -> _from_base("11111010", 2)
$x = $class -> _from_base("372", 8)
$x = $class -> _from_base("250", 10)
$x = $class -> _from_base("FA", 16)
```
Some more examples, all returning 250:
```
$x = $class -> _from_base("100021", 3)
$x = $class -> _from_base("3322", 4)
$x = $class -> _from_base("2000", 5)
$x = $class -> _from_base("caaa", 5, "abcde")
$x = $class -> _from_base("42", 62)
$x = $class -> _from_base("2!", 94)
```
CLASS->\_from\_base\_num(ARRAY, BASE) Returns an object given an array of values and a base. This method is equivalent to `_from_base()`, but works on numbers in an array rather than characters in a string. Unlike `_from_base()`, all input values may be arbitrarily large.
```
$x = $class -> _from_base_num([1, 1, 0, 1], 2) # $x is 13
$x = $class -> _from_base_num([3, 125, 39], 128) # $x is 65191
```
####
Mathematical functions
CLASS->\_add(OBJ1, OBJ2) Addition. Returns the result of adding OBJ2 to OBJ1.
CLASS->\_mul(OBJ1, OBJ2) Multiplication. Returns the result of multiplying OBJ2 and OBJ1.
CLASS->\_div(OBJ1, OBJ2) Division. In scalar context, returns the quotient after dividing OBJ1 by OBJ2 and truncating the result to an integer. In list context, return the quotient and the remainder.
CLASS->\_sub(OBJ1, OBJ2, FLAG)
CLASS->\_sub(OBJ1, OBJ2) Subtraction. Returns the result of subtracting OBJ2 by OBJ1. If `flag` is false or omitted, OBJ1 might be modified. If `flag` is true, OBJ2 might be modified.
CLASS->\_sadd(OBJ1, SIGN1, OBJ2, SIGN2) Signed addition. Returns the result of adding OBJ2 with sign SIGN2 to OBJ1 with sign SIGN1.
```
($obj3, $sign3) = $class -> _sadd($obj1, $sign1, $obj2, $sign2);
```
CLASS->\_ssub(OBJ1, SIGN1, OBJ2, SIGN2) Signed subtraction. Returns the result of subtracting OBJ2 with sign SIGN2 to OBJ1 with sign SIGN1.
```
($obj3, $sign3) = $class -> _sadd($obj1, $sign1, $obj2, $sign2);
```
CLASS->\_dec(OBJ) Returns the result after decrementing OBJ by one.
CLASS->\_inc(OBJ) Returns the result after incrementing OBJ by one.
CLASS->\_mod(OBJ1, OBJ2) Returns OBJ1 modulo OBJ2, i.e., the remainder after dividing OBJ1 by OBJ2.
CLASS->\_sqrt(OBJ) Returns the square root of OBJ, truncated to an integer.
CLASS->\_root(OBJ, N) Returns the Nth root of OBJ, truncated to an integer.
CLASS->\_fac(OBJ) Returns the factorial of OBJ, i.e., the product of all positive integers up to and including OBJ.
CLASS->\_dfac(OBJ) Returns the double factorial of OBJ. If OBJ is an even integer, returns the product of all positive, even integers up to and including OBJ, i.e., 2\*4\*6\*...\*OBJ. If OBJ is an odd integer, returns the product of all positive, odd integers, i.e., 1\*3\*5\*...\*OBJ.
CLASS->\_pow(OBJ1, OBJ2) Returns OBJ1 raised to the power of OBJ2. By convention, 0\*\*0 = 1.
CLASS->\_modinv(OBJ1, OBJ2) Returns the modular multiplicative inverse, i.e., return OBJ3 so that
```
(OBJ3 * OBJ1) % OBJ2 = 1 % OBJ2
```
The result is returned as two arguments. If the modular multiplicative inverse does not exist, both arguments are undefined. Otherwise, the arguments are a number (object) and its sign ("+" or "-").
The output value, with its sign, must either be a positive value in the range 1,2,...,OBJ2-1 or the same value subtracted OBJ2. For instance, if the input arguments are objects representing the numbers 7 and 5, the method must either return an object representing the number 3 and a "+" sign, since (3\*7) % 5 = 1 % 5, or an object representing the number 2 and a "-" sign, since (-2\*7) % 5 = 1 % 5.
CLASS->\_modpow(OBJ1, OBJ2, OBJ3) Returns the modular exponentiation, i.e., (OBJ1 \*\* OBJ2) % OBJ3.
CLASS->\_rsft(OBJ, N, B) Returns the result after shifting OBJ N digits to thee right in base B. This is equivalent to performing integer division by B\*\*N and discarding the remainder, except that it might be much faster.
For instance, if the object $obj represents the hexadecimal number 0xabcde, then `_rsft($obj, 2, 16)` returns an object representing the number 0xabc. The "remainer", 0xde, is discarded and not returned.
CLASS->\_lsft(OBJ, N, B) Returns the result after shifting OBJ N digits to the left in base B. This is equivalent to multiplying by B\*\*N, except that it might be much faster.
CLASS->\_log\_int(OBJ, B) Returns the logarithm of OBJ to base BASE truncted to an integer. This method has two output arguments, the OBJECT and a STATUS. The STATUS is Perl scalar; it is 1 if OBJ is the exact result, 0 if the result was truncted to give OBJ, and undef if it is unknown whether OBJ is the exact result.
CLASS->\_gcd(OBJ1, OBJ2) Returns the greatest common divisor of OBJ1 and OBJ2.
CLASS->\_lcm(OBJ1, OBJ2) Return the least common multiple of OBJ1 and OBJ2.
CLASS->\_fib(OBJ) In scalar context, returns the nth Fibonacci number: \_fib(0) returns 0, \_fib(1) returns 1, \_fib(2) returns 1, \_fib(3) returns 2 etc. In list context, returns the Fibonacci numbers from F(0) to F(n): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
CLASS->\_lucas(OBJ) In scalar context, returns the nth Lucas number: \_lucas(0) returns 2, \_lucas(1) returns 1, \_lucas(2) returns 3, etc. In list context, returns the Lucas numbers from L(0) to L(n): 2, 1, 3, 4, 7, 11, 18, 29,47, 76, ...
####
Bitwise operators
CLASS->\_and(OBJ1, OBJ2) Returns bitwise and.
CLASS->\_or(OBJ1, OBJ2) Returns bitwise or.
CLASS->\_xor(OBJ1, OBJ2) Returns bitwise exclusive or.
CLASS->\_sand(OBJ1, OBJ2, SIGN1, SIGN2) Returns bitwise signed and.
CLASS->\_sor(OBJ1, OBJ2, SIGN1, SIGN2) Returns bitwise signed or.
CLASS->\_sxor(OBJ1, OBJ2, SIGN1, SIGN2) Returns bitwise signed exclusive or.
####
Boolean operators
CLASS->\_is\_zero(OBJ) Returns a true value if OBJ is zero, and false value otherwise.
CLASS->\_is\_one(OBJ) Returns a true value if OBJ is one, and false value otherwise.
CLASS->\_is\_two(OBJ) Returns a true value if OBJ is two, and false value otherwise.
CLASS->\_is\_ten(OBJ) Returns a true value if OBJ is ten, and false value otherwise.
CLASS->\_is\_even(OBJ) Return a true value if OBJ is an even integer, and a false value otherwise.
CLASS->\_is\_odd(OBJ) Return a true value if OBJ is an even integer, and a false value otherwise.
CLASS->\_acmp(OBJ1, OBJ2) Compare OBJ1 and OBJ2 and return -1, 0, or 1, if OBJ1 is numerically less than, equal to, or larger than OBJ2, respectively.
####
String conversion
CLASS->\_str(OBJ) Returns a string representing OBJ in decimal notation. The returned string should have no leading zeros, i.e., it should match `^(0|[1-9]\d*)$`.
CLASS->\_to\_bin(OBJ) Returns the binary string representation of OBJ.
CLASS->\_to\_oct(OBJ) Returns the octal string representation of the number.
CLASS->\_to\_hex(OBJ) Returns the hexadecimal string representation of the number.
CLASS->\_to\_bytes(OBJ) Returns a byte string representation of OBJ. The byte string is in big endian byte order, so if OBJ represents the number 256, the output should be the two-byte string "\x01\x00".
CLASS->\_to\_base(OBJ, BASE, COLLSEQ) Returns a string representation of OBJ in base BASE with collation sequence COLLSEQ.
```
$val = $class -> _new("210");
$str = $class -> _to_base($val, 10, "xyz") # $str is "zyx"
$val = $class -> _new("32");
$str = $class -> _to_base($val, 2, "-|") # $str is "|-----"
```
See \_from\_base() for more information.
CLASS->\_to\_base\_num(OBJ, BASE) Converts the given number to the given base. This method is equivalent to `_to_base()`, but returns numbers in an array rather than characters in a string. In the output, the first element is the most significant. Unlike `_to_base()`, all input values may be arbitrarily large.
```
$x = $class -> _to_base_num(13, 2) # $x is [1, 1, 0, 1]
$x = $class -> _to_base_num(65191, 128) # $x is [3, 125, 39]
```
CLASS->\_as\_bin(OBJ) Like `_to_bin()` but with a '0b' prefix.
CLASS->\_as\_oct(OBJ) Like `_to_oct()` but with a '0' prefix.
CLASS->\_as\_hex(OBJ) Like `_to_hex()` but with a '0x' prefix.
CLASS->\_as\_bytes(OBJ) This is an alias to `_to_bytes()`.
####
Numeric conversion
CLASS->\_num(OBJ) Returns a Perl scalar number representing the number OBJ as close as possible. Since Perl scalars have limited precision, the returned value might not be exactly the same as OBJ.
#### Miscellaneous
CLASS->\_copy(OBJ) Returns a true copy OBJ.
CLASS->\_len(OBJ) Returns the number of the decimal digits in OBJ. The output is a Perl scalar.
CLASS->\_zeros(OBJ) Returns the number of trailing decimal zeros. The output is a Perl scalar. The number zero has no trailing decimal zeros.
CLASS->\_digit(OBJ, N) Returns the Nth digit in OBJ as a Perl scalar. N is a Perl scalar, where zero refers to the rightmost (least significant) digit, and negative values count from the left (most significant digit). If $obj represents the number 123, then
```
CLASS->_digit($obj, 0) # returns 3
CLASS->_digit($obj, 1) # returns 2
CLASS->_digit($obj, 2) # returns 1
CLASS->_digit($obj, -1) # returns 1
```
CLASS->\_digitsum(OBJ) Returns the sum of the base 10 digits.
CLASS->\_check(OBJ) Returns true if the object is invalid and false otherwise. Preferably, the true value is a string describing the problem with the object. This is a check routine to test the internal state of the object for corruption.
CLASS->\_set(OBJ) xxx
###
API version 2
The following methods are required for an API version of 2 or greater.
#### Constructors
CLASS->\_1ex(N) Return an object representing the number 10\*\*N where N >= 0 is a Perl scalar.
####
Mathematical functions
CLASS->\_nok(OBJ1, OBJ2) Return the binomial coefficient OBJ1 over OBJ1.
#### Miscellaneous
CLASS->\_alen(OBJ) Return the approximate number of decimal digits of the object. The output is a Perl scalar.
WRAP YOUR OWN
--------------
If you want to port your own favourite C library for big numbers to the Math::BigInt interface, you can take any of the already existing modules as a rough guideline. You should really wrap up the latest Math::BigInt and Math::BigFloat testsuites with your module, and replace in them any of the following:
```
use Math::BigInt;
```
by this:
```
use Math::BigInt lib => 'yourlib';
```
This way you ensure that your library really works 100% within Math::BigInt.
BUGS
----
Please report any bugs or feature requests to `bug-math-bigint at rt.cpan.org`, or through the web interface at <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
-------
You can find documentation for this module with the perldoc command.
```
perldoc Math::BigInt::Calc
```
You can also look for information at:
* RT: CPAN's request tracker
<https://rt.cpan.org/Public/Dist/Display.html?Name=Math-BigInt>
* AnnoCPAN: Annotated CPAN documentation
<http://annocpan.org/dist/Math-BigInt>
* CPAN Ratings
<https://cpanratings.perl.org/dist/Math-BigInt>
* MetaCPAN
<https://metacpan.org/release/Math-BigInt>
* CPAN Testers Matrix
<http://matrix.cpantesters.org/?dist=Math-BigInt>
* The Bignum mailing list
+ Post to mailing list
`bignum at lists.scsys.co.uk`
+ View mailing list
<http://lists.scsys.co.uk/pipermail/bignum/>
+ Subscribe/Unsubscribe
<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum>
LICENSE
-------
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
AUTHOR
------
Peter John Acklam, <[email protected]>
Code and documentation based on the Math::BigInt::Calc module by Tels <[email protected]>
SEE ALSO
---------
<Math::BigInt>, <Math::BigInt::Calc>, <Math::BigInt::GMP>, <Math::BigInt::FastCalc> and <Math::BigInt::Pari>.
| programming_docs |
perl ExtUtils::MM_BeOS ExtUtils::MM\_BeOS
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::MM\_BeOS - methods to override UN\*X behaviour in ExtUtils::MakeMaker
SYNOPSIS
--------
```
use ExtUtils::MM_BeOS; # Done internally by ExtUtils::MakeMaker if needed
```
DESCRIPTION
-----------
See <ExtUtils::MM_Unix> for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics.
os\_flavor BeOS is BeOS.
init\_linker libperl.a equivalent to be linked to dynamic extensions.
perl vmsish vmsish
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
vmsish - Perl pragma to control VMS-specific language features
SYNOPSIS
--------
```
use vmsish;
use vmsish 'status'; # or '$?'
use vmsish 'exit';
use vmsish 'time';
use vmsish 'hushed';
no vmsish 'hushed';
vmsish::hushed($hush);
use vmsish;
no vmsish 'time';
```
DESCRIPTION
-----------
If no import list is supplied, all possible VMS-specific features are assumed. Currently, there are four VMS-specific features available: 'status' (a.k.a '$?'), 'exit', 'time' and 'hushed'.
If you're not running VMS, this module does nothing.
`vmsish status`
This makes `$?` and `system` return the native VMS exit status instead of emulating the POSIX exit status.
`vmsish exit`
This makes `exit 1` produce a successful exit (with status SS$\_NORMAL), instead of emulating UNIX exit(), which considers `exit 1` to indicate an error. As with the CRTL's exit() function, `exit 0` is also mapped to an exit status of SS$\_NORMAL, and any other argument to exit() is used directly as Perl's exit status.
`vmsish time`
This makes all times relative to the local time zone, instead of the default of Universal Time (a.k.a Greenwich Mean Time, or GMT).
`vmsish hushed`
This suppresses printing of VMS status messages to SYS$OUTPUT and SYS$ERROR if Perl terminates with an error status, and allows programs that are expecting "unix-style" Perl to avoid having to parse VMS error messages. It does not suppress any messages from Perl itself, just the messages generated by DCL after Perl exits. The DCL symbol $STATUS will still have the termination status, but with a high-order bit set:
EXAMPLE: $ perl -e"exit 44;" Non-hushed error exit %SYSTEM-F-ABORT, abort DCL message $ show sym $STATUS $STATUS == "%X0000002C"
```
$ perl -e"use vmsish qw(hushed); exit 44;" Hushed error exit
$ show sym $STATUS
$STATUS == "%X1000002C"
```
The 'hushed' flag has a global scope during compilation: the exit() or die() commands that are compiled after 'vmsish hushed' will be hushed when they are executed. Doing a "no vmsish 'hushed'" turns off the hushed flag.
The status of the hushed flag also affects output of VMS error messages from compilation errors. Again, you still get the Perl error message (and the code in $STATUS)
EXAMPLE: use vmsish 'hushed'; # turn on hushed flag use Carp; # Carp compiled hushed exit 44; # will be hushed croak('I die'); # will be hushed no vmsish 'hushed'; # turn off hushed flag exit 44; # will not be hushed croak('I die2'): # WILL be hushed, croak was compiled hushed
You can also control the 'hushed' flag at run-time, using the built-in routine vmsish::hushed(). Without argument, it returns the hushed status. Since vmsish::hushed is built-in, you do not need to "use vmsish" to call it.
EXAMPLE: if ($quiet\_exit) { vmsish::hushed(1); } print "Sssshhhh...I'm hushed...\n" if vmsish::hushed(); exit 44;
Note that an exit() or die() that is compiled 'hushed' because of "use vmsish" is not un-hushed by calling vmsish::hushed(0) at runtime.
The messages from error exits from inside the Perl core are generally more serious, and are not suppressed.
See ["Perl Modules" in perlmod](perlmod#Perl-Modules).
perl Time::HiRes Time::HiRes
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
* [C API](#C-API)
* [DIAGNOSTICS](#DIAGNOSTICS)
+ [useconds or interval more than ...](#useconds-or-interval-more-than-...)
+ [negative time not invented yet](#negative-time-not-invented-yet)
+ [internal error: useconds < 0 (unsigned ... signed ...)](#internal-error:-useconds-%3C-0-(unsigned-...-signed-...))
+ [useconds or uinterval equal to or more than 1000000](#useconds-or-uinterval-equal-to-or-more-than-1000000)
+ [unimplemented in this platform](#unimplemented-in-this-platform)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
SYNOPSIS
--------
```
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep
clock_gettime clock_getres clock_nanosleep clock
stat lstat utime);
usleep ($microseconds);
nanosleep ($nanoseconds);
ualarm ($microseconds);
ualarm ($microseconds, $interval_microseconds);
$t0 = [gettimeofday];
($seconds, $microseconds) = gettimeofday;
$elapsed = tv_interval ( $t0, [$seconds, $microseconds]);
$elapsed = tv_interval ( $t0, [gettimeofday]);
$elapsed = tv_interval ( $t0 );
use Time::HiRes qw ( time alarm sleep );
$now_fractions = time;
sleep ($floating_seconds);
alarm ($floating_seconds);
alarm ($floating_seconds, $floating_interval);
use Time::HiRes qw( setitimer getitimer );
setitimer ($which, $floating_seconds, $floating_interval );
getitimer ($which);
use Time::HiRes qw( clock_gettime clock_getres clock_nanosleep
ITIMER_REAL ITIMER_VIRTUAL ITIMER_PROF
ITIMER_REALPROF );
$realtime = clock_gettime(CLOCK_REALTIME);
$resolution = clock_getres(CLOCK_REALTIME);
clock_nanosleep(CLOCK_REALTIME, 1.5e9);
clock_nanosleep(CLOCK_REALTIME, time()*1e9 + 10e9, TIMER_ABSTIME);
my $ticktock = clock();
use Time::HiRes qw( stat lstat );
my @stat = stat("file");
my @stat = stat(FH);
my @stat = lstat("file");
use Time::HiRes qw( utime );
utime $floating_seconds, $floating_seconds, file...;
```
DESCRIPTION
-----------
The `Time::HiRes` module implements a Perl interface to the `usleep`, `nanosleep`, `ualarm`, `gettimeofday`, and `setitimer`/`getitimer` system calls, in other words, high resolution time and timers. See the ["EXAMPLES"](#EXAMPLES) section below and the test scripts for usage; see your system documentation for the description of the underlying `nanosleep` or `usleep`, `ualarm`, `gettimeofday`, and `setitimer`/`getitimer` calls.
If your system lacks `gettimeofday()` or an emulation of it you don't get `gettimeofday()` or the one-argument form of `tv_interval()`. If your system lacks all of `nanosleep()`, `usleep()`, `select()`, and `poll`, you don't get `Time::HiRes::usleep()`, `Time::HiRes::nanosleep()`, or `Time::HiRes::sleep()`. If your system lacks both `ualarm()` and `setitimer()` you don't get `Time::HiRes::ualarm()` or `Time::HiRes::alarm()`.
If you try to import an unimplemented function in the `use` statement it will fail at compile time.
If your subsecond sleeping is implemented with `nanosleep()` instead of `usleep()`, you can mix subsecond sleeping with signals since `nanosleep()` does not use signals. This, however, is not portable, and you should first check for the truth value of `&Time::HiRes::d_nanosleep` to see whether you have nanosleep, and then carefully read your `nanosleep()` C API documentation for any peculiarities.
If you are using `nanosleep` for something else than mixing sleeping with signals, give some thought to whether Perl is the tool you should be using for work requiring nanosecond accuracies.
Remember that unless you are working on a *hard realtime* system, any clocks and timers will be imprecise, especially so if you are working in a pre-emptive multiuser system. Understand the difference between *wallclock time* and process time (in UNIX-like systems the sum of *user* and *system* times). Any attempt to sleep for X seconds will most probably end up sleeping **more** than that, but don't be surprised if you end up sleeping slightly **less**.
The following functions can be imported from this module. No functions are exported by default.
gettimeofday () In array context returns a two-element array with the seconds and microseconds since the epoch. In scalar context returns floating seconds like `Time::HiRes::time()` (see below).
usleep ( $useconds ) Sleeps for the number of microseconds (millionths of a second) specified. Returns the number of microseconds actually slept. Can sleep for more than one second, unlike the `usleep` system call. Can also sleep for zero seconds, which often works like a *thread yield*. See also [`Time::HiRes::sleep()`](#sleep-%28-%24floating_seconds-%29), and [`clock_nanosleep()`](#clock_nanosleep-%28-%24which%2C-%24nanoseconds%2C-%24flags-%3D-0%29).
Do not expect usleep() to be exact down to one microsecond.
nanosleep ( $nanoseconds ) Sleeps for the number of nanoseconds (1e9ths of a second) specified. Returns the number of nanoseconds actually slept (accurate only to microseconds, the nearest thousand of them). Can sleep for more than one second. Can also sleep for zero seconds, which often works like a *thread yield*. See also [`Time::HiRes::sleep()`](#sleep-%28-%24floating_seconds-%29), [`Time::HiRes::usleep()`](#usleep-%28-%24useconds-%29), and [`clock_nanosleep()`](#clock_nanosleep-%28-%24which%2C-%24nanoseconds%2C-%24flags-%3D-0%29).
Do not expect nanosleep() to be exact down to one nanosecond. Getting even accuracy of one thousand nanoseconds is good.
ualarm ( $useconds [, $interval\_useconds ] ) Issues a `ualarm` call; the `$interval_useconds` is optional and will be zero if unspecified, resulting in `alarm`-like behaviour.
Returns the remaining time in the alarm in microseconds, or `undef` if an error occurred.
ualarm(0) will cancel an outstanding ualarm().
Note that the interaction between alarms and sleeps is unspecified.
tv\_interval tv\_interval ( $ref\_to\_gettimeofday [, $ref\_to\_later\_gettimeofday] )
Returns the floating seconds between the two times, which should have been returned by `gettimeofday()`. If the second argument is omitted, then the current time is used.
time () Returns a floating seconds since the epoch. This function can be imported, resulting in a nice drop-in replacement for the `time` provided with core Perl; see the ["EXAMPLES"](#EXAMPLES) below.
**NOTE 1**: This higher resolution timer can return values either less or more than the core `time()`, depending on whether your platform rounds the higher resolution timer values up, down, or to the nearest second to get the core `time()`, but naturally the difference should be never more than half a second. See also ["clock\_getres"](#clock_getres), if available in your system.
**NOTE 2**: Since Sunday, September 9th, 2001 at 01:46:40 AM GMT, when the `time()` seconds since epoch rolled over to 1\_000\_000\_000, the default floating point format of Perl and the seconds since epoch have conspired to produce an apparent bug: if you print the value of `Time::HiRes::time()` you seem to be getting only five decimals, not six as promised (microseconds). Not to worry, the microseconds are there (assuming your platform supports such granularity in the first place). What is going on is that the default floating point format of Perl only outputs 15 digits. In this case that means ten digits before the decimal separator and five after. To see the microseconds you can use either `printf`/`sprintf` with `"%.6f"`, or the `gettimeofday()` function in list context, which will give you the seconds and microseconds as two separate values.
sleep ( $floating\_seconds ) Sleeps for the specified amount of seconds. Returns the number of seconds actually slept (a floating point value). This function can be imported, resulting in a nice drop-in replacement for the `sleep` provided with perl, see the ["EXAMPLES"](#EXAMPLES) below.
Note that the interaction between alarms and sleeps is unspecified.
alarm ( $floating\_seconds [, $interval\_floating\_seconds ] ) The `SIGALRM` signal is sent after the specified number of seconds. Implemented using `setitimer()` if available, `ualarm()` if not. The `$interval_floating_seconds` argument is optional and will be zero if unspecified, resulting in `alarm()`-like behaviour. This function can be imported, resulting in a nice drop-in replacement for the `alarm` provided with perl, see the ["EXAMPLES"](#EXAMPLES) below.
Returns the remaining time in the alarm in seconds, or `undef` if an error occurred.
**NOTE 1**: With some combinations of operating systems and Perl releases `SIGALRM` restarts `select()`, instead of interrupting it. This means that an `alarm()` followed by a `select()` may together take the sum of the times specified for the `alarm()` and the `select()`, not just the time of the `alarm()`.
Note that the interaction between alarms and sleeps is unspecified.
setitimer ( $which, $floating\_seconds [, $interval\_floating\_seconds ] ) Start up an interval timer: after a certain time, a signal ($which) arrives, and more signals may keep arriving at certain intervals. To disable an "itimer", use `$floating_seconds` of zero. If the `$interval_floating_seconds` is set to zero (or unspecified), the timer is disabled **after** the next delivered signal.
Use of interval timers may interfere with `alarm()`, `sleep()`, and `usleep()`. In standard-speak the "interaction is unspecified", which means that *anything* may happen: it may work, it may not.
In scalar context, the remaining time in the timer is returned.
In list context, both the remaining time and the interval are returned.
There are usually three or four interval timers (signals) available: the `$which` can be `ITIMER_REAL`, `ITIMER_VIRTUAL`, `ITIMER_PROF`, or `ITIMER_REALPROF`. Note that which ones are available depends: true UNIX platforms usually have the first three, but only Solaris seems to have `ITIMER_REALPROF` (which is used to profile multithreaded programs). Win32 unfortunately does not have interval timers.
`ITIMER_REAL` results in `alarm()`-like behaviour. Time is counted in *real time*; that is, wallclock time. `SIGALRM` is delivered when the timer expires.
`ITIMER_VIRTUAL` counts time in (process) *virtual time*; that is, only when the process is running. In multiprocessor/user/CPU systems this may be more or less than real or wallclock time. (This time is also known as the *user time*.) `SIGVTALRM` is delivered when the timer expires.
`ITIMER_PROF` counts time when either the process virtual time or when the operating system is running on behalf of the process (such as I/O). (This time is also known as the *system time*.) (The sum of user time and system time is known as the *CPU time*.) `SIGPROF` is delivered when the timer expires. `SIGPROF` can interrupt system calls.
The semantics of interval timers for multithreaded programs are system-specific, and some systems may support additional interval timers. For example, it is unspecified which thread gets the signals. See your [`setitimer(2)`](setitimer(2)) documentation.
getitimer ( $which ) Return the remaining time in the interval timer specified by `$which`.
In scalar context, the remaining time is returned.
In list context, both the remaining time and the interval are returned. The interval is always what you put in using `setitimer()`.
clock\_gettime ( $which ) Return as seconds the current value of the POSIX high resolution timer specified by `$which`. All implementations that support POSIX high resolution timers are supposed to support at least the `$which` value of `CLOCK_REALTIME`, which is supposed to return results close to the results of `gettimeofday`, or the number of seconds since 00:00:00:00 January 1, 1970 Greenwich Mean Time (GMT). Do not assume that CLOCK\_REALTIME is zero, it might be one, or something else. Another potentially useful (but not available everywhere) value is `CLOCK_MONOTONIC`, which guarantees a monotonically increasing time value (unlike time() or gettimeofday(), which can be adjusted). See your system documentation for other possibly supported values.
clock\_getres ( $which ) Return as seconds the resolution of the POSIX high resolution timer specified by `$which`. All implementations that support POSIX high resolution timers are supposed to support at least the `$which` value of `CLOCK_REALTIME`, see ["clock\_gettime"](#clock_gettime).
**NOTE**: the resolution returned may be highly optimistic. Even if the resolution is high (a small number), all it means is that you'll be able to specify the arguments to clock\_gettime() and clock\_nanosleep() with that resolution. The system might not actually be able to measure events at that resolution, and the various overheads and the overall system load are certain to affect any timings.
clock\_nanosleep ( $which, $nanoseconds, $flags = 0) Sleeps for the number of nanoseconds (1e9ths of a second) specified. Returns the number of nanoseconds actually slept. The $which is the "clock id", as with clock\_gettime() and clock\_getres(). The flags default to zero but `TIMER_ABSTIME` can specified (must be exported explicitly) which means that `$nanoseconds` is not a time interval (as is the default) but instead an absolute time. Can sleep for more than one second. Can also sleep for zero seconds, which often works like a *thread yield*. See also [`Time::HiRes::sleep()`](#sleep-%28-%24floating_seconds-%29), [`Time::HiRes::usleep()`](#usleep-%28-%24useconds-%29), and [`Time::HiRes::nanosleep()`](#nanosleep-%28-%24nanoseconds-%29).
Do not expect clock\_nanosleep() to be exact down to one nanosecond. Getting even accuracy of one thousand nanoseconds is good.
clock() Return as seconds the *process time* (user + system time) spent by the process since the first call to clock() (the definition is **not** "since the start of the process", though if you are lucky these times may be quite close to each other, depending on the system). What this means is that you probably need to store the result of your first call to clock(), and subtract that value from the following results of clock().
The time returned also includes the process times of the terminated child processes for which wait() has been executed. This value is somewhat like the second value returned by the times() of core Perl, but not necessarily identical. Note that due to backward compatibility limitations the returned value may wrap around at about 2147 seconds or at about 36 minutes.
stat
stat FH
stat EXPR lstat
lstat FH
lstat EXPR As ["stat" in perlfunc](perlfunc#stat) or ["lstat" in perlfunc](perlfunc#lstat) but with the access/modify/change file timestamps in subsecond resolution, if the operating system and the filesystem both support such timestamps. To override the standard stat():
```
use Time::HiRes qw(stat);
```
Test for the value of &Time::HiRes::d\_hires\_stat to find out whether the operating system supports subsecond file timestamps: a value larger than zero means yes. There are unfortunately no easy ways to find out whether the filesystem supports such timestamps. UNIX filesystems often do; NTFS does; FAT doesn't (FAT timestamp granularity is **two** seconds).
A zero return value of &Time::HiRes::d\_hires\_stat means that Time::HiRes::stat is a no-op passthrough for CORE::stat() (and likewise for lstat), and therefore the timestamps will stay integers. The same thing will happen if the filesystem does not do subsecond timestamps, even if the &Time::HiRes::d\_hires\_stat is non-zero.
In any case do not expect nanosecond resolution, or even a microsecond resolution. Also note that the modify/access timestamps might have different resolutions, and that they need not be synchronized, e.g. if the operations are
```
write
stat # t1
read
stat # t2
```
the access time stamp from t2 need not be greater-than the modify time stamp from t1: it may be equal or *less*.
utime LIST As ["utime" in perlfunc](perlfunc#utime) but with the ability to set the access/modify file timestamps in subsecond resolution, if the operating system and the filesystem, and the mount options of the filesystem, all support such timestamps.
To override the standard utime():
```
use Time::HiRes qw(utime);
```
Test for the value of &Time::HiRes::d\_hires\_utime to find out whether the operating system supports setting subsecond file timestamps.
As with CORE::utime(), passing undef as both the atime and mtime will call the syscall with a NULL argument.
The actual achievable subsecond resolution depends on the combination of the operating system and the filesystem.
Modifying the timestamps may not be possible at all: for example, the `noatime` filesystem mount option may prohibit you from changing the access time timestamp.
Returns the number of files successfully changed.
EXAMPLES
--------
```
use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
$microseconds = 750_000;
usleep($microseconds);
# signal alarm in 2.5s & every .1s thereafter
ualarm(2_500_000, 100_000);
# cancel that ualarm
ualarm(0);
# get seconds and microseconds since the epoch
($s, $usec) = gettimeofday();
# measure elapsed time
# (could also do by subtracting 2 gettimeofday return values)
$t0 = [gettimeofday];
# do bunch of stuff here
$t1 = [gettimeofday];
# do more stuff here
$t0_t1 = tv_interval $t0, $t1;
$elapsed = tv_interval ($t0, [gettimeofday]);
$elapsed = tv_interval ($t0); # equivalent code
#
# replacements for time, alarm and sleep that know about
# floating seconds
#
use Time::HiRes;
$now_fractions = Time::HiRes::time;
Time::HiRes::sleep (2.5);
Time::HiRes::alarm (10.6666666);
use Time::HiRes qw ( time alarm sleep );
$now_fractions = time;
sleep (2.5);
alarm (10.6666666);
# Arm an interval timer to go off first at 10 seconds and
# after that every 2.5 seconds, in process virtual time
use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
$SIG{VTALRM} = sub { print time, "\n" };
setitimer(ITIMER_VIRTUAL, 10, 2.5);
use Time::HiRes qw( clock_gettime clock_getres CLOCK_REALTIME );
# Read the POSIX high resolution timer.
my $high = clock_gettime(CLOCK_REALTIME);
# But how accurate we can be, really?
my $reso = clock_getres(CLOCK_REALTIME);
use Time::HiRes qw( clock_nanosleep TIMER_ABSTIME );
clock_nanosleep(CLOCK_REALTIME, 1e6);
clock_nanosleep(CLOCK_REALTIME, 2e9, TIMER_ABSTIME);
use Time::HiRes qw( clock );
my $clock0 = clock();
... # Do something.
my $clock1 = clock();
my $clockd = $clock1 - $clock0;
use Time::HiRes qw( stat );
my ($atime, $mtime, $ctime) = (stat("istics"))[8, 9, 10];
```
C API
------
In addition to the perl API described above, a C API is available for extension writers. The following C functions are available in the modglobal hash:
```
name C prototype
--------------- ----------------------
Time::NVtime NV (*)()
Time::U2time void (*)(pTHX_ UV ret[2])
```
Both functions return equivalent information (like `gettimeofday`) but with different representations. The names `NVtime` and `U2time` were selected mainly because they are operating system independent. (`gettimeofday` is Unix-centric, though some platforms like Win32 and VMS have emulations for it.)
Here is an example of using `NVtime` from C:
```
NV (*myNVtime)(); /* Returns -1 on failure. */
SV **svp = hv_fetchs(PL_modglobal, "Time::NVtime", 0);
if (!svp) croak("Time::HiRes is required");
if (!SvIOK(*svp)) croak("Time::NVtime isn't a function pointer");
myNVtime = INT2PTR(NV(*)(), SvIV(*svp));
printf("The current time is: %" NVff "\n", (*myNVtime)());
```
DIAGNOSTICS
-----------
###
useconds or interval more than ...
In ualarm() you tried to use number of microseconds or interval (also in microseconds) more than 1\_000\_000 and setitimer() is not available in your system to emulate that case.
###
negative time not invented yet
You tried to use a negative time argument.
###
internal error: useconds < 0 (unsigned ... signed ...)
Something went horribly wrong-- the number of microseconds that cannot become negative just became negative. Maybe your compiler is broken?
###
useconds or uinterval equal to or more than 1000000
In some platforms it is not possible to get an alarm with subsecond resolution and later than one second.
###
unimplemented in this platform
Some calls simply aren't available, real or emulated, on every platform.
CAVEATS
-------
Notice that the core `time()` maybe rounding rather than truncating. What this means is that the core `time()` may be reporting the time as one second later than `gettimeofday()` and `Time::HiRes::time()`.
Adjusting the system clock (either manually or by services like ntp) may cause problems, especially for long running programs that assume a monotonously increasing time (note that all platforms do not adjust time as gracefully as UNIX ntp does). For example in Win32 (and derived platforms like Cygwin and MinGW) the Time::HiRes::time() may temporarily drift off from the system clock (and the original time()) by up to 0.5 seconds. Time::HiRes will notice this eventually and recalibrate. Note that since Time::HiRes 1.77 the clock\_gettime(CLOCK\_MONOTONIC) might help in this (in case your system supports CLOCK\_MONOTONIC).
Some systems have APIs but not implementations: for example QNX and Haiku have the interval timer APIs but not the functionality.
In pre-Sierra macOS (pre-10.12, OS X) clock\_getres(), clock\_gettime() and clock\_nanosleep() are emulated using the Mach timers; as a side effect of being emulated the CLOCK\_REALTIME and CLOCK\_MONOTONIC are the same timer.
gnukfreebsd seems to have non-functional futimens() and utimensat() (at least as of 10.1): therefore the hires utime() does not work.
SEE ALSO
---------
Perl modules <BSD::Resource>, <Time::TAI64>.
Your system documentation for [`clock(3)`](clock(3)), [`clock_gettime(2)`](clock_gettime(2)), [`clock_getres(3)`](clock_getres(3)), [`clock_nanosleep(3)`](clock_nanosleep(3)), [`clock_settime(2)`](clock_settime(2)), [`getitimer(2)`](getitimer(2)), [`gettimeofday(2)`](gettimeofday(2)), [`setitimer(2)`](setitimer(2)), [`sleep(3)`](sleep(3)), [`stat(2)`](stat(2)), [`ualarm(3)`](ualarm(3)).
AUTHORS
-------
D. Wegscheid <[email protected]> R. Schertler <[email protected]> J. Hietaniemi <[email protected]> G. Aas <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 1996-2002 Douglas E. Wegscheid. All rights reserved.
Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Jarkko Hietaniemi. All rights reserved.
Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <[email protected]>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl PerlIO::mmap PerlIO::mmap
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [IMPLEMENTATION NOTE](#IMPLEMENTATION-NOTE)
NAME
----
PerlIO::mmap - Memory mapped IO
SYNOPSIS
--------
```
open my $fh, '<:mmap', $filename;
```
DESCRIPTION
-----------
This layer does `read` and `write` operations by mmap()ing the file if possible, but falls back to the default behavior if not.
IMPLEMENTATION NOTE
--------------------
`PerlIO::mmap` only exists to use XSLoader to load C code that provides support for using memory mapped IO. One does not need to explicitly `use PerlIO::mmap;`.
perl perlpodstyle perlpodstyle
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR1)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE1)
* [SEE ALSO](#SEE-ALSO1)
NAME
----
perlpodstyle - Perl POD style guide
DESCRIPTION
-----------
These are general guidelines for how to write POD documentation for Perl scripts and modules, based on general guidelines for writing good UNIX man pages. All of these guidelines are, of course, optional, but following them will make your documentation more consistent with other documentation on the system.
The name of the program being documented is conventionally written in bold (using B<>) wherever it occurs, as are all program options. Arguments should be written in italics (I<>). Function names are traditionally written in italics; if you write a function as function(), Pod::Man will take care of this for you. Literal code or commands should be in C<>. References to other man pages should be in the form `manpage(section)` or `L<manpage(section)>`, and Pod::Man will automatically format those appropriately. The second form, with L<>, is used to request that a POD formatter make a link to the man page if possible. As an exception, one normally omits the section when referring to module documentation since it's not clear what section module documentation will be in; use `L<Module::Name>` for module references instead.
References to other programs or functions are normally in the form of man page references so that cross-referencing tools can provide the user with links and the like. It's possible to overdo this, though, so be careful not to clutter your documentation with too much markup. References to other programs that are not given as man page references should be enclosed in B<>.
The major headers should be set out using a `=head1` directive, and are historically written in the rather startling ALL UPPER CASE format; this is not mandatory, but it's strongly recommended so that sections have consistent naming across different software packages. Minor headers may be included using `=head2`, and are typically in mixed case.
The standard sections of a manual page are:
NAME Mandatory section; should be a comma-separated list of programs or functions documented by this POD page, such as:
```
foo, bar - programs to do something
```
Manual page indexers are often extremely picky about the format of this section, so don't put anything in it except this line. Every program or function documented by this POD page should be listed, separated by a comma and a space. For a Perl module, just give the module name. A single dash, and only a single dash, should separate the list of programs or functions from the description. Do not use any markup such as C<> or B<> anywhere in this line. Functions should not be qualified with `()` or the like. The description should ideally fit on a single line, even if a man program replaces the dash with a few tabs.
SYNOPSIS A short usage summary for programs and functions. This section is mandatory for section 3 pages. For Perl module documentation, it's usually convenient to have the contents of this section be a verbatim block showing some (brief) examples of typical ways the module is used.
DESCRIPTION Extended description and discussion of the program or functions, or the body of the documentation for man pages that document something else. If particularly long, it's a good idea to break this up into subsections `=head2` directives like:
```
=head2 Normal Usage
=head2 Advanced Features
=head2 Writing Configuration Files
```
or whatever is appropriate for your documentation.
For a module, this is generally where the documentation of the interfaces provided by the module goes, usually in the form of a list with an `=item` for each interface. Depending on how many interfaces there are, you may want to put that documentation in separate METHODS, FUNCTIONS, CLASS METHODS, or INSTANCE METHODS sections instead and save the DESCRIPTION section for an overview.
OPTIONS Detailed description of each of the command-line options taken by the program. This should be separate from the description for the use of parsers like <Pod::Usage>. This is normally presented as a list, with each option as a separate `=item`. The specific option string should be enclosed in B<>. Any values that the option takes should be enclosed in I<>. For example, the section for the option **--section**=*manext* would be introduced with:
```
=item B<--section>=I<manext>
```
Synonymous options (like both the short and long forms) are separated by a comma and a space on the same `=item` line, or optionally listed as their own item with a reference to the canonical name. For example, since **--section** can also be written as **-s**, the above would be:
```
=item B<-s> I<manext>, B<--section>=I<manext>
```
Writing the short option first is recommended because it's easier to read. The long option is long enough to draw the eye to it anyway and the short option can otherwise get lost in visual noise.
RETURN VALUE What the program or function returns, if successful. This section can be omitted for programs whose precise exit codes aren't important, provided they return 0 on success and non-zero on failure as is standard. It should always be present for functions. For modules, it may be useful to summarize return values from the module interface here, or it may be more useful to discuss return values separately in the documentation of each function or method the module provides.
ERRORS Exceptions, error return codes, exit statuses, and errno settings. Typically used for function or module documentation; program documentation uses DIAGNOSTICS instead. The general rule of thumb is that errors printed to `STDOUT` or `STDERR` and intended for the end user are documented in DIAGNOSTICS while errors passed internal to the calling program and intended for other programmers are documented in ERRORS. When documenting a function that sets errno, a full list of the possible errno values should be given here.
DIAGNOSTICS All possible messages the program can print out and what they mean. You may wish to follow the same documentation style as the Perl documentation; see <perldiag> for more details (and look at the POD source as well).
If applicable, please include details on what the user should do to correct the error; documenting an error as indicating "the input buffer is too small" without telling the user how to increase the size of the input buffer (or at least telling them that it isn't possible) aren't very useful.
EXAMPLES Give some example uses of the program or function. Don't skimp; users often find this the most useful part of the documentation. The examples are generally given as verbatim paragraphs.
Don't just present an example without explaining what it does. Adding a short paragraph saying what the example will do can increase the value of the example immensely.
ENVIRONMENT Environment variables that the program cares about, normally presented as a list using `=over`, `=item`, and `=back`. For example:
```
=over 6
=item HOME
Used to determine the user's home directory. F<.foorc> in this
directory is read for configuration details, if it exists.
=back
```
Since environment variables are normally in all uppercase, no additional special formatting is generally needed; they're glaring enough as it is.
FILES All files used by the program or function, normally presented as a list, and what it uses them for. File names should be enclosed in F<>. It's particularly important to document files that will be potentially modified.
CAVEATS Things to take special care with, sometimes called WARNINGS.
BUGS Things that are broken or just don't work quite right.
RESTRICTIONS Bugs you don't plan to fix. :-)
NOTES Miscellaneous commentary.
AUTHOR Who wrote it (use AUTHORS for multiple people). It's a good idea to include your current e-mail address (or some e-mail address to which bug reports should be sent) or some other contact information so that users have a way of contacting you. Remember that program documentation tends to roam the wild for far longer than you expect and pick a contact method that's likely to last.
HISTORY Programs derived from other sources sometimes have this. Some people keep a modification log here, but that usually gets long and is normally better maintained in a separate file.
COPYRIGHT AND LICENSE For copyright
```
Copyright YEAR(s) YOUR NAME(s)
```
(No, (C) is not needed. No, "all rights reserved" is not needed.)
For licensing the easiest way is to use the same licensing as Perl itself:
```
This library is free software; you may redistribute it and/or
modify it under the same terms as Perl itself.
```
This makes it easy for people to use your module with Perl. Note that this licensing example is neither an endorsement or a requirement, you are of course free to choose any licensing.
SEE ALSO Other man pages to check out, like man(1), man(7), makewhatis(8), or catman(8). Normally a simple list of man pages separated by commas, or a paragraph giving the name of a reference work. Man page references, if they use the standard `name(section)` form, don't have to be enclosed in L<> (although it's recommended), but other things in this section probably should be when appropriate.
If the package has a mailing list, include a URL or subscription instructions here.
If the package has a web site, include a URL here.
Documentation of object-oriented libraries or modules may want to use CONSTRUCTORS and METHODS sections, or CLASS METHODS and INSTANCE METHODS sections, for detailed documentation of the parts of the library and save the DESCRIPTION section for an overview. Large modules with a function interface may want to use FUNCTIONS for similar reasons. Some people use OVERVIEW to summarize the description if it's quite long.
Section ordering varies, although NAME must always be the first section (you'll break some man page systems otherwise), and NAME, SYNOPSIS, DESCRIPTION, and OPTIONS generally always occur first and in that order if present. In general, SEE ALSO, AUTHOR, and similar material should be left for last. Some systems also move WARNINGS and NOTES to last. The order given above should be reasonable for most purposes.
Some systems use CONFORMING TO to note conformance to relevant standards and MT-LEVEL to note safeness for use in threaded programs or signal handlers. These headings are primarily useful when documenting parts of a C library.
Finally, as a general note, try not to use an excessive amount of markup. As documented here and in <Pod::Man>, you can safely leave Perl variables, function names, man page references, and the like unadorned by markup and the POD translators will figure it out for you. This makes it much easier to later edit the documentation. Note that many existing translators will do the wrong thing with e-mail addresses when wrapped in L<>, so don't do that.
AUTHOR
------
Russ Allbery <[email protected]>, with large portions of this documentation taken from the documentation of the original **pod2man** implementation by Larry Wall and Tom Christiansen.
COPYRIGHT AND LICENSE
----------------------
Copyright 1999, 2000, 2001, 2004, 2006, 2008, 2010, 2015, 2018 Russ Allbery <[email protected]>
Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty.
SPDX-License-Identifier: FSFAP
SEE ALSO
---------
For additional information that may be more accurate for your specific system, see either [man(5)](http://man.he.net/man5/man) or [man(7)](http://man.he.net/man7/man) depending on your system manual section numbering conventions.
This documentation is maintained as part of the podlators distribution. The current version is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>.
perl perlguts perlguts
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Variables](#Variables)
+ [Datatypes](#Datatypes)
+ [What is an "IV"?](#What-is-an-%22IV%22?)
+ [Working with SVs](#Working-with-SVs)
+ [Offsets](#Offsets)
+ [What's Really Stored in an SV?](#What's-Really-Stored-in-an-SV?)
+ [Working with AVs](#Working-with-AVs)
+ [Working with HVs](#Working-with-HVs)
+ [Hash API Extensions](#Hash-API-Extensions)
+ [AVs, HVs and undefined values](#AVs,-HVs-and-undefined-values)
+ [References](#References)
+ [Blessed References and Class Objects](#Blessed-References-and-Class-Objects)
+ [Creating New Variables](#Creating-New-Variables)
+ [Reference Counts and Mortality](#Reference-Counts-and-Mortality)
+ [Stashes and Globs](#Stashes-and-Globs)
+ [I/O Handles](#I/O-Handles)
+ [Double-Typed SVs](#Double-Typed-SVs)
+ [Read-Only Values](#Read-Only-Values)
+ [Copy on Write](#Copy-on-Write)
+ [Magic Variables](#Magic-Variables)
+ [Assigning Magic](#Assigning-Magic)
+ [Magic Virtual Tables](#Magic-Virtual-Tables)
+ [Finding Magic](#Finding-Magic)
+ [Understanding the Magic of Tied Hashes and Arrays](#Understanding-the-Magic-of-Tied-Hashes-and-Arrays)
+ [Localizing changes](#Localizing-changes)
* [Subroutines](#Subroutines)
+ [XSUBs and the Argument Stack](#XSUBs-and-the-Argument-Stack)
+ [Autoloading with XSUBs](#Autoloading-with-XSUBs)
+ [Calling Perl Routines from within C Programs](#Calling-Perl-Routines-from-within-C-Programs)
+ [Putting a C value on Perl stack](#Putting-a-C-value-on-Perl-stack)
+ [Scratchpads](#Scratchpads)
+ [Scratchpads and recursion](#Scratchpads-and-recursion)
* [Memory Allocation](#Memory-Allocation)
+ [Allocation](#Allocation)
+ [Reallocation](#Reallocation)
+ [Moving](#Moving)
* [PerlIO](#PerlIO)
* [Compiled code](#Compiled-code)
+ [Code tree](#Code-tree)
+ [Examining the tree](#Examining-the-tree)
+ [Compile pass 1: check routines](#Compile-pass-1:-check-routines)
+ [Compile pass 1a: constant folding](#Compile-pass-1a:-constant-folding)
+ [Compile pass 2: context propagation](#Compile-pass-2:-context-propagation)
+ [Compile pass 3: peephole optimization](#Compile-pass-3:-peephole-optimization)
+ [Pluggable runops](#Pluggable-runops)
+ [Compile-time scope hooks](#Compile-time-scope-hooks)
* [Examining internal data structures with the dump functions](#Examining-internal-data-structures-with-the-dump-functions)
* [How multiple interpreters and concurrency are supported](#How-multiple-interpreters-and-concurrency-are-supported)
+ [Background and MULTIPLICITY](#Background-and-MULTIPLICITY)
+ [So what happened to dTHR?](#So-what-happened-to-dTHR?)
+ [How do I use all this in extensions?](#How-do-I-use-all-this-in-extensions?)
+ [Should I do anything special if I call perl from multiple threads?](#Should-I-do-anything-special-if-I-call-perl-from-multiple-threads?)
+ [Future Plans and PERL\_IMPLICIT\_SYS](#Future-Plans-and-PERL_IMPLICIT_SYS)
* [Internal Functions](#Internal-Functions)
+ [Formatted Printing of IVs, UVs, and NVs](#Formatted-Printing-of-IVs,-UVs,-and-NVs)
+ [Formatted Printing of SVs](#Formatted-Printing-of-SVs)
+ [Formatted Printing of Strings](#Formatted-Printing-of-Strings)
+ [Formatted Printing of Size\_t and SSize\_t](#Formatted-Printing-of-Size_t-and-SSize_t)
+ [Formatted Printing of Ptrdiff\_t, intmax\_t, short and other special sizes](#Formatted-Printing-of-Ptrdiff_t,-intmax_t,-short-and-other-special-sizes)
+ [Pointer-To-Integer and Integer-To-Pointer](#Pointer-To-Integer-and-Integer-To-Pointer)
+ [Exception Handling](#Exception-Handling)
+ [Source Documentation](#Source-Documentation)
+ [Backwards compatibility](#Backwards-compatibility)
* [Unicode Support](#Unicode-Support)
+ [What is Unicode, anyway?](#What-is-Unicode,-anyway?)
+ [How can I recognise a UTF-8 string?](#How-can-I-recognise-a-UTF-8-string?)
+ [How does UTF-8 represent Unicode characters?](#How-does-UTF-8-represent-Unicode-characters?)
+ [How does Perl store UTF-8 strings?](#How-does-Perl-store-UTF-8-strings?)
+ [How do I pass a Perl string to a C library?](#How-do-I-pass-a-Perl-string-to-a-C-library?)
- [What about SvPV, SvPV\_nolen, etc.?](#What-about-SvPV,-SvPV_nolen,-etc.?)
+ [How do I convert a string to UTF-8?](#How-do-I-convert-a-string-to-UTF-8?)
+ [How do I compare strings?](#How-do-I-compare-strings?)
+ [Is there anything else I need to know?](#Is-there-anything-else-I-need-to-know?)
* [Custom Operators](#Custom-Operators)
* [Stacks](#Stacks)
+ [Value Stack](#Value-Stack)
+ [Mark Stack](#Mark-Stack)
+ [Temporaries Stack](#Temporaries-Stack)
+ [Save Stack](#Save-Stack)
+ [Scope Stack](#Scope-Stack)
* [Dynamic Scope and the Context Stack](#Dynamic-Scope-and-the-Context-Stack)
+ [Introduction to the context stack](#Introduction-to-the-context-stack)
+ [Pushing contexts](#Pushing-contexts)
+ [Popping contexts](#Popping-contexts)
+ [Redoing contexts](#Redoing-contexts)
* [Slab-based operator allocation](#Slab-based-operator-allocation)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlguts - Introduction to the Perl API
DESCRIPTION
-----------
This document attempts to describe how to use the Perl API, as well as to provide some info on the basic workings of the Perl core. It is far from complete and probably contains many errors. Please refer any questions or comments to the author below.
Variables
---------
### Datatypes
Perl has three typedefs that handle Perl's three main data types:
```
SV Scalar Value
AV Array Value
HV Hash Value
```
Each typedef has specific routines that manipulate the various data types.
###
What is an "IV"?
Perl uses a special typedef IV which is a simple signed integer type that is guaranteed to be large enough to hold a pointer (as well as an integer). Additionally, there is the UV, which is simply an unsigned IV.
Perl also uses several special typedefs to declare variables to hold integers of (at least) a given size. Use I8, I16, I32, and I64 to declare a signed integer variable which has at least as many bits as the number in its name. These all evaluate to the native C type that is closest to the given number of bits, but no smaller than that number. For example, on many platforms, a `short` is 16 bits long, and if so, I16 will evaluate to a `short`. But on platforms where a `short` isn't exactly 16 bits, Perl will use the smallest type that contains 16 bits or more.
U8, U16, U32, and U64 are to declare the corresponding unsigned integer types.
If the platform doesn't support 64-bit integers, both I64 and U64 will be undefined. Use IV and UV to declare the largest practicable, and `["WIDEST\_UTYPE" in perlapi](perlapi#WIDEST_UTYPE)` for the absolute maximum unsigned, but which may not be usable in all circumstances.
A numeric constant can be specified with ["`INT16_C`" in perlapi](perlapi#INT16_C), ["`UINTMAX_C`" in perlapi](perlapi#UINTMAX_C), and similar.
###
Working with SVs
An SV can be created and loaded with one command. There are five types of values that can be loaded: an integer value (IV), an unsigned integer value (UV), a double (NV), a string (PV), and another scalar (SV). ("PV" stands for "Pointer Value". You might think that it is misnamed because it is described as pointing only to strings. However, it is possible to have it point to other things. For example, it could point to an array of UVs. But, using it for non-strings requires care, as the underlying assumption of much of the internals is that PVs are just for strings. Often, for example, a trailing `NUL` is tacked on automatically. The non-string use is documented only in this paragraph.)
The seven routines are:
```
SV* newSViv(IV);
SV* newSVuv(UV);
SV* newSVnv(double);
SV* newSVpv(const char*, STRLEN);
SV* newSVpvn(const char*, STRLEN);
SV* newSVpvf(const char*, ...);
SV* newSVsv(SV*);
```
`STRLEN` is an integer type (`Size_t`, usually defined as `size_t` in *config.h*) guaranteed to be large enough to represent the size of any string that perl can handle.
In the unlikely case of a SV requiring more complex initialization, you can create an empty SV with newSV(len). If `len` is 0 an empty SV of type NULL is returned, else an SV of type PV is returned with len + 1 (for the `NUL`) bytes of storage allocated, accessible via SvPVX. In both cases the SV has the undef value.
```
SV *sv = newSV(0); /* no storage allocated */
SV *sv = newSV(10); /* 10 (+1) bytes of uninitialised storage
* allocated */
```
To change the value of an *already-existing* SV, there are eight routines:
```
void sv_setiv(SV*, IV);
void sv_setuv(SV*, UV);
void sv_setnv(SV*, double);
void sv_setpv(SV*, const char*);
void sv_setpvn(SV*, const char*, STRLEN)
void sv_setpvf(SV*, const char*, ...);
void sv_vsetpvfn(SV*, const char*, STRLEN, va_list *,
SV **, Size_t, bool *);
void sv_setsv(SV*, SV*);
```
Notice that you can choose to specify the length of the string to be assigned by using `sv_setpvn`, `newSVpvn`, or `newSVpv`, or you may allow Perl to calculate the length by using `sv_setpv` or by specifying 0 as the second argument to `newSVpv`. Be warned, though, that Perl will determine the string's length by using `strlen`, which depends on the string terminating with a `NUL` character, and not otherwise containing NULs.
The arguments of `sv_setpvf` are processed like `sprintf`, and the formatted output becomes the value.
`sv_vsetpvfn` is an analogue of `vsprintf`, but it allows you to specify either a pointer to a variable argument list or the address and length of an array of SVs. The last argument points to a boolean; on return, if that boolean is true, then locale-specific information has been used to format the string, and the string's contents are therefore untrustworthy (see <perlsec>). This pointer may be NULL if that information is not important. Note that this function requires you to specify the length of the format.
The `sv_set*()` functions are not generic enough to operate on values that have "magic". See ["Magic Virtual Tables"](#Magic-Virtual-Tables) later in this document.
All SVs that contain strings should be terminated with a `NUL` character. If it is not `NUL`-terminated there is a risk of core dumps and corruptions from code which passes the string to C functions or system calls which expect a `NUL`-terminated string. Perl's own functions typically add a trailing `NUL` for this reason. Nevertheless, you should be very careful when you pass a string stored in an SV to a C function or system call.
To access the actual value that an SV points to, Perl's API exposes several macros that coerce the actual scalar type into an IV, UV, double, or string:
* `SvIV(SV*)` (`IV`) and `SvUV(SV*)` (`UV`)
* `SvNV(SV*)` (`double`)
* Strings are a bit complicated:
+ Byte string: `SvPVbyte(SV*, STRLEN len)` or `SvPVbyte_nolen(SV*)`
If the Perl string is `"\xff\xff"`, then this returns a 2-byte `char*`.
This is suitable for Perl strings that represent bytes.
+ UTF-8 string: `SvPVutf8(SV*, STRLEN len)` or `SvPVutf8_nolen(SV*)`
If the Perl string is `"\xff\xff"`, then this returns a 4-byte `char*`.
This is suitable for Perl strings that represent characters.
**CAVEAT**: That `char*` will be encoded via Perl's internal UTF-8 variant, which means that if the SV contains non-Unicode code points (e.g., 0x110000), then the result may contain extensions over valid UTF-8. See ["is\_strict\_utf8\_string" in perlapi](perlapi#is_strict_utf8_string) for some methods Perl gives you to check the UTF-8 validity of these macros' returns.
+ You can also use `SvPV(SV*, STRLEN len)` or `SvPV_nolen(SV*)` to fetch the SV's raw internal buffer. This is tricky, though; if your Perl string is `"\xff\xff"`, then depending on the SV's internal encoding you might get back a 2-byte **OR** a 4-byte `char*`. Moreover, if it's the 4-byte string, that could come from either Perl `"\xff\xff"` stored UTF-8 encoded, or Perl `"\xc3\xbf\xc3\xbf"` stored as raw octets. To differentiate between these you **MUST** look up the SV's UTF8 bit (cf. `SvUTF8`) to know whether the source Perl string is 2 characters (`SvUTF8` would be on) or 4 characters (`SvUTF8` would be off).
**IMPORTANT:** Use of `SvPV`, `SvPV_nolen`, or similarly-named macros *without* looking up the SV's UTF8 bit is almost certainly a bug if non-ASCII input is allowed.
When the UTF8 bit is on, the same **CAVEAT** about UTF-8 validity applies here as for `SvPVutf8`.(See ["How do I pass a Perl string to a C library?"](#How-do-I-pass-a-Perl-string-to-a-C-library%3F) for more details.)
In `SvPVbyte`, `SvPVutf8`, and `SvPV`, the length of the `char*` returned is placed into the variable `len` (these are macros, so you do *not* use `&len`). If you do not care what the length of the data is, use `SvPVbyte_nolen`, `SvPVutf8_nolen`, or `SvPV_nolen` instead. The global variable `PL_na` can also be given to `SvPVbyte`/`SvPVutf8`/`SvPV` in this case. But that can be quite inefficient because `PL_na` must be accessed in thread-local storage in threaded Perl. In any case, remember that Perl allows arbitrary strings of data that may both contain NULs and might not be terminated by a `NUL`.
Also remember that C doesn't allow you to safely say `foo(SvPVbyte(s, len), len);`. It might work with your compiler, but it won't work for everyone. Break this sort of statement up into separate assignments:
```
SV *s;
STRLEN len;
char *ptr;
ptr = SvPVbyte(s, len);
foo(ptr, len);
```
If you want to know if the scalar value is TRUE, you can use:
```
SvTRUE(SV*)
```
Although Perl will automatically grow strings for you, if you need to force Perl to allocate more memory for your SV, you can use the macro
```
SvGROW(SV*, STRLEN newlen)
```
which will determine if more memory needs to be allocated. If so, it will call the function `sv_grow`. Note that `SvGROW` can only increase, not decrease, the allocated memory of an SV and that it does not automatically add space for the trailing `NUL` byte (perl's own string functions typically do `SvGROW(sv, len + 1)`).
If you want to write to an existing SV's buffer and set its value to a string, use SvPVbyte\_force() or one of its variants to force the SV to be a PV. This will remove any of various types of non-stringness from the SV while preserving the content of the SV in the PV. This can be used, for example, to append data from an API function to a buffer without extra copying:
```
(void)SvPVbyte_force(sv, len);
s = SvGROW(sv, len + needlen + 1);
/* something that modifies up to needlen bytes at s+len, but
modifies newlen bytes
eg. newlen = read(fd, s + len, needlen);
ignoring errors for these examples
*/
s[len + newlen] = '\0';
SvCUR_set(sv, len + newlen);
SvUTF8_off(sv);
SvSETMAGIC(sv);
```
If you already have the data in memory or if you want to keep your code simple, you can use one of the sv\_cat\*() variants, such as sv\_catpvn(). If you want to insert anywhere in the string you can use sv\_insert() or sv\_insert\_flags().
If you don't need the existing content of the SV, you can avoid some copying with:
```
SvPVCLEAR(sv);
s = SvGROW(sv, needlen + 1);
/* something that modifies up to needlen bytes at s, but modifies
newlen bytes
eg. newlen = read(fd, s, needlen);
*/
s[newlen] = '\0';
SvCUR_set(sv, newlen);
SvPOK_only(sv); /* also clears SVf_UTF8 */
SvSETMAGIC(sv);
```
Again, if you already have the data in memory or want to avoid the complexity of the above, you can use sv\_setpvn().
If you have a buffer allocated with Newx() and want to set that as the SV's value, you can use sv\_usepvn\_flags(). That has some requirements if you want to avoid perl re-allocating the buffer to fit the trailing NUL:
```
Newx(buf, somesize+1, char);
/* ... fill in buf ... */
buf[somesize] = '\0';
sv_usepvn_flags(sv, buf, somesize, SV_SMAGIC | SV_HAS_TRAILING_NUL);
/* buf now belongs to perl, don't release it */
```
If you have an SV and want to know what kind of data Perl thinks is stored in it, you can use the following macros to check the type of SV you have.
```
SvIOK(SV*)
SvNOK(SV*)
SvPOK(SV*)
```
Be aware that retrieving the numeric value of an SV can set IOK or NOK on that SV, even when the SV started as a string. Prior to Perl 5.36.0 retrieving the string value of an integer could set POK, but this can no longer occur. From 5.36.0 this can be used to distinguish the original representation of an SV and is intended to make life simpler for serializers:
```
/* references handled elsewhere */
if (SvIsBOOL(sv)) {
/* originally boolean */
...
}
else if (SvPOK(sv)) {
/* originally a string */
...
}
else if (SvNIOK(sv)) {
/* originally numeric */
...
}
else {
/* something special or undef */
}
```
You can get and set the current length of the string stored in an SV with the following macros:
```
SvCUR(SV*)
SvCUR_set(SV*, I32 val)
```
You can also get a pointer to the end of the string stored in the SV with the macro:
```
SvEND(SV*)
```
But note that these last three macros are valid only if `SvPOK()` is true.
If you want to append something to the end of string stored in an `SV*`, you can use the following functions:
```
void sv_catpv(SV*, const char*);
void sv_catpvn(SV*, const char*, STRLEN);
void sv_catpvf(SV*, const char*, ...);
void sv_vcatpvfn(SV*, const char*, STRLEN, va_list *, SV **,
I32, bool);
void sv_catsv(SV*, SV*);
```
The first function calculates the length of the string to be appended by using `strlen`. In the second, you specify the length of the string yourself. The third function processes its arguments like `sprintf` and appends the formatted output. The fourth function works like `vsprintf`. You can specify the address and length of an array of SVs instead of the va\_list argument. The fifth function extends the string stored in the first SV with the string stored in the second SV. It also forces the second SV to be interpreted as a string.
The `sv_cat*()` functions are not generic enough to operate on values that have "magic". See ["Magic Virtual Tables"](#Magic-Virtual-Tables) later in this document.
If you know the name of a scalar variable, you can get a pointer to its SV by using the following:
```
SV* get_sv("package::varname", 0);
```
This returns NULL if the variable does not exist.
If you want to know if this variable (or any other SV) is actually `defined`, you can call:
```
SvOK(SV*)
```
The scalar `undef` value is stored in an SV instance called `PL_sv_undef`.
Its address can be used whenever an `SV*` is needed. Make sure that you don't try to compare a random sv with `&PL_sv_undef`. For example when interfacing Perl code, it'll work correctly for:
```
foo(undef);
```
But won't work when called as:
```
$x = undef;
foo($x);
```
So to repeat always use SvOK() to check whether an sv is defined.
Also you have to be careful when using `&PL_sv_undef` as a value in AVs or HVs (see ["AVs, HVs and undefined values"](#AVs%2C-HVs-and-undefined-values)).
There are also the two values `PL_sv_yes` and `PL_sv_no`, which contain boolean TRUE and FALSE values, respectively. Like `PL_sv_undef`, their addresses can be used whenever an `SV*` is needed.
Do not be fooled into thinking that `(SV *) 0` is the same as `&PL_sv_undef`. Take this code:
```
SV* sv = (SV*) 0;
if (I-am-to-return-a-real-value) {
sv = sv_2mortal(newSViv(42));
}
sv_setsv(ST(0), sv);
```
This code tries to return a new SV (which contains the value 42) if it should return a real value, or undef otherwise. Instead it has returned a NULL pointer which, somewhere down the line, will cause a segmentation violation, bus error, or just weird results. Change the zero to `&PL_sv_undef` in the first line and all will be well.
To free an SV that you've created, call `SvREFCNT_dec(SV*)`. Normally this call is not necessary (see ["Reference Counts and Mortality"](#Reference-Counts-and-Mortality)).
### Offsets
Perl provides the function `sv_chop` to efficiently remove characters from the beginning of a string; you give it an SV and a pointer to somewhere inside the PV, and it discards everything before the pointer. The efficiency comes by means of a little hack: instead of actually removing the characters, `sv_chop` sets the flag `OOK` (offset OK) to signal to other functions that the offset hack is in effect, and it moves the PV pointer (called `SvPVX`) forward by the number of bytes chopped off, and adjusts `SvCUR` and `SvLEN` accordingly. (A portion of the space between the old and new PV pointers is used to store the count of chopped bytes.)
Hence, at this point, the start of the buffer that we allocated lives at `SvPVX(sv) - SvIV(sv)` in memory and the PV pointer is pointing into the middle of this allocated storage.
This is best demonstrated by example. Normally copy-on-write will prevent the substitution from operator from using this hack, but if you can craft a string for which copy-on-write is not possible, you can see it in play. In the current implementation, the final byte of a string buffer is used as a copy-on-write reference count. If the buffer is not big enough, then copy-on-write is skipped. First have a look at an empty string:
```
% ./perl -Ilib -MDevel::Peek -le '$a=""; $a .= ""; Dump $a'
SV = PV(0x7ffb7c008a70) at 0x7ffb7c030390
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0x7ffb7bc05b50 ""\0
CUR = 0
LEN = 10
```
Notice here the LEN is 10. (It may differ on your platform.) Extend the length of the string to one less than 10, and do a substitution:
```
% ./perl -Ilib -MDevel::Peek -le '$a=""; $a.="123456789"; $a=~s/.//; \
Dump($a)'
SV = PV(0x7ffa04008a70) at 0x7ffa04030390
REFCNT = 1
FLAGS = (POK,OOK,pPOK)
OFFSET = 1
PV = 0x7ffa03c05b61 ( "\1" . ) "23456789"\0
CUR = 8
LEN = 9
```
Here the number of bytes chopped off (1) is shown next as the OFFSET. The portion of the string between the "real" and the "fake" beginnings is shown in parentheses, and the values of `SvCUR` and `SvLEN` reflect the fake beginning, not the real one. (The first character of the string buffer happens to have changed to "\1" here, not "1", because the current implementation stores the offset count in the string buffer. This is subject to change.)
Something similar to the offset hack is performed on AVs to enable efficient shifting and splicing off the beginning of the array; while `AvARRAY` points to the first element in the array that is visible from Perl, `AvALLOC` points to the real start of the C array. These are usually the same, but a `shift` operation can be carried out by increasing `AvARRAY` by one and decreasing `AvFILL` and `AvMAX`. Again, the location of the real start of the C array only comes into play when freeing the array. See `av_shift` in *av.c*.
###
What's Really Stored in an SV?
Recall that the usual method of determining the type of scalar you have is to use `Sv*OK` macros. Because a scalar can be both a number and a string, usually these macros will always return TRUE and calling the `Sv*V` macros will do the appropriate conversion of string to integer/double or integer/double to string.
If you *really* need to know if you have an integer, double, or string pointer in an SV, you can use the following three macros instead:
```
SvIOKp(SV*)
SvNOKp(SV*)
SvPOKp(SV*)
```
These will tell you if you truly have an integer, double, or string pointer stored in your SV. The "p" stands for private.
There are various ways in which the private and public flags may differ. For example, in perl 5.16 and earlier a tied SV may have a valid underlying value in the IV slot (so SvIOKp is true), but the data should be accessed via the FETCH routine rather than directly, so SvIOK is false. (In perl 5.18 onwards, tied scalars use the flags the same way as untied scalars.) Another is when numeric conversion has occurred and precision has been lost: only the private flag is set on 'lossy' values. So when an NV is converted to an IV with loss, SvIOKp, SvNOKp and SvNOK will be set, while SvIOK wont be.
In general, though, it's best to use the `Sv*V` macros.
###
Working with AVs
There are two ways to create and load an AV. The first method creates an empty AV:
```
AV* newAV();
```
The second method both creates the AV and initially populates it with SVs:
```
AV* av_make(SSize_t num, SV **ptr);
```
The second argument points to an array containing `num` `SV*`'s. Once the AV has been created, the SVs can be destroyed, if so desired.
Once the AV has been created, the following operations are possible on it:
```
void av_push(AV*, SV*);
SV* av_pop(AV*);
SV* av_shift(AV*);
void av_unshift(AV*, SSize_t num);
```
These should be familiar operations, with the exception of `av_unshift`. This routine adds `num` elements at the front of the array with the `undef` value. You must then use `av_store` (described below) to assign values to these new elements.
Here are some other functions:
```
SSize_t av_top_index(AV*);
SV** av_fetch(AV*, SSize_t key, I32 lval);
SV** av_store(AV*, SSize_t key, SV* val);
```
The `av_top_index` function returns the highest index value in an array (just like $#array in Perl). If the array is empty, -1 is returned. The `av_fetch` function returns the value at index `key`, but if `lval` is non-zero, then `av_fetch` will store an undef value at that index. The `av_store` function stores the value `val` at index `key`, and does not increment the reference count of `val`. Thus the caller is responsible for taking care of that, and if `av_store` returns NULL, the caller will have to decrement the reference count to avoid a memory leak. Note that `av_fetch` and `av_store` both return `SV**`'s, not `SV*`'s as their return value.
A few more:
```
void av_clear(AV*);
void av_undef(AV*);
void av_extend(AV*, SSize_t key);
```
The `av_clear` function deletes all the elements in the AV\* array, but does not actually delete the array itself. The `av_undef` function will delete all the elements in the array plus the array itself. The `av_extend` function extends the array so that it contains at least `key+1` elements. If `key+1` is less than the currently allocated length of the array, then nothing is done.
If you know the name of an array variable, you can get a pointer to its AV by using the following:
```
AV* get_av("package::varname", 0);
```
This returns NULL if the variable does not exist.
See ["Understanding the Magic of Tied Hashes and Arrays"](#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use the array access functions on tied arrays.
###
Working with HVs
To create an HV, you use the following routine:
```
HV* newHV();
```
Once the HV has been created, the following operations are possible on it:
```
SV** hv_store(HV*, const char* key, U32 klen, SV* val, U32 hash);
SV** hv_fetch(HV*, const char* key, U32 klen, I32 lval);
```
The `klen` parameter is the length of the key being passed in (Note that you cannot pass 0 in as a value of `klen` to tell Perl to measure the length of the key). The `val` argument contains the SV pointer to the scalar being stored, and `hash` is the precomputed hash value (zero if you want `hv_store` to calculate it for you). The `lval` parameter indicates whether this fetch is actually a part of a store operation, in which case a new undefined value will be added to the HV with the supplied key and `hv_fetch` will return as if the value had already existed.
Remember that `hv_store` and `hv_fetch` return `SV**`'s and not just `SV*`. To access the scalar value, you must first dereference the return value. However, you should check to make sure that the return value is not NULL before dereferencing it.
The first of these two functions checks if a hash table entry exists, and the second deletes it.
```
bool hv_exists(HV*, const char* key, U32 klen);
SV* hv_delete(HV*, const char* key, U32 klen, I32 flags);
```
If `flags` does not include the `G_DISCARD` flag then `hv_delete` will create and return a mortal copy of the deleted value.
And more miscellaneous functions:
```
void hv_clear(HV*);
void hv_undef(HV*);
```
Like their AV counterparts, `hv_clear` deletes all the entries in the hash table but does not actually delete the hash table. The `hv_undef` deletes both the entries and the hash table itself.
Perl keeps the actual data in a linked list of structures with a typedef of HE. These contain the actual key and value pointers (plus extra administrative overhead). The key is a string pointer; the value is an `SV*`. However, once you have an `HE*`, to get the actual key and value, use the routines specified below.
```
I32 hv_iterinit(HV*);
/* Prepares starting point to traverse hash table */
HE* hv_iternext(HV*);
/* Get the next entry, and return a pointer to a
structure that has both the key and value */
char* hv_iterkey(HE* entry, I32* retlen);
/* Get the key from an HE structure and also return
the length of the key string */
SV* hv_iterval(HV*, HE* entry);
/* Return an SV pointer to the value of the HE
structure */
SV* hv_iternextsv(HV*, char** key, I32* retlen);
/* This convenience routine combines hv_iternext,
hv_iterkey, and hv_iterval. The key and retlen
arguments are return values for the key and its
length. The value is returned in the SV* argument */
```
If you know the name of a hash variable, you can get a pointer to its HV by using the following:
```
HV* get_hv("package::varname", 0);
```
This returns NULL if the variable does not exist.
The hash algorithm is defined in the `PERL_HASH` macro:
```
PERL_HASH(hash, key, klen)
```
The exact implementation of this macro varies by architecture and version of perl, and the return value may change per invocation, so the value is only valid for the duration of a single perl process.
See ["Understanding the Magic of Tied Hashes and Arrays"](#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use the hash access functions on tied hashes.
###
Hash API Extensions
Beginning with version 5.004, the following functions are also supported:
```
HE* hv_fetch_ent (HV* tb, SV* key, I32 lval, U32 hash);
HE* hv_store_ent (HV* tb, SV* key, SV* val, U32 hash);
bool hv_exists_ent (HV* tb, SV* key, U32 hash);
SV* hv_delete_ent (HV* tb, SV* key, I32 flags, U32 hash);
SV* hv_iterkeysv (HE* entry);
```
Note that these functions take `SV*` keys, which simplifies writing of extension code that deals with hash structures. These functions also allow passing of `SV*` keys to `tie` functions without forcing you to stringify the keys (unlike the previous set of functions).
They also return and accept whole hash entries (`HE*`), making their use more efficient (since the hash number for a particular string doesn't have to be recomputed every time). See <perlapi> for detailed descriptions.
The following macros must always be used to access the contents of hash entries. Note that the arguments to these macros must be simple variables, since they may get evaluated more than once. See <perlapi> for detailed descriptions of these macros.
```
HePV(HE* he, STRLEN len)
HeVAL(HE* he)
HeHASH(HE* he)
HeSVKEY(HE* he)
HeSVKEY_force(HE* he)
HeSVKEY_set(HE* he, SV* sv)
```
These two lower level macros are defined, but must only be used when dealing with keys that are not `SV*`s:
```
HeKEY(HE* he)
HeKLEN(HE* he)
```
Note that both `hv_store` and `hv_store_ent` do not increment the reference count of the stored `val`, which is the caller's responsibility. If these functions return a NULL value, the caller will usually have to decrement the reference count of `val` to avoid a memory leak.
###
AVs, HVs and undefined values
Sometimes you have to store undefined values in AVs or HVs. Although this may be a rare case, it can be tricky. That's because you're used to using `&PL_sv_undef` if you need an undefined SV.
For example, intuition tells you that this XS code:
```
AV *av = newAV();
av_store( av, 0, &PL_sv_undef );
```
is equivalent to this Perl code:
```
my @av;
$av[0] = undef;
```
Unfortunately, this isn't true. In perl 5.18 and earlier, AVs use `&PL_sv_undef` as a marker for indicating that an array element has not yet been initialized. Thus, `exists $av[0]` would be true for the above Perl code, but false for the array generated by the XS code. In perl 5.20, storing &PL\_sv\_undef will create a read-only element, because the scalar &PL\_sv\_undef itself is stored, not a copy.
Similar problems can occur when storing `&PL_sv_undef` in HVs:
```
hv_store( hv, "key", 3, &PL_sv_undef, 0 );
```
This will indeed make the value `undef`, but if you try to modify the value of `key`, you'll get the following error:
```
Modification of non-creatable hash value attempted
```
In perl 5.8.0, `&PL_sv_undef` was also used to mark placeholders in restricted hashes. This caused such hash entries not to appear when iterating over the hash or when checking for the keys with the `hv_exists` function.
You can run into similar problems when you store `&PL_sv_yes` or `&PL_sv_no` into AVs or HVs. Trying to modify such elements will give you the following error:
```
Modification of a read-only value attempted
```
To make a long story short, you can use the special variables `&PL_sv_undef`, `&PL_sv_yes` and `&PL_sv_no` with AVs and HVs, but you have to make sure you know what you're doing.
Generally, if you want to store an undefined value in an AV or HV, you should not use `&PL_sv_undef`, but rather create a new undefined value using the `newSV` function, for example:
```
av_store( av, 42, newSV(0) );
hv_store( hv, "foo", 3, newSV(0), 0 );
```
### References
References are a special type of scalar that point to other data types (including other references).
To create a reference, use either of the following functions:
```
SV* newRV_inc((SV*) thing);
SV* newRV_noinc((SV*) thing);
```
The `thing` argument can be any of an `SV*`, `AV*`, or `HV*`. The functions are identical except that `newRV_inc` increments the reference count of the `thing`, while `newRV_noinc` does not. For historical reasons, `newRV` is a synonym for `newRV_inc`.
Once you have a reference, you can use the following macro to dereference the reference:
```
SvRV(SV*)
```
then call the appropriate routines, casting the returned `SV*` to either an `AV*` or `HV*`, if required.
To determine if an SV is a reference, you can use the following macro:
```
SvROK(SV*)
```
To discover what type of value the reference refers to, use the following macro and then check the return value.
```
SvTYPE(SvRV(SV*))
```
The most useful types that will be returned are:
```
SVt_PVAV Array
SVt_PVHV Hash
SVt_PVCV Code
SVt_PVGV Glob (possibly a file handle)
```
Any numerical value returned which is less than SVt\_PVAV will be a scalar of some form.
See ["svtype" in perlapi](perlapi#svtype) for more details.
###
Blessed References and Class Objects
References are also used to support object-oriented programming. In perl's OO lexicon, an object is simply a reference that has been blessed into a package (or class). Once blessed, the programmer may now use the reference to access the various methods in the class.
A reference can be blessed into a package with the following function:
```
SV* sv_bless(SV* sv, HV* stash);
```
The `sv` argument must be a reference value. The `stash` argument specifies which class the reference will belong to. See ["Stashes and Globs"](#Stashes-and-Globs) for information on converting class names into stashes.
/\* Still under construction \*/
The following function upgrades rv to reference if not already one. Creates a new SV for rv to point to. If `classname` is non-null, the SV is blessed into the specified class. SV is returned.
```
SV* newSVrv(SV* rv, const char* classname);
```
The following three functions copy integer, unsigned integer or double into an SV whose reference is `rv`. SV is blessed if `classname` is non-null.
```
SV* sv_setref_iv(SV* rv, const char* classname, IV iv);
SV* sv_setref_uv(SV* rv, const char* classname, UV uv);
SV* sv_setref_nv(SV* rv, const char* classname, NV iv);
```
The following function copies the pointer value (*the address, not the string!*) into an SV whose reference is rv. SV is blessed if `classname` is non-null.
```
SV* sv_setref_pv(SV* rv, const char* classname, void* pv);
```
The following function copies a string into an SV whose reference is `rv`. Set length to 0 to let Perl calculate the string length. SV is blessed if `classname` is non-null.
```
SV* sv_setref_pvn(SV* rv, const char* classname, char* pv,
STRLEN length);
```
The following function tests whether the SV is blessed into the specified class. It does not check inheritance relationships.
```
int sv_isa(SV* sv, const char* name);
```
The following function tests whether the SV is a reference to a blessed object.
```
int sv_isobject(SV* sv);
```
The following function tests whether the SV is derived from the specified class. SV can be either a reference to a blessed object or a string containing a class name. This is the function implementing the `UNIVERSAL::isa` functionality.
```
bool sv_derived_from(SV* sv, const char* name);
```
To check if you've got an object derived from a specific class you have to write:
```
if (sv_isobject(sv) && sv_derived_from(sv, class)) { ... }
```
###
Creating New Variables
To create a new Perl variable with an undef value which can be accessed from your Perl script, use the following routines, depending on the variable type.
```
SV* get_sv("package::varname", GV_ADD);
AV* get_av("package::varname", GV_ADD);
HV* get_hv("package::varname", GV_ADD);
```
Notice the use of GV\_ADD as the second parameter. The new variable can now be set, using the routines appropriate to the data type.
There are additional macros whose values may be bitwise OR'ed with the `GV_ADD` argument to enable certain extra features. Those bits are:
GV\_ADDMULTI Marks the variable as multiply defined, thus preventing the:
```
Name <varname> used only once: possible typo
```
warning.
GV\_ADDWARN Issues the warning:
```
Had to create <varname> unexpectedly
```
if the variable did not exist before the function was called.
If you do not specify a package name, the variable is created in the current package.
###
Reference Counts and Mortality
Perl uses a reference count-driven garbage collection mechanism. SVs, AVs, or HVs (xV for short in the following) start their life with a reference count of 1. If the reference count of an xV ever drops to 0, then it will be destroyed and its memory made available for reuse. At the most basic internal level, reference counts can be manipulated with the following macros:
```
int SvREFCNT(SV* sv);
SV* SvREFCNT_inc(SV* sv);
void SvREFCNT_dec(SV* sv);
```
(There are also suffixed versions of the increment and decrement macros, for situations where the full generality of these basic macros can be exchanged for some performance.)
However, the way a programmer should think about references is not so much in terms of the bare reference count, but in terms of *ownership* of references. A reference to an xV can be owned by any of a variety of entities: another xV, the Perl interpreter, an XS data structure, a piece of running code, or a dynamic scope. An xV generally does not know what entities own the references to it; it only knows how many references there are, which is the reference count.
To correctly maintain reference counts, it is essential to keep track of what references the XS code is manipulating. The programmer should always know where a reference has come from and who owns it, and be aware of any creation or destruction of references, and any transfers of ownership. Because ownership isn't represented explicitly in the xV data structures, only the reference count need be actually maintained by the code, and that means that this understanding of ownership is not actually evident in the code. For example, transferring ownership of a reference from one owner to another doesn't change the reference count at all, so may be achieved with no actual code. (The transferring code doesn't touch the referenced object, but does need to ensure that the former owner knows that it no longer owns the reference, and that the new owner knows that it now does.)
An xV that is visible at the Perl level should not become unreferenced and thus be destroyed. Normally, an object will only become unreferenced when it is no longer visible, often by the same means that makes it invisible. For example, a Perl reference value (RV) owns a reference to its referent, so if the RV is overwritten that reference gets destroyed, and the no-longer-reachable referent may be destroyed as a result.
Many functions have some kind of reference manipulation as part of their purpose. Sometimes this is documented in terms of ownership of references, and sometimes it is (less helpfully) documented in terms of changes to reference counts. For example, the [newRV\_inc()](perlapi#newRV_inc) function is documented to create a new RV (with reference count 1) and increment the reference count of the referent that was supplied by the caller. This is best understood as creating a new reference to the referent, which is owned by the created RV, and returning to the caller ownership of the sole reference to the RV. The [newRV\_noinc()](perlapi#newRV_noinc) function instead does not increment the reference count of the referent, but the RV nevertheless ends up owning a reference to the referent. It is therefore implied that the caller of `newRV_noinc()` is relinquishing a reference to the referent, making this conceptually a more complicated operation even though it does less to the data structures.
For example, imagine you want to return a reference from an XSUB function. Inside the XSUB routine, you create an SV which initially has just a single reference, owned by the XSUB routine. This reference needs to be disposed of before the routine is complete, otherwise it will leak, preventing the SV from ever being destroyed. So to create an RV referencing the SV, it is most convenient to pass the SV to `newRV_noinc()`, which consumes that reference. Now the XSUB routine no longer owns a reference to the SV, but does own a reference to the RV, which in turn owns a reference to the SV. The ownership of the reference to the RV is then transferred by the process of returning the RV from the XSUB.
There are some convenience functions available that can help with the destruction of xVs. These functions introduce the concept of "mortality". Much documentation speaks of an xV itself being mortal, but this is misleading. It is really *a reference to* an xV that is mortal, and it is possible for there to be more than one mortal reference to a single xV. For a reference to be mortal means that it is owned by the temps stack, one of perl's many internal stacks, which will destroy that reference "a short time later". Usually the "short time later" is the end of the current Perl statement. However, it gets more complicated around dynamic scopes: there can be multiple sets of mortal references hanging around at the same time, with different death dates. Internally, the actual determinant for when mortal xV references are destroyed depends on two macros, SAVETMPS and FREETMPS. See <perlcall> and <perlxs> and ["Temporaries Stack"](#Temporaries-Stack) below for more details on these macros.
Mortal references are mainly used for xVs that are placed on perl's main stack. The stack is problematic for reference tracking, because it contains a lot of xV references, but doesn't own those references: they are not counted. Currently, there are many bugs resulting from xVs being destroyed while referenced by the stack, because the stack's uncounted references aren't enough to keep the xVs alive. So when putting an (uncounted) reference on the stack, it is vitally important to ensure that there will be a counted reference to the same xV that will last at least as long as the uncounted reference. But it's also important that that counted reference be cleaned up at an appropriate time, and not unduly prolong the xV's life. For there to be a mortal reference is often the best way to satisfy this requirement, especially if the xV was created especially to be put on the stack and would otherwise be unreferenced.
To create a mortal reference, use the functions:
```
SV* sv_newmortal()
SV* sv_mortalcopy(SV*)
SV* sv_2mortal(SV*)
```
`sv_newmortal()` creates an SV (with the undefined value) whose sole reference is mortal. `sv_mortalcopy()` creates an xV whose value is a copy of a supplied xV and whose sole reference is mortal. `sv_2mortal()` mortalises an existing xV reference: it transfers ownership of a reference from the caller to the temps stack. Because `sv_newmortal` gives the new SV no value, it must normally be given one via `sv_setpv`, `sv_setiv`, etc. :
```
SV *tmp = sv_newmortal();
sv_setiv(tmp, an_integer);
```
As that is multiple C statements it is quite common so see this idiom instead:
```
SV *tmp = sv_2mortal(newSViv(an_integer));
```
The mortal routines are not just for SVs; AVs and HVs can be made mortal by passing their address (type-casted to `SV*`) to the `sv_2mortal` or `sv_mortalcopy` routines.
###
Stashes and Globs
A **stash** is a hash that contains all variables that are defined within a package. Each key of the stash is a symbol name (shared by all the different types of objects that have the same name), and each value in the hash table is a GV (Glob Value). This GV in turn contains references to the various objects of that name, including (but not limited to) the following:
```
Scalar Value
Array Value
Hash Value
I/O Handle
Format
Subroutine
```
There is a single stash called `PL_defstash` that holds the items that exist in the `main` package. To get at the items in other packages, append the string "::" to the package name. The items in the `Foo` package are in the stash `Foo::` in PL\_defstash. The items in the `Bar::Baz` package are in the stash `Baz::` in `Bar::`'s stash.
To get the stash pointer for a particular package, use the function:
```
HV* gv_stashpv(const char* name, I32 flags)
HV* gv_stashsv(SV*, I32 flags)
```
The first function takes a literal string, the second uses the string stored in the SV. Remember that a stash is just a hash table, so you get back an `HV*`. The `flags` flag will create a new package if it is set to GV\_ADD.
The name that `gv_stash*v` wants is the name of the package whose symbol table you want. The default package is called `main`. If you have multiply nested packages, pass their names to `gv_stash*v`, separated by `::` as in the Perl language itself.
Alternately, if you have an SV that is a blessed reference, you can find out the stash pointer by using:
```
HV* SvSTASH(SvRV(SV*));
```
then use the following to get the package name itself:
```
char* HvNAME(HV* stash);
```
If you need to bless or re-bless an object you can use the following function:
```
SV* sv_bless(SV*, HV* stash)
```
where the first argument, an `SV*`, must be a reference, and the second argument is a stash. The returned `SV*` can now be used in the same way as any other SV.
For more information on references and blessings, consult <perlref>.
###
I/O Handles
Like AVs and HVs, IO objects are another type of non-scalar SV which may contain input and output [PerlIO](perlapio) objects or a `DIR *` from opendir().
You can create a new IO object:
```
IO* newIO();
```
Unlike other SVs, a new IO object is automatically blessed into the <IO::File> class.
The IO object contains an input and output PerlIO handle:
```
PerlIO *IoIFP(IO *io);
PerlIO *IoOFP(IO *io);
```
Typically if the IO object has been opened on a file, the input handle is always present, but the output handle is only present if the file is open for output. For a file, if both are present they will be the same PerlIO object.
Distinct input and output PerlIO objects are created for sockets and character devices.
The IO object also contains other data associated with Perl I/O handles:
```
IV IoLINES(io); /* $. */
IV IoPAGE(io); /* $% */
IV IoPAGE_LEN(io); /* $= */
IV IoLINES_LEFT(io); /* $- */
char *IoTOP_NAME(io); /* $^ */
GV *IoTOP_GV(io); /* $^ */
char *IoFMT_NAME(io); /* $~ */
GV *IoFMT_GV(io); /* $~ */
char *IoBOTTOM_NAME(io);
GV *IoBOTTOM_GV(io);
char IoTYPE(io);
U8 IoFLAGS(io);
=for apidoc_sections $io_scn, $formats_section
=for apidoc_section $reports
=for apidoc Amh|IV|IoLINES|IO *io
=for apidoc Amh|IV|IoPAGE|IO *io
=for apidoc Amh|IV|IoPAGE_LEN|IO *io
=for apidoc Amh|IV|IoLINES_LEFT|IO *io
=for apidoc Amh|char *|IoTOP_NAME|IO *io
=for apidoc Amh|GV *|IoTOP_GV|IO *io
=for apidoc Amh|char *|IoFMT_NAME|IO *io
=for apidoc Amh|GV *|IoFMT_GV|IO *io
=for apidoc Amh|char *|IoBOTTOM_NAME|IO *io
=for apidoc Amh|GV *|IoBOTTOM_GV|IO *io
=for apidoc_section $io
=for apidoc Amh|char|IoTYPE|IO *io
=for apidoc Amh|U8|IoFLAGS|IO *io
```
Most of these are involved with [formats](perlform).
IoFLAGs() may contain a combination of flags, the most interesting of which are `IOf_FLUSH` (`$|`) for autoflush and `IOf_UNTAINT`, settable with [IO::Handle's untaint() method](IO::Handle#%24io-%3Euntaint).
The IO object may also contains a directory handle:
```
DIR *IoDIRP(io);
```
suitable for use with PerlDir\_read() etc.
All of these accessors macros are lvalues, there are no distinct `_set()` macros to modify the members of the IO object.
###
Double-Typed SVs
Scalar variables normally contain only one type of value, an integer, double, pointer, or reference. Perl will automatically convert the actual scalar data from the stored type into the requested type.
Some scalar variables contain more than one type of scalar data. For example, the variable `$!` contains either the numeric value of `errno` or its string equivalent from either `strerror` or `sys_errlist[]`.
To force multiple data values into an SV, you must do two things: use the `sv_set*v` routines to add the additional scalar type, then set a flag so that Perl will believe it contains more than one type of data. The four macros to set the flags are:
```
SvIOK_on
SvNOK_on
SvPOK_on
SvROK_on
```
The particular macro you must use depends on which `sv_set*v` routine you called first. This is because every `sv_set*v` routine turns on only the bit for the particular type of data being set, and turns off all the rest.
For example, to create a new Perl variable called "dberror" that contains both the numeric and descriptive string error values, you could use the following code:
```
extern int dberror;
extern char *dberror_list;
SV* sv = get_sv("dberror", GV_ADD);
sv_setiv(sv, (IV) dberror);
sv_setpv(sv, dberror_list[dberror]);
SvIOK_on(sv);
```
If the order of `sv_setiv` and `sv_setpv` had been reversed, then the macro `SvPOK_on` would need to be called instead of `SvIOK_on`.
###
Read-Only Values
In Perl 5.16 and earlier, copy-on-write (see the next section) shared a flag bit with read-only scalars. So the only way to test whether `sv_setsv`, etc., will raise a "Modification of a read-only value" error in those versions is:
```
SvREADONLY(sv) && !SvIsCOW(sv)
```
Under Perl 5.18 and later, SvREADONLY only applies to read-only variables, and, under 5.20, copy-on-write scalars can also be read-only, so the above check is incorrect. You just want:
```
SvREADONLY(sv)
```
If you need to do this check often, define your own macro like this:
```
#if PERL_VERSION >= 18
# define SvTRULYREADONLY(sv) SvREADONLY(sv)
#else
# define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
#endif
```
###
Copy on Write
Perl implements a copy-on-write (COW) mechanism for scalars, in which string copies are not immediately made when requested, but are deferred until made necessary by one or the other scalar changing. This is mostly transparent, but one must take care not to modify string buffers that are shared by multiple SVs.
You can test whether an SV is using copy-on-write with `SvIsCOW(sv)`.
You can force an SV to make its own copy of its string buffer by calling `sv_force_normal(sv)` or SvPV\_force\_nolen(sv).
If you want to make the SV drop its string buffer, use `sv_force_normal_flags(sv, SV_COW_DROP_PV)` or simply `sv_setsv(sv, NULL)`.
All of these functions will croak on read-only scalars (see the previous section for more on those).
To test that your code is behaving correctly and not modifying COW buffers, on systems that support [mmap(2)](http://man.he.net/man2/mmap) (i.e., Unix) you can configure perl with `-Accflags=-DPERL_DEBUG_READONLY_COW` and it will turn buffer violations into crashes. You will find it to be marvellously slow, so you may want to skip perl's own tests.
###
Magic Variables
[This section still under construction. Ignore everything here. Post no bills. Everything not permitted is forbidden.]
Any SV may be magical, that is, it has special features that a normal SV does not have. These features are stored in the SV structure in a linked list of `struct magic`'s, typedef'ed to `MAGIC`.
```
struct magic {
MAGIC* mg_moremagic;
MGVTBL* mg_virtual;
U16 mg_private;
char mg_type;
U8 mg_flags;
I32 mg_len;
SV* mg_obj;
char* mg_ptr;
};
```
Note this is current as of patchlevel 0, and could change at any time.
###
Assigning Magic
Perl adds magic to an SV using the sv\_magic function:
```
void sv_magic(SV* sv, SV* obj, int how, const char* name, I32 namlen);
```
The `sv` argument is a pointer to the SV that is to acquire a new magical feature.
If `sv` is not already magical, Perl uses the `SvUPGRADE` macro to convert `sv` to type `SVt_PVMG`. Perl then continues by adding new magic to the beginning of the linked list of magical features. Any prior entry of the same type of magic is deleted. Note that this can be overridden, and multiple instances of the same type of magic can be associated with an SV.
The `name` and `namlen` arguments are used to associate a string with the magic, typically the name of a variable. `namlen` is stored in the `mg_len` field and if `name` is non-null then either a `savepvn` copy of `name` or `name` itself is stored in the `mg_ptr` field, depending on whether `namlen` is greater than zero or equal to zero respectively. As a special case, if `(name && namlen == HEf_SVKEY)` then `name` is assumed to contain an `SV*` and is stored as-is with its REFCNT incremented.
The sv\_magic function uses `how` to determine which, if any, predefined "Magic Virtual Table" should be assigned to the `mg_virtual` field. See the ["Magic Virtual Tables"](#Magic-Virtual-Tables) section below. The `how` argument is also stored in the `mg_type` field. The value of `how` should be chosen from the set of macros `PERL_MAGIC_foo` found in *perl.h*. Note that before these macros were added, Perl internals used to directly use character literals, so you may occasionally come across old code or documentation referring to 'U' magic rather than `PERL_MAGIC_uvar` for example.
The `obj` argument is stored in the `mg_obj` field of the `MAGIC` structure. If it is not the same as the `sv` argument, the reference count of the `obj` object is incremented. If it is the same, or if the `how` argument is `PERL_MAGIC_arylen`, `PERL_MAGIC_regdatum`, `PERL_MAGIC_regdata`, or if it is a NULL pointer, then `obj` is merely stored, without the reference count being incremented.
See also `sv_magicext` in <perlapi> for a more flexible way to add magic to an SV.
There is also a function to add magic to an `HV`:
```
void hv_magic(HV *hv, GV *gv, int how);
```
This simply calls `sv_magic` and coerces the `gv` argument into an `SV`.
To remove the magic from an SV, call the function sv\_unmagic:
```
int sv_unmagic(SV *sv, int type);
```
The `type` argument should be equal to the `how` value when the `SV` was initially made magical.
However, note that `sv_unmagic` removes all magic of a certain `type` from the `SV`. If you want to remove only certain magic of a `type` based on the magic virtual table, use `sv_unmagicext` instead:
```
int sv_unmagicext(SV *sv, int type, MGVTBL *vtbl);
```
###
Magic Virtual Tables
The `mg_virtual` field in the `MAGIC` structure is a pointer to an `MGVTBL`, which is a structure of function pointers and stands for "Magic Virtual Table" to handle the various operations that might be applied to that variable.
The `MGVTBL` has five (or sometimes eight) pointers to the following routine types:
```
int (*svt_get) (pTHX_ SV* sv, MAGIC* mg);
int (*svt_set) (pTHX_ SV* sv, MAGIC* mg);
U32 (*svt_len) (pTHX_ SV* sv, MAGIC* mg);
int (*svt_clear)(pTHX_ SV* sv, MAGIC* mg);
int (*svt_free) (pTHX_ SV* sv, MAGIC* mg);
int (*svt_copy) (pTHX_ SV *sv, MAGIC* mg, SV *nsv,
const char *name, I32 namlen);
int (*svt_dup) (pTHX_ MAGIC *mg, CLONE_PARAMS *param);
int (*svt_local)(pTHX_ SV *nsv, MAGIC *mg);
```
This MGVTBL structure is set at compile-time in *perl.h* and there are currently 32 types. These different structures contain pointers to various routines that perform additional actions depending on which function is being called.
```
Function pointer Action taken
---------------- ------------
svt_get Do something before the value of the SV is
retrieved.
svt_set Do something after the SV is assigned a value.
svt_len Report on the SV's length.
svt_clear Clear something the SV represents.
svt_free Free any extra storage associated with the SV.
svt_copy copy tied variable magic to a tied element
svt_dup duplicate a magic structure during thread cloning
svt_local copy magic to local value during 'local'
```
For instance, the MGVTBL structure called `vtbl_sv` (which corresponds to an `mg_type` of `PERL_MAGIC_sv`) contains:
```
{ magic_get, magic_set, magic_len, 0, 0 }
```
Thus, when an SV is determined to be magical and of type `PERL_MAGIC_sv`, if a get operation is being performed, the routine `magic_get` is called. All the various routines for the various magical types begin with `magic_`. NOTE: the magic routines are not considered part of the Perl API, and may not be exported by the Perl library.
The last three slots are a recent addition, and for source code compatibility they are only checked for if one of the three flags `MGf_COPY`, `MGf_DUP`, or `MGf_LOCAL` is set in mg\_flags. This means that most code can continue declaring a vtable as a 5-element value. These three are currently used exclusively by the threading code, and are highly subject to change.
The current kinds of Magic Virtual Tables are:
```
mg_type
(old-style char and macro) MGVTBL Type of magic
-------------------------- ------ -------------
\0 PERL_MAGIC_sv vtbl_sv Special scalar variable
# PERL_MAGIC_arylen vtbl_arylen Array length ($#ary)
% PERL_MAGIC_rhash (none) Extra data for restricted
hashes
* PERL_MAGIC_debugvar vtbl_debugvar $DB::single, signal, trace
vars
. PERL_MAGIC_pos vtbl_pos pos() lvalue
: PERL_MAGIC_symtab (none) Extra data for symbol
tables
< PERL_MAGIC_backref vtbl_backref For weak ref data
@ PERL_MAGIC_arylen_p (none) To move arylen out of XPVAV
B PERL_MAGIC_bm vtbl_regexp Boyer-Moore
(fast string search)
c PERL_MAGIC_overload_table vtbl_ovrld Holds overload table
(AMT) on stash
D PERL_MAGIC_regdata vtbl_regdata Regex match position data
(@+ and @- vars)
d PERL_MAGIC_regdatum vtbl_regdatum Regex match position data
element
E PERL_MAGIC_env vtbl_env %ENV hash
e PERL_MAGIC_envelem vtbl_envelem %ENV hash element
f PERL_MAGIC_fm vtbl_regexp Formline
('compiled' format)
g PERL_MAGIC_regex_global vtbl_mglob m//g target
H PERL_MAGIC_hints vtbl_hints %^H hash
h PERL_MAGIC_hintselem vtbl_hintselem %^H hash element
I PERL_MAGIC_isa vtbl_isa @ISA array
i PERL_MAGIC_isaelem vtbl_isaelem @ISA array element
k PERL_MAGIC_nkeys vtbl_nkeys scalar(keys()) lvalue
L PERL_MAGIC_dbfile (none) Debugger %_<filename
l PERL_MAGIC_dbline vtbl_dbline Debugger %_<filename
element
N PERL_MAGIC_shared (none) Shared between threads
n PERL_MAGIC_shared_scalar (none) Shared between threads
o PERL_MAGIC_collxfrm vtbl_collxfrm Locale transformation
P PERL_MAGIC_tied vtbl_pack Tied array or hash
p PERL_MAGIC_tiedelem vtbl_packelem Tied array or hash element
q PERL_MAGIC_tiedscalar vtbl_packelem Tied scalar or handle
r PERL_MAGIC_qr vtbl_regexp Precompiled qr// regex
S PERL_MAGIC_sig vtbl_sig %SIG hash
s PERL_MAGIC_sigelem vtbl_sigelem %SIG hash element
t PERL_MAGIC_taint vtbl_taint Taintedness
U PERL_MAGIC_uvar vtbl_uvar Available for use by
extensions
u PERL_MAGIC_uvar_elem (none) Reserved for use by
extensions
V PERL_MAGIC_vstring (none) SV was vstring literal
v PERL_MAGIC_vec vtbl_vec vec() lvalue
w PERL_MAGIC_utf8 vtbl_utf8 Cached UTF-8 information
x PERL_MAGIC_substr vtbl_substr substr() lvalue
Y PERL_MAGIC_nonelem vtbl_nonelem Array element that does not
exist
y PERL_MAGIC_defelem vtbl_defelem Shadow "foreach" iterator
variable / smart parameter
vivification
\ PERL_MAGIC_lvref vtbl_lvref Lvalue reference
constructor
] PERL_MAGIC_checkcall vtbl_checkcall Inlining/mutation of call
to this CV
~ PERL_MAGIC_ext (none) Available for use by
extensions
```
When an uppercase and lowercase letter both exist in the table, then the uppercase letter is typically used to represent some kind of composite type (a list or a hash), and the lowercase letter is used to represent an element of that composite type. Some internals code makes use of this case relationship. However, 'v' and 'V' (vec and v-string) are in no way related.
The `PERL_MAGIC_ext` and `PERL_MAGIC_uvar` magic types are defined specifically for use by extensions and will not be used by perl itself. Extensions can use `PERL_MAGIC_ext` magic to 'attach' private information to variables (typically objects). This is especially useful because there is no way for normal perl code to corrupt this private information (unlike using extra elements of a hash object).
Similarly, `PERL_MAGIC_uvar` magic can be used much like tie() to call a C function any time a scalar's value is used or changed. The `MAGIC`'s `mg_ptr` field points to a `ufuncs` structure:
```
struct ufuncs {
I32 (*uf_val)(pTHX_ IV, SV*);
I32 (*uf_set)(pTHX_ IV, SV*);
IV uf_index;
};
```
When the SV is read from or written to, the `uf_val` or `uf_set` function will be called with `uf_index` as the first arg and a pointer to the SV as the second. A simple example of how to add `PERL_MAGIC_uvar` magic is shown below. Note that the ufuncs structure is copied by sv\_magic, so you can safely allocate it on the stack.
```
void
Umagic(sv)
SV *sv;
PREINIT:
struct ufuncs uf;
CODE:
uf.uf_val = &my_get_fn;
uf.uf_set = &my_set_fn;
uf.uf_index = 0;
sv_magic(sv, 0, PERL_MAGIC_uvar, (char*)&uf, sizeof(uf));
```
Attaching `PERL_MAGIC_uvar` to arrays is permissible but has no effect.
For hashes there is a specialized hook that gives control over hash keys (but not values). This hook calls `PERL_MAGIC_uvar` 'get' magic if the "set" function in the `ufuncs` structure is NULL. The hook is activated whenever the hash is accessed with a key specified as an `SV` through the functions `hv_store_ent`, `hv_fetch_ent`, `hv_delete_ent`, and `hv_exists_ent`. Accessing the key as a string through the functions without the `..._ent` suffix circumvents the hook. See ["GUTS" in Hash::Util::FieldHash](Hash::Util::FieldHash#GUTS) for a detailed description.
Note that because multiple extensions may be using `PERL_MAGIC_ext` or `PERL_MAGIC_uvar` magic, it is important for extensions to take extra care to avoid conflict. Typically only using the magic on objects blessed into the same class as the extension is sufficient. For `PERL_MAGIC_ext` magic, it is usually a good idea to define an `MGVTBL`, even if all its fields will be `0`, so that individual `MAGIC` pointers can be identified as a particular kind of magic using their magic virtual table. `mg_findext` provides an easy way to do that:
```
STATIC MGVTBL my_vtbl = { 0, 0, 0, 0, 0, 0, 0, 0 };
MAGIC *mg;
if ((mg = mg_findext(sv, PERL_MAGIC_ext, &my_vtbl))) {
/* this is really ours, not another module's PERL_MAGIC_ext */
my_priv_data_t *priv = (my_priv_data_t *)mg->mg_ptr;
...
}
```
Also note that the `sv_set*()` and `sv_cat*()` functions described earlier do **not** invoke 'set' magic on their targets. This must be done by the user either by calling the `SvSETMAGIC()` macro after calling these functions, or by using one of the `sv_set*_mg()` or `sv_cat*_mg()` functions. Similarly, generic C code must call the `SvGETMAGIC()` macro to invoke any 'get' magic if they use an SV obtained from external sources in functions that don't handle magic. See <perlapi> for a description of these functions. For example, calls to the `sv_cat*()` functions typically need to be followed by `SvSETMAGIC()`, but they don't need a prior `SvGETMAGIC()` since their implementation handles 'get' magic.
###
Finding Magic
```
MAGIC *mg_find(SV *sv, int type); /* Finds the magic pointer of that
* type */
```
This routine returns a pointer to a `MAGIC` structure stored in the SV. If the SV does not have that magical feature, `NULL` is returned. If the SV has multiple instances of that magical feature, the first one will be returned. `mg_findext` can be used to find a `MAGIC` structure of an SV based on both its magic type and its magic virtual table:
```
MAGIC *mg_findext(SV *sv, int type, MGVTBL *vtbl);
```
Also, if the SV passed to `mg_find` or `mg_findext` is not of type SVt\_PVMG, Perl may core dump.
```
int mg_copy(SV* sv, SV* nsv, const char* key, STRLEN klen);
```
This routine checks to see what types of magic `sv` has. If the mg\_type field is an uppercase letter, then the mg\_obj is copied to `nsv`, but the mg\_type field is changed to be the lowercase letter.
###
Understanding the Magic of Tied Hashes and Arrays
Tied hashes and arrays are magical beasts of the `PERL_MAGIC_tied` magic type.
WARNING: As of the 5.004 release, proper usage of the array and hash access functions requires understanding a few caveats. Some of these caveats are actually considered bugs in the API, to be fixed in later releases, and are bracketed with [MAYCHANGE] below. If you find yourself actually applying such information in this section, be aware that the behavior may change in the future, umm, without warning.
The perl tie function associates a variable with an object that implements the various GET, SET, etc methods. To perform the equivalent of the perl tie function from an XSUB, you must mimic this behaviour. The code below carries out the necessary steps -- firstly it creates a new hash, and then creates a second hash which it blesses into the class which will implement the tie methods. Lastly it ties the two hashes together, and returns a reference to the new tied hash. Note that the code below does NOT call the TIEHASH method in the MyTie class - see ["Calling Perl Routines from within C Programs"](#Calling-Perl-Routines-from-within-C-Programs) for details on how to do this.
```
SV*
mytie()
PREINIT:
HV *hash;
HV *stash;
SV *tie;
CODE:
hash = newHV();
tie = newRV_noinc((SV*)newHV());
stash = gv_stashpv("MyTie", GV_ADD);
sv_bless(tie, stash);
hv_magic(hash, (GV*)tie, PERL_MAGIC_tied);
RETVAL = newRV_noinc(hash);
OUTPUT:
RETVAL
```
The `av_store` function, when given a tied array argument, merely copies the magic of the array onto the value to be "stored", using `mg_copy`. It may also return NULL, indicating that the value did not actually need to be stored in the array. [MAYCHANGE] After a call to `av_store` on a tied array, the caller will usually need to call `mg_set(val)` to actually invoke the perl level "STORE" method on the TIEARRAY object. If `av_store` did return NULL, a call to `SvREFCNT_dec(val)` will also be usually necessary to avoid a memory leak. [/MAYCHANGE]
The previous paragraph is applicable verbatim to tied hash access using the `hv_store` and `hv_store_ent` functions as well.
`av_fetch` and the corresponding hash functions `hv_fetch` and `hv_fetch_ent` actually return an undefined mortal value whose magic has been initialized using `mg_copy`. Note the value so returned does not need to be deallocated, as it is already mortal. [MAYCHANGE] But you will need to call `mg_get()` on the returned value in order to actually invoke the perl level "FETCH" method on the underlying TIE object. Similarly, you may also call `mg_set()` on the return value after possibly assigning a suitable value to it using `sv_setsv`, which will invoke the "STORE" method on the TIE object. [/MAYCHANGE]
[MAYCHANGE] In other words, the array or hash fetch/store functions don't really fetch and store actual values in the case of tied arrays and hashes. They merely call `mg_copy` to attach magic to the values that were meant to be "stored" or "fetched". Later calls to `mg_get` and `mg_set` actually do the job of invoking the TIE methods on the underlying objects. Thus the magic mechanism currently implements a kind of lazy access to arrays and hashes.
Currently (as of perl version 5.004), use of the hash and array access functions requires the user to be aware of whether they are operating on "normal" hashes and arrays, or on their tied variants. The API may be changed to provide more transparent access to both tied and normal data types in future versions. [/MAYCHANGE]
You would do well to understand that the TIEARRAY and TIEHASH interfaces are mere sugar to invoke some perl method calls while using the uniform hash and array syntax. The use of this sugar imposes some overhead (typically about two to four extra opcodes per FETCH/STORE operation, in addition to the creation of all the mortal variables required to invoke the methods). This overhead will be comparatively small if the TIE methods are themselves substantial, but if they are only a few statements long, the overhead will not be insignificant.
###
Localizing changes
Perl has a very handy construction
```
{
local $var = 2;
...
}
```
This construction is *approximately* equivalent to
```
{
my $oldvar = $var;
$var = 2;
...
$var = $oldvar;
}
```
The biggest difference is that the first construction would reinstate the initial value of $var, irrespective of how control exits the block: `goto`, `return`, `die`/`eval`, etc. It is a little bit more efficient as well.
There is a way to achieve a similar task from C via Perl API: create a *pseudo-block*, and arrange for some changes to be automatically undone at the end of it, either explicit, or via a non-local exit (via die()). A *block*-like construct is created by a pair of `ENTER`/`LEAVE` macros (see ["Returning a Scalar" in perlcall](perlcall#Returning-a-Scalar)). Such a construct may be created specially for some important localized task, or an existing one (like boundaries of enclosing Perl subroutine/block, or an existing pair for freeing TMPs) may be used. (In the second case the overhead of additional localization must be almost negligible.) Note that any XSUB is automatically enclosed in an `ENTER`/`LEAVE` pair.
Inside such a *pseudo-block* the following service is available:
`SAVEINT(int i)`
`SAVEIV(IV i)`
`SAVEI32(I32 i)`
`SAVELONG(long i)`
`SAVEI8(I8 i)`
`SAVEI16(I16 i)`
`SAVEBOOL(int i)`
`SAVESTRLEN(STRLEN i)`
These macros arrange things to restore the value of integer variable `i` at the end of the enclosing *pseudo-block*.
`SAVESPTR(s)`
`SAVEPPTR(p)`
These macros arrange things to restore the value of pointers `s` and `p`. `s` must be a pointer of a type which survives conversion to `SV*` and back, `p` should be able to survive conversion to `char*` and back.
`SAVEFREESV(SV *sv)`
The refcount of `sv` will be decremented at the end of *pseudo-block*. This is similar to `sv_2mortal` in that it is also a mechanism for doing a delayed `SvREFCNT_dec`. However, while `sv_2mortal` extends the lifetime of `sv` until the beginning of the next statement, `SAVEFREESV` extends it until the end of the enclosing scope. These lifetimes can be wildly different.
Also compare `SAVEMORTALIZESV`.
`SAVEMORTALIZESV(SV *sv)`
Just like `SAVEFREESV`, but mortalizes `sv` at the end of the current scope instead of decrementing its reference count. This usually has the effect of keeping `sv` alive until the statement that called the currently live scope has finished executing.
`SAVEFREEOP(OP *op)`
The `OP *` is op\_free()ed at the end of *pseudo-block*.
`SAVEFREEPV(p)`
The chunk of memory which is pointed to by `p` is Safefree()ed at the end of *pseudo-block*.
`SAVECLEARSV(SV *sv)`
Clears a slot in the current scratchpad which corresponds to `sv` at the end of *pseudo-block*.
`SAVEDELETE(HV *hv, char *key, I32 length)`
The key `key` of `hv` is deleted at the end of *pseudo-block*. The string pointed to by `key` is Safefree()ed. If one has a *key* in short-lived storage, the corresponding string may be reallocated like this:
```
SAVEDELETE(PL_defstash, savepv(tmpbuf), strlen(tmpbuf));
```
`SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)`
At the end of *pseudo-block* the function `f` is called with the only argument `p`.
`SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)`
At the end of *pseudo-block* the function `f` is called with the implicit context argument (if any), and `p`.
`SAVESTACK_POS()`
The current offset on the Perl internal stack (cf. `SP`) is restored at the end of *pseudo-block*.
The following API list contains functions, thus one needs to provide pointers to the modifiable data explicitly (either C pointers, or Perlish `GV *`s). Where the above macros take `int`, a similar function takes `int *`.
Other macros above have functions implementing them, but its probably best to just use the macro, and not those or the ones below.
`SV* save_scalar(GV *gv)`
Equivalent to Perl code `local $gv`.
`AV* save_ary(GV *gv)`
`HV* save_hash(GV *gv)`
Similar to `save_scalar`, but localize `@gv` and `%gv`.
`void save_item(SV *item)`
Duplicates the current value of `SV`. On the exit from the current `ENTER`/`LEAVE` *pseudo-block* the value of `SV` will be restored using the stored value. It doesn't handle magic. Use `save_scalar` if magic is affected.
`void save_list(SV **sarg, I32 maxsarg)`
A variant of `save_item` which takes multiple arguments via an array `sarg` of `SV*` of length `maxsarg`.
`SV* save_svref(SV **sptr)`
Similar to `save_scalar`, but will reinstate an `SV *`.
`void save_aptr(AV **aptr)`
`void save_hptr(HV **hptr)`
Similar to `save_svref`, but localize `AV *` and `HV *`.
The `Alias` module implements localization of the basic types within the *caller's scope*. People who are interested in how to localize things in the containing scope should take a look there too.
Subroutines
-----------
###
XSUBs and the Argument Stack
The XSUB mechanism is a simple way for Perl programs to access C subroutines. An XSUB routine will have a stack that contains the arguments from the Perl program, and a way to map from the Perl data structures to a C equivalent.
The stack arguments are accessible through the `ST(n)` macro, which returns the `n`'th stack argument. Argument 0 is the first argument passed in the Perl subroutine call. These arguments are `SV*`, and can be used anywhere an `SV*` is used.
Most of the time, output from the C routine can be handled through use of the RETVAL and OUTPUT directives. However, there are some cases where the argument stack is not already long enough to handle all the return values. An example is the POSIX tzname() call, which takes no arguments, but returns two, the local time zone's standard and summer time abbreviations.
To handle this situation, the PPCODE directive is used and the stack is extended using the macro:
```
EXTEND(SP, num);
```
where `SP` is the macro that represents the local copy of the stack pointer, and `num` is the number of elements the stack should be extended by.
Now that there is room on the stack, values can be pushed on it using `PUSHs` macro. The pushed values will often need to be "mortal" (See ["Reference Counts and Mortality"](#Reference-Counts-and-Mortality)):
```
PUSHs(sv_2mortal(newSViv(an_integer)))
PUSHs(sv_2mortal(newSVuv(an_unsigned_integer)))
PUSHs(sv_2mortal(newSVnv(a_double)))
PUSHs(sv_2mortal(newSVpv("Some String",0)))
/* Although the last example is better written as the more
* efficient: */
PUSHs(newSVpvs_flags("Some String", SVs_TEMP))
```
And now the Perl program calling `tzname`, the two values will be assigned as in:
```
($standard_abbrev, $summer_abbrev) = POSIX::tzname;
```
An alternate (and possibly simpler) method to pushing values on the stack is to use the macro:
```
XPUSHs(SV*)
```
This macro automatically adjusts the stack for you, if needed. Thus, you do not need to call `EXTEND` to extend the stack.
Despite their suggestions in earlier versions of this document the macros `(X)PUSH[iunp]` are *not* suited to XSUBs which return multiple results. For that, either stick to the `(X)PUSHs` macros shown above, or use the new `m(X)PUSH[iunp]` macros instead; see ["Putting a C value on Perl stack"](#Putting-a-C-value-on-Perl-stack).
For more information, consult <perlxs> and <perlxstut>.
###
Autoloading with XSUBs
If an AUTOLOAD routine is an XSUB, as with Perl subroutines, Perl puts the fully-qualified name of the autoloaded subroutine in the $AUTOLOAD variable of the XSUB's package.
But it also puts the same information in certain fields of the XSUB itself:
```
HV *stash = CvSTASH(cv);
const char *subname = SvPVX(cv);
STRLEN name_length = SvCUR(cv); /* in bytes */
U32 is_utf8 = SvUTF8(cv);
```
`SvPVX(cv)` contains just the sub name itself, not including the package. For an AUTOLOAD routine in UNIVERSAL or one of its superclasses, `CvSTASH(cv)` returns NULL during a method call on a nonexistent package.
**Note**: Setting $AUTOLOAD stopped working in 5.6.1, which did not support XS AUTOLOAD subs at all. Perl 5.8.0 introduced the use of fields in the XSUB itself. Perl 5.16.0 restored the setting of $AUTOLOAD. If you need to support 5.8-5.14, use the XSUB's fields.
###
Calling Perl Routines from within C Programs
There are four routines that can be used to call a Perl subroutine from within a C program. These four are:
```
I32 call_sv(SV*, I32);
I32 call_pv(const char*, I32);
I32 call_method(const char*, I32);
I32 call_argv(const char*, I32, char**);
```
The routine most often used is `call_sv`. The `SV*` argument contains either the name of the Perl subroutine to be called, or a reference to the subroutine. The second argument consists of flags that control the context in which the subroutine is called, whether or not the subroutine is being passed arguments, how errors should be trapped, and how to treat return values.
All four routines return the number of arguments that the subroutine returned on the Perl stack.
These routines used to be called `perl_call_sv`, etc., before Perl v5.6.0, but those names are now deprecated; macros of the same name are provided for compatibility.
When using any of these routines (except `call_argv`), the programmer must manipulate the Perl stack. These include the following macros and functions:
```
dSP
SP
PUSHMARK()
PUTBACK
SPAGAIN
ENTER
SAVETMPS
FREETMPS
LEAVE
XPUSH*()
POP*()
```
For a detailed description of calling conventions from C to Perl, consult <perlcall>.
###
Putting a C value on Perl stack
A lot of opcodes (this is an elementary operation in the internal perl stack machine) put an SV\* on the stack. However, as an optimization the corresponding SV is (usually) not recreated each time. The opcodes reuse specially assigned SVs (*target*s) which are (as a corollary) not constantly freed/created.
Each of the targets is created only once (but see ["Scratchpads and recursion"](#Scratchpads-and-recursion) below), and when an opcode needs to put an integer, a double, or a string on stack, it just sets the corresponding parts of its *target* and puts the *target* on stack.
The macro to put this target on stack is `PUSHTARG`, and it is directly used in some opcodes, as well as indirectly in zillions of others, which use it via `(X)PUSH[iunp]`.
Because the target is reused, you must be careful when pushing multiple values on the stack. The following code will not do what you think:
```
XPUSHi(10);
XPUSHi(20);
```
This translates as "set `TARG` to 10, push a pointer to `TARG` onto the stack; set `TARG` to 20, push a pointer to `TARG` onto the stack". At the end of the operation, the stack does not contain the values 10 and 20, but actually contains two pointers to `TARG`, which we have set to 20.
If you need to push multiple different values then you should either use the `(X)PUSHs` macros, or else use the new `m(X)PUSH[iunp]` macros, none of which make use of `TARG`. The `(X)PUSHs` macros simply push an SV\* on the stack, which, as noted under ["XSUBs and the Argument Stack"](#XSUBs-and-the-Argument-Stack), will often need to be "mortal". The new `m(X)PUSH[iunp]` macros make this a little easier to achieve by creating a new mortal for you (via `(X)PUSHmortal`), pushing that onto the stack (extending it if necessary in the case of the `mXPUSH[iunp]` macros), and then setting its value. Thus, instead of writing this to "fix" the example above:
```
XPUSHs(sv_2mortal(newSViv(10)))
XPUSHs(sv_2mortal(newSViv(20)))
```
you can simply write:
```
mXPUSHi(10)
mXPUSHi(20)
```
On a related note, if you do use `(X)PUSH[iunp]`, then you're going to need a `dTARG` in your variable declarations so that the `*PUSH*` macros can make use of the local variable `TARG`. See also `dTARGET` and `dXSTARG`.
### Scratchpads
The question remains on when the SVs which are *target*s for opcodes are created. The answer is that they are created when the current unit--a subroutine or a file (for opcodes for statements outside of subroutines)--is compiled. During this time a special anonymous Perl array is created, which is called a scratchpad for the current unit.
A scratchpad keeps SVs which are lexicals for the current unit and are targets for opcodes. A previous version of this document stated that one can deduce that an SV lives on a scratchpad by looking on its flags: lexicals have `SVs_PADMY` set, and *target*s have `SVs_PADTMP` set. But this has never been fully true. `SVs_PADMY` could be set on a variable that no longer resides in any pad. While *target*s do have `SVs_PADTMP` set, it can also be set on variables that have never resided in a pad, but nonetheless act like *target*s. As of perl 5.21.5, the `SVs_PADMY` flag is no longer used and is defined as 0. `SvPADMY()` now returns true for anything without `SVs_PADTMP`.
The correspondence between OPs and *target*s is not 1-to-1. Different OPs in the compile tree of the unit can use the same target, if this would not conflict with the expected life of the temporary.
###
Scratchpads and recursion
In fact it is not 100% true that a compiled unit contains a pointer to the scratchpad AV. In fact it contains a pointer to an AV of (initially) one element, and this element is the scratchpad AV. Why do we need an extra level of indirection?
The answer is **recursion**, and maybe **threads**. Both these can create several execution pointers going into the same subroutine. For the subroutine-child not write over the temporaries for the subroutine-parent (lifespan of which covers the call to the child), the parent and the child should have different scratchpads. (*And* the lexicals should be separate anyway!)
So each subroutine is born with an array of scratchpads (of length 1). On each entry to the subroutine it is checked that the current depth of the recursion is not more than the length of this array, and if it is, new scratchpad is created and pushed into the array.
The *target*s on this scratchpad are `undef`s, but they are already marked with correct flags.
Memory Allocation
------------------
### Allocation
All memory meant to be used with the Perl API functions should be manipulated using the macros described in this section. The macros provide the necessary transparency between differences in the actual malloc implementation that is used within perl.
The following three macros are used to initially allocate memory :
```
Newx(pointer, number, type);
Newxc(pointer, number, type, cast);
Newxz(pointer, number, type);
```
The first argument `pointer` should be the name of a variable that will point to the newly allocated memory.
The second and third arguments `number` and `type` specify how many of the specified type of data structure should be allocated. The argument `type` is passed to `sizeof`. The final argument to `Newxc`, `cast`, should be used if the `pointer` argument is different from the `type` argument.
Unlike the `Newx` and `Newxc` macros, the `Newxz` macro calls `memzero` to zero out all the newly allocated memory.
### Reallocation
```
Renew(pointer, number, type);
Renewc(pointer, number, type, cast);
Safefree(pointer)
```
These three macros are used to change a memory buffer size or to free a piece of memory no longer needed. The arguments to `Renew` and `Renewc` match those of `New` and `Newc` with the exception of not needing the "magic cookie" argument.
### Moving
```
Move(source, dest, number, type);
Copy(source, dest, number, type);
Zero(dest, number, type);
```
These three macros are used to move, copy, or zero out previously allocated memory. The `source` and `dest` arguments point to the source and destination starting points. Perl will move, copy, or zero out `number` instances of the size of the `type` data structure (using the `sizeof` function).
PerlIO
------
The most recent development releases of Perl have been experimenting with removing Perl's dependency on the "normal" standard I/O suite and allowing other stdio implementations to be used. This involves creating a new abstraction layer that then calls whichever implementation of stdio Perl was compiled with. All XSUBs should now use the functions in the PerlIO abstraction layer and not make any assumptions about what kind of stdio is being used.
For a complete description of the PerlIO abstraction, consult <perlapio>.
Compiled code
--------------
###
Code tree
Here we describe the internal form your code is converted to by Perl. Start with a simple example:
```
$a = $b + $c;
```
This is converted to a tree similar to this one:
```
assign-to
/ \
+ $a
/ \
$b $c
```
(but slightly more complicated). This tree reflects the way Perl parsed your code, but has nothing to do with the execution order. There is an additional "thread" going through the nodes of the tree which shows the order of execution of the nodes. In our simplified example above it looks like:
```
$b ---> $c ---> + ---> $a ---> assign-to
```
But with the actual compile tree for `$a = $b + $c` it is different: some nodes *optimized away*. As a corollary, though the actual tree contains more nodes than our simplified example, the execution order is the same as in our example.
###
Examining the tree
If you have your perl compiled for debugging (usually done with `-DDEBUGGING` on the `Configure` command line), you may examine the compiled tree by specifying `-Dx` on the Perl command line. The output takes several lines per node, and for `$b+$c` it looks like this:
```
5 TYPE = add ===> 6
TARG = 1
FLAGS = (SCALAR,KIDS)
{
TYPE = null ===> (4)
(was rv2sv)
FLAGS = (SCALAR,KIDS)
{
3 TYPE = gvsv ===> 4
FLAGS = (SCALAR)
GV = main::b
}
}
{
TYPE = null ===> (5)
(was rv2sv)
FLAGS = (SCALAR,KIDS)
{
4 TYPE = gvsv ===> 5
FLAGS = (SCALAR)
GV = main::c
}
}
```
This tree has 5 nodes (one per `TYPE` specifier), only 3 of them are not optimized away (one per number in the left column). The immediate children of the given node correspond to `{}` pairs on the same level of indentation, thus this listing corresponds to the tree:
```
add
/ \
null null
| |
gvsv gvsv
```
The execution order is indicated by `===>` marks, thus it is `3 4 5 6` (node `6` is not included into above listing), i.e., `gvsv gvsv add whatever`.
Each of these nodes represents an op, a fundamental operation inside the Perl core. The code which implements each operation can be found in the *pp\*.c* files; the function which implements the op with type `gvsv` is `pp_gvsv`, and so on. As the tree above shows, different ops have different numbers of children: `add` is a binary operator, as one would expect, and so has two children. To accommodate the various different numbers of children, there are various types of op data structure, and they link together in different ways.
The simplest type of op structure is `OP`: this has no children. Unary operators, `UNOP`s, have one child, and this is pointed to by the `op_first` field. Binary operators (`BINOP`s) have not only an `op_first` field but also an `op_last` field. The most complex type of op is a `LISTOP`, which has any number of children. In this case, the first child is pointed to by `op_first` and the last child by `op_last`. The children in between can be found by iteratively following the `OpSIBLING` pointer from the first child to the last (but see below).
There are also some other op types: a `PMOP` holds a regular expression, and has no children, and a `LOOP` may or may not have children. If the `op_children` field is non-zero, it behaves like a `LISTOP`. To complicate matters, if a `UNOP` is actually a `null` op after optimization (see ["Compile pass 2: context propagation"](#Compile-pass-2%3A-context-propagation)) it will still have children in accordance with its former type.
Finally, there is a `LOGOP`, or logic op. Like a `LISTOP`, this has one or more children, but it doesn't have an `op_last` field: so you have to follow `op_first` and then the `OpSIBLING` chain itself to find the last child. Instead it has an `op_other` field, which is comparable to the `op_next` field described below, and represents an alternate execution path. Operators like `and`, `or` and `?` are `LOGOP`s. Note that in general, `op_other` may not point to any of the direct children of the `LOGOP`.
Starting in version 5.21.2, perls built with the experimental define `-DPERL_OP_PARENT` add an extra boolean flag for each op, `op_moresib`. When not set, this indicates that this is the last op in an `OpSIBLING` chain. This frees up the `op_sibling` field on the last sibling to point back to the parent op. Under this build, that field is also renamed `op_sibparent` to reflect its joint role. The macro `OpSIBLING(o)` wraps this special behaviour, and always returns NULL on the last sibling. With this build the `op_parent(o)` function can be used to find the parent of any op. Thus for forward compatibility, you should always use the `OpSIBLING(o)` macro rather than accessing `op_sibling` directly.
Another way to examine the tree is to use a compiler back-end module, such as <B::Concise>.
###
Compile pass 1: check routines
The tree is created by the compiler while *yacc* code feeds it the constructions it recognizes. Since *yacc* works bottom-up, so does the first pass of perl compilation.
What makes this pass interesting for perl developers is that some optimization may be performed on this pass. This is optimization by so-called "check routines". The correspondence between node names and corresponding check routines is described in *opcode.pl* (do not forget to run `make regen_headers` if you modify this file).
A check routine is called when the node is fully constructed except for the execution-order thread. Since at this time there are no back-links to the currently constructed node, one can do most any operation to the top-level node, including freeing it and/or creating new nodes above/below it.
The check routine returns the node which should be inserted into the tree (if the top-level node was not modified, check routine returns its argument).
By convention, check routines have names `ck_*`. They are usually called from `new*OP` subroutines (or `convert`) (which in turn are called from *perly.y*).
###
Compile pass 1a: constant folding
Immediately after the check routine is called the returned node is checked for being compile-time executable. If it is (the value is judged to be constant) it is immediately executed, and a *constant* node with the "return value" of the corresponding subtree is substituted instead. The subtree is deleted.
If constant folding was not performed, the execution-order thread is created.
###
Compile pass 2: context propagation
When a context for a part of compile tree is known, it is propagated down through the tree. At this time the context can have 5 values (instead of 2 for runtime context): void, boolean, scalar, list, and lvalue. In contrast with the pass 1 this pass is processed from top to bottom: a node's context determines the context for its children.
Additional context-dependent optimizations are performed at this time. Since at this moment the compile tree contains back-references (via "thread" pointers), nodes cannot be free()d now. To allow optimized-away nodes at this stage, such nodes are null()ified instead of free()ing (i.e. their type is changed to OP\_NULL).
###
Compile pass 3: peephole optimization
After the compile tree for a subroutine (or for an `eval` or a file) is created, an additional pass over the code is performed. This pass is neither top-down or bottom-up, but in the execution order (with additional complications for conditionals). Optimizations performed at this stage are subject to the same restrictions as in the pass 2.
Peephole optimizations are done by calling the function pointed to by the global variable `PL_peepp`. By default, `PL_peepp` just calls the function pointed to by the global variable `PL_rpeepp`. By default, that performs some basic op fixups and optimisations along the execution-order op chain, and recursively calls `PL_rpeepp` for each side chain of ops (resulting from conditionals). Extensions may provide additional optimisations or fixups, hooking into either the per-subroutine or recursive stage, like this:
```
static peep_t prev_peepp;
static void my_peep(pTHX_ OP *o)
{
/* custom per-subroutine optimisation goes here */
prev_peepp(aTHX_ o);
/* custom per-subroutine optimisation may also go here */
}
BOOT:
prev_peepp = PL_peepp;
PL_peepp = my_peep;
static peep_t prev_rpeepp;
static void my_rpeep(pTHX_ OP *first)
{
OP *o = first, *t = first;
for(; o = o->op_next, t = t->op_next) {
/* custom per-op optimisation goes here */
o = o->op_next;
if (!o || o == t) break;
/* custom per-op optimisation goes AND here */
}
prev_rpeepp(aTHX_ orig_o);
}
BOOT:
prev_rpeepp = PL_rpeepp;
PL_rpeepp = my_rpeep;
```
###
Pluggable runops
The compile tree is executed in a runops function. There are two runops functions, in *run.c* and in *dump.c*. `Perl_runops_debug` is used with DEBUGGING and `Perl_runops_standard` is used otherwise. For fine control over the execution of the compile tree it is possible to provide your own runops function.
It's probably best to copy one of the existing runops functions and change it to suit your needs. Then, in the BOOT section of your XS file, add the line:
```
PL_runops = my_runops;
```
This function should be as efficient as possible to keep your programs running as fast as possible.
###
Compile-time scope hooks
As of perl 5.14 it is possible to hook into the compile-time lexical scope mechanism using `Perl_blockhook_register`. This is used like this:
```
STATIC void my_start_hook(pTHX_ int full);
STATIC BHK my_hooks;
BOOT:
BhkENTRY_set(&my_hooks, bhk_start, my_start_hook);
Perl_blockhook_register(aTHX_ &my_hooks);
```
This will arrange to have `my_start_hook` called at the start of compiling every lexical scope. The available hooks are:
`void bhk_start(pTHX_ int full)`
This is called just after starting a new lexical scope. Note that Perl code like
```
if ($x) { ... }
```
creates two scopes: the first starts at the `(` and has `full == 1`, the second starts at the `{` and has `full == 0`. Both end at the `}`, so calls to `start` and `pre`/`post_end` will match. Anything pushed onto the save stack by this hook will be popped just before the scope ends (between the `pre_` and `post_end` hooks, in fact).
`void bhk_pre_end(pTHX_ OP **o)`
This is called at the end of a lexical scope, just before unwinding the stack. *o* is the root of the optree representing the scope; it is a double pointer so you can replace the OP if you need to.
`void bhk_post_end(pTHX_ OP **o)`
This is called at the end of a lexical scope, just after unwinding the stack. *o* is as above. Note that it is possible for calls to `pre_` and `post_end` to nest, if there is something on the save stack that calls string eval.
`void bhk_eval(pTHX_ OP *const o)`
This is called just before starting to compile an `eval STRING`, `do FILE`, `require` or `use`, after the eval has been set up. *o* is the OP that requested the eval, and will normally be an `OP_ENTEREVAL`, `OP_DOFILE` or `OP_REQUIRE`.
Once you have your hook functions, you need a `BHK` structure to put them in. It's best to allocate it statically, since there is no way to free it once it's registered. The function pointers should be inserted into this structure using the `BhkENTRY_set` macro, which will also set flags indicating which entries are valid. If you do need to allocate your `BHK` dynamically for some reason, be sure to zero it before you start.
Once registered, there is no mechanism to switch these hooks off, so if that is necessary you will need to do this yourself. An entry in `%^H` is probably the best way, so the effect is lexically scoped; however it is also possible to use the `BhkDISABLE` and `BhkENABLE` macros to temporarily switch entries on and off. You should also be aware that generally speaking at least one scope will have opened before your extension is loaded, so you will see some `pre`/`post_end` pairs that didn't have a matching `start`.
Examining internal data structures with the `dump` functions
-------------------------------------------------------------
To aid debugging, the source file *dump.c* contains a number of functions which produce formatted output of internal data structures.
The most commonly used of these functions is `Perl_sv_dump`; it's used for dumping SVs, AVs, HVs, and CVs. The `Devel::Peek` module calls `sv_dump` to produce debugging output from Perl-space, so users of that module should already be familiar with its format.
`Perl_op_dump` can be used to dump an `OP` structure or any of its derivatives, and produces output similar to `perl -Dx`; in fact, `Perl_dump_eval` will dump the main root of the code being evaluated, exactly like `-Dx`.
Other useful functions are `Perl_dump_sub`, which turns a `GV` into an op tree, `Perl_dump_packsubs` which calls `Perl_dump_sub` on all the subroutines in a package like so: (Thankfully, these are all xsubs, so there is no op tree)
```
(gdb) print Perl_dump_packsubs(PL_defstash)
SUB attributes::bootstrap = (xsub 0x811fedc 0)
SUB UNIVERSAL::can = (xsub 0x811f50c 0)
SUB UNIVERSAL::isa = (xsub 0x811f304 0)
SUB UNIVERSAL::VERSION = (xsub 0x811f7ac 0)
SUB DynaLoader::boot_DynaLoader = (xsub 0x805b188 0)
```
and `Perl_dump_all`, which dumps all the subroutines in the stash and the op tree of the main root.
How multiple interpreters and concurrency are supported
--------------------------------------------------------
###
Background and MULTIPLICITY
The Perl interpreter can be regarded as a closed box: it has an API for feeding it code or otherwise making it do things, but it also has functions for its own use. This smells a lot like an object, and there is a way for you to build Perl so that you can have multiple interpreters, with one interpreter represented either as a C structure, or inside a thread-specific structure. These structures contain all the context, the state of that interpreter.
The macro that controls the major Perl build flavor is MULTIPLICITY. The MULTIPLICITY build has a C structure that packages all the interpreter state, which is being passed to various perl functions as a "hidden" first argument. MULTIPLICITY makes multi-threaded perls possible (with the ithreads threading model, related to the macro USE\_ITHREADS.)
PERL\_IMPLICIT\_CONTEXT is a legacy synonym for MULTIPLICITY.
To see whether you have non-const data you can use a BSD (or GNU) compatible `nm`:
```
nm libperl.a | grep -v ' [TURtr] '
```
If this displays any `D` or `d` symbols (or possibly `C` or `c`), you have non-const data. The symbols the `grep` removed are as follows: `Tt` are *text*, or code, the `Rr` are *read-only* (const) data, and the `U` is <undefined>, external symbols referred to.
The test *t/porting/libperl.t* does this kind of symbol sanity checking on `libperl.a`.
All this obviously requires a way for the Perl internal functions to be either subroutines taking some kind of structure as the first argument, or subroutines taking nothing as the first argument. To enable these two very different ways of building the interpreter, the Perl source (as it does in so many other situations) makes heavy use of macros and subroutine naming conventions.
First problem: deciding which functions will be public API functions and which will be private. All functions whose names begin `S_` are private (think "S" for "secret" or "static"). All other functions begin with "Perl\_", but just because a function begins with "Perl\_" does not mean it is part of the API. (See ["Internal Functions"](#Internal-Functions).) The easiest way to be **sure** a function is part of the API is to find its entry in <perlapi>. If it exists in <perlapi>, it's part of the API. If it doesn't, and you think it should be (i.e., you need it for your extension), submit an issue at <https://github.com/Perl/perl5/issues> explaining why you think it should be.
Second problem: there must be a syntax so that the same subroutine declarations and calls can pass a structure as their first argument, or pass nothing. To solve this, the subroutines are named and declared in a particular way. Here's a typical start of a static function used within the Perl guts:
```
STATIC void
S_incline(pTHX_ char *s)
```
STATIC becomes "static" in C, and may be #define'd to nothing in some configurations in the future.
A public function (i.e. part of the internal API, but not necessarily sanctioned for use in extensions) begins like this:
```
void
Perl_sv_setiv(pTHX_ SV* dsv, IV num)
```
`pTHX_` is one of a number of macros (in *perl.h*) that hide the details of the interpreter's context. THX stands for "thread", "this", or "thingy", as the case may be. (And no, George Lucas is not involved. :-) The first character could be 'p' for a **p**rototype, 'a' for **a**rgument, or 'd' for **d**eclaration, so we have `pTHX`, `aTHX` and `dTHX`, and their variants.
When Perl is built without options that set MULTIPLICITY, there is no first argument containing the interpreter's context. The trailing underscore in the pTHX\_ macro indicates that the macro expansion needs a comma after the context argument because other arguments follow it. If MULTIPLICITY is not defined, pTHX\_ will be ignored, and the subroutine is not prototyped to take the extra argument. The form of the macro without the trailing underscore is used when there are no additional explicit arguments.
When a core function calls another, it must pass the context. This is normally hidden via macros. Consider `sv_setiv`. It expands into something like this:
```
#ifdef MULTIPLICITY
#define sv_setiv(a,b) Perl_sv_setiv(aTHX_ a, b)
/* can't do this for vararg functions, see below */
#else
#define sv_setiv Perl_sv_setiv
#endif
```
This works well, and means that XS authors can gleefully write:
```
sv_setiv(foo, bar);
```
and still have it work under all the modes Perl could have been compiled with.
This doesn't work so cleanly for varargs functions, though, as macros imply that the number of arguments is known in advance. Instead we either need to spell them out fully, passing `aTHX_` as the first argument (the Perl core tends to do this with functions like Perl\_warner), or use a context-free version.
The context-free version of Perl\_warner is called Perl\_warner\_nocontext, and does not take the extra argument. Instead it does `dTHX;` to get the context from thread-local storage. We `#define warner Perl_warner_nocontext` so that extensions get source compatibility at the expense of performance. (Passing an arg is cheaper than grabbing it from thread-local storage.)
You can ignore [pad]THXx when browsing the Perl headers/sources. Those are strictly for use within the core. Extensions and embedders need only be aware of [pad]THX.
###
So what happened to dTHR?
`dTHR` was introduced in perl 5.005 to support the older thread model. The older thread model now uses the `THX` mechanism to pass context pointers around, so `dTHR` is not useful any more. Perl 5.6.0 and later still have it for backward source compatibility, but it is defined to be a no-op.
###
How do I use all this in extensions?
When Perl is built with MULTIPLICITY, extensions that call any functions in the Perl API will need to pass the initial context argument somehow. The kicker is that you will need to write it in such a way that the extension still compiles when Perl hasn't been built with MULTIPLICITY enabled.
There are three ways to do this. First, the easy but inefficient way, which is also the default, in order to maintain source compatibility with extensions: whenever *XSUB.h* is #included, it redefines the aTHX and aTHX\_ macros to call a function that will return the context. Thus, something like:
```
sv_setiv(sv, num);
```
in your extension will translate to this when MULTIPLICITY is in effect:
```
Perl_sv_setiv(Perl_get_context(), sv, num);
```
or to this otherwise:
```
Perl_sv_setiv(sv, num);
```
You don't have to do anything new in your extension to get this; since the Perl library provides Perl\_get\_context(), it will all just work.
The second, more efficient way is to use the following template for your Foo.xs:
```
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
STATIC void my_private_function(int arg1, int arg2);
STATIC void
my_private_function(int arg1, int arg2)
{
dTHX; /* fetch context */
... call many Perl API functions ...
}
[... etc ...]
MODULE = Foo PACKAGE = Foo
/* typical XSUB */
void
my_xsub(arg)
int arg
CODE:
my_private_function(arg, 10);
```
Note that the only two changes from the normal way of writing an extension is the addition of a `#define PERL_NO_GET_CONTEXT` before including the Perl headers, followed by a `dTHX;` declaration at the start of every function that will call the Perl API. (You'll know which functions need this, because the C compiler will complain that there's an undeclared identifier in those functions.) No changes are needed for the XSUBs themselves, because the XS() macro is correctly defined to pass in the implicit context if needed.
The third, even more efficient way is to ape how it is done within the Perl guts:
```
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* pTHX_ only needed for functions that call Perl API */
STATIC void my_private_function(pTHX_ int arg1, int arg2);
STATIC void
my_private_function(pTHX_ int arg1, int arg2)
{
/* dTHX; not needed here, because THX is an argument */
... call Perl API functions ...
}
[... etc ...]
MODULE = Foo PACKAGE = Foo
/* typical XSUB */
void
my_xsub(arg)
int arg
CODE:
my_private_function(aTHX_ arg, 10);
```
This implementation never has to fetch the context using a function call, since it is always passed as an extra argument. Depending on your needs for simplicity or efficiency, you may mix the previous two approaches freely.
Never add a comma after `pTHX` yourself--always use the form of the macro with the underscore for functions that take explicit arguments, or the form without the argument for functions with no explicit arguments.
###
Should I do anything special if I call perl from multiple threads?
If you create interpreters in one thread and then proceed to call them in another, you need to make sure perl's own Thread Local Storage (TLS) slot is initialized correctly in each of those threads.
The `perl_alloc` and `perl_clone` API functions will automatically set the TLS slot to the interpreter they created, so that there is no need to do anything special if the interpreter is always accessed in the same thread that created it, and that thread did not create or call any other interpreters afterwards. If that is not the case, you have to set the TLS slot of the thread before calling any functions in the Perl API on that particular interpreter. This is done by calling the `PERL_SET_CONTEXT` macro in that thread as the first thing you do:
```
/* do this before doing anything else with some_perl */
PERL_SET_CONTEXT(some_perl);
... other Perl API calls on some_perl go here ...
```
(You can always get the current context via `PERL_GET_CONTEXT`.)
###
Future Plans and PERL\_IMPLICIT\_SYS
Just as MULTIPLICITY provides a way to bundle up everything that the interpreter knows about itself and pass it around, so too are there plans to allow the interpreter to bundle up everything it knows about the environment it's running on. This is enabled with the PERL\_IMPLICIT\_SYS macro. Currently it only works with USE\_ITHREADS on Windows.
This allows the ability to provide an extra pointer (called the "host" environment) for all the system calls. This makes it possible for all the system stuff to maintain their own state, broken down into seven C structures. These are thin wrappers around the usual system calls (see *win32/perllib.c*) for the default perl executable, but for a more ambitious host (like the one that would do fork() emulation) all the extra work needed to pretend that different interpreters are actually different "processes", would be done here.
The Perl engine/interpreter and the host are orthogonal entities. There could be one or more interpreters in a process, and one or more "hosts", with free association between them.
Internal Functions
-------------------
All of Perl's internal functions which will be exposed to the outside world are prefixed by `Perl_` so that they will not conflict with XS functions or functions used in a program in which Perl is embedded. Similarly, all global variables begin with `PL_`. (By convention, static functions start with `S_`.)
Inside the Perl core (`PERL_CORE` defined), you can get at the functions either with or without the `Perl_` prefix, thanks to a bunch of defines that live in *embed.h*. Note that extension code should *not* set `PERL_CORE`; this exposes the full perl internals, and is likely to cause breakage of the XS in each new perl release.
The file *embed.h* is generated automatically from *embed.pl* and *embed.fnc*. *embed.pl* also creates the prototyping header files for the internal functions, generates the documentation and a lot of other bits and pieces. It's important that when you add a new function to the core or change an existing one, you change the data in the table in *embed.fnc* as well. Here's a sample entry from that table:
```
Apd |SV** |av_fetch |AV* ar|I32 key|I32 lval
```
The first column is a set of flags, the second column the return type, the third column the name. Columns after that are the arguments. The flags are documented at the top of *embed.fnc*.
If you edit *embed.pl* or *embed.fnc*, you will need to run `make regen_headers` to force a rebuild of *embed.h* and other auto-generated files.
###
Formatted Printing of IVs, UVs, and NVs
If you are printing IVs, UVs, or NVS instead of the stdio(3) style formatting codes like `%d`, `%ld`, `%f`, you should use the following macros for portability
```
IVdf IV in decimal
UVuf UV in decimal
UVof UV in octal
UVxf UV in hexadecimal
NVef NV %e-like
NVff NV %f-like
NVgf NV %g-like
```
These will take care of 64-bit integers and long doubles. For example:
```
printf("IV is %" IVdf "\n", iv);
```
The `IVdf` will expand to whatever is the correct format for the IVs. Note that the spaces are required around the format in case the code is compiled with C++, to maintain compliance with its standard.
Note that there are different "long doubles": Perl will use whatever the compiler has.
If you are printing addresses of pointers, use %p or UVxf combined with PTR2UV().
###
Formatted Printing of SVs
The contents of SVs may be printed using the `SVf` format, like so:
```
Perl_croak(aTHX_ "This croaked because: %" SVf "\n", SVfARG(err_msg))
```
where `err_msg` is an SV.
Not all scalar types are printable. Simple values certainly are: one of IV, UV, NV, or PV. Also, if the SV is a reference to some value, either it will be dereferenced and the value printed, or information about the type of that value and its address are displayed. The results of printing any other type of SV are undefined and likely to lead to an interpreter crash. NVs are printed using a `%g`-ish format.
Note that the spaces are required around the `SVf` in case the code is compiled with C++, to maintain compliance with its standard.
Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the `-C`> parameter. (See ["-C [number/list]" in perlrun](perlrun#-C-%5Bnumber%2Flist%5D).
You can use this to concatenate two scalars:
```
SV *var1 = get_sv("var1", GV_ADD);
SV *var2 = get_sv("var2", GV_ADD);
SV *var3 = newSVpvf("var1=%" SVf " and var2=%" SVf,
SVfARG(var1), SVfARG(var2));
```
###
Formatted Printing of Strings
If you just want the bytes printed in a 7bit NUL-terminated string, you can just use `%s` (assuming they are all really only 7bit). But if there is a possibility the value will be encoded as UTF-8 or contains bytes above `0x7F` (and therefore 8bit), you should instead use the `UTF8f` format. And as its parameter, use the `UTF8fARG()` macro:
```
chr * msg;
/* U+2018: \xE2\x80\x98 LEFT SINGLE QUOTATION MARK
U+2019: \xE2\x80\x99 RIGHT SINGLE QUOTATION MARK */
if (can_utf8)
msg = "\xE2\x80\x98Uses fancy quotes\xE2\x80\x99";
else
msg = "'Uses simple quotes'";
Perl_croak(aTHX_ "The message is: %" UTF8f "\n",
UTF8fARG(can_utf8, strlen(msg), msg));
```
The first parameter to `UTF8fARG` is a boolean: 1 if the string is in UTF-8; 0 if string is in native byte encoding (Latin1). The second parameter is the number of bytes in the string to print. And the third and final parameter is a pointer to the first byte in the string.
Note that any filehandle being printed to under UTF-8 must be expecting UTF-8 in order to get good results and avoid Wide-character warnings. One way to do this for typical filehandles is to invoke perl with the `-C`> parameter. (See ["-C [number/list]" in perlrun](perlrun#-C-%5Bnumber%2Flist%5D).
###
Formatted Printing of `Size_t` and `SSize_t`
The most general way to do this is to cast them to a UV or IV, and print as in the [previous section](#Formatted-Printing-of-IVs%2C-UVs%2C-and-NVs).
But if you're using `PerlIO_printf()`, it's less typing and visual clutter to use the `%z` length modifier (for *siZe*):
```
PerlIO_printf("STRLEN is %zu\n", len);
```
This modifier is not portable, so its use should be restricted to `PerlIO_printf()`.
###
Formatted Printing of `Ptrdiff_t`, `intmax_t`, `short` and other special sizes
There are modifiers for these special situations if you are using `PerlIO_printf()`. See ["size" in perlfunc](perlfunc#size).
###
Pointer-To-Integer and Integer-To-Pointer
Because pointer size does not necessarily equal integer size, use the follow macros to do it right.
```
PTR2UV(pointer)
PTR2IV(pointer)
PTR2NV(pointer)
INT2PTR(pointertotype, integer)
```
For example:
```
IV iv = ...;
SV *sv = INT2PTR(SV*, iv);
```
and
```
AV *av = ...;
UV uv = PTR2UV(av);
```
There are also
```
PTR2nat(pointer) /* pointer to integer of PTRSIZE */
PTR2ul(pointer) /* pointer to unsigned long */
```
And `PTRV` which gives the native type for an integer the same size as pointers, such as `unsigned` or `unsigned long`.
###
Exception Handling
There are a couple of macros to do very basic exception handling in XS modules. You have to define `NO_XSLOCKS` before including *XSUB.h* to be able to use these macros:
```
#define NO_XSLOCKS
#include "XSUB.h"
```
You can use these macros if you call code that may croak, but you need to do some cleanup before giving control back to Perl. For example:
```
dXCPT; /* set up necessary variables */
XCPT_TRY_START {
code_that_may_croak();
} XCPT_TRY_END
XCPT_CATCH
{
/* do cleanup here */
XCPT_RETHROW;
}
```
Note that you always have to rethrow an exception that has been caught. Using these macros, it is not possible to just catch the exception and ignore it. If you have to ignore the exception, you have to use the `call_*` function.
The advantage of using the above macros is that you don't have to setup an extra function for `call_*`, and that using these macros is faster than using `call_*`.
###
Source Documentation
There's an effort going on to document the internal functions and automatically produce reference manuals from them -- <perlapi> is one such manual which details all the functions which are available to XS writers. <perlintern> is the autogenerated manual for the functions which are not part of the API and are supposedly for internal use only.
Source documentation is created by putting POD comments into the C source, like this:
```
/*
=for apidoc sv_setiv
Copies an integer into the given SV. Does not handle 'set' magic. See
L<perlapi/sv_setiv_mg>.
=cut
*/
```
Please try and supply some documentation if you add functions to the Perl core.
###
Backwards compatibility
The Perl API changes over time. New functions are added or the interfaces of existing functions are changed. The `Devel::PPPort` module tries to provide compatibility code for some of these changes, so XS writers don't have to code it themselves when supporting multiple versions of Perl.
`Devel::PPPort` generates a C header file *ppport.h* that can also be run as a Perl script. To generate *ppport.h*, run:
```
perl -MDevel::PPPort -eDevel::PPPort::WriteFile
```
Besides checking existing XS code, the script can also be used to retrieve compatibility information for various API calls using the `--api-info` command line switch. For example:
```
% perl ppport.h --api-info=sv_magicext
```
For details, see `perldoc ppport.h`.
Unicode Support
----------------
Perl 5.6.0 introduced Unicode support. It's important for porters and XS writers to understand this support and make sure that the code they write does not corrupt Unicode data.
###
What **is** Unicode, anyway?
In the olden, less enlightened times, we all used to use ASCII. Most of us did, anyway. The big problem with ASCII is that it's American. Well, no, that's not actually the problem; the problem is that it's not particularly useful for people who don't use the Roman alphabet. What used to happen was that particular languages would stick their own alphabet in the upper range of the sequence, between 128 and 255. Of course, we then ended up with plenty of variants that weren't quite ASCII, and the whole point of it being a standard was lost.
Worse still, if you've got a language like Chinese or Japanese that has hundreds or thousands of characters, then you really can't fit them into a mere 256, so they had to forget about ASCII altogether, and build their own systems using pairs of numbers to refer to one character.
To fix this, some people formed Unicode, Inc. and produced a new character set containing all the characters you can possibly think of and more. There are several ways of representing these characters, and the one Perl uses is called UTF-8. UTF-8 uses a variable number of bytes to represent a character. You can learn more about Unicode and Perl's Unicode model in <perlunicode>.
(On EBCDIC platforms, Perl uses instead UTF-EBCDIC, which is a form of UTF-8 adapted for EBCDIC platforms. Below, we just talk about UTF-8. UTF-EBCDIC is like UTF-8, but the details are different. The macros hide the differences from you, just remember that the particular numbers and bit patterns presented below will differ in UTF-EBCDIC.)
###
How can I recognise a UTF-8 string?
You can't. This is because UTF-8 data is stored in bytes just like non-UTF-8 data. The Unicode character 200, (`0xC8` for you hex types) capital E with a grave accent, is represented by the two bytes `v196.172`. Unfortunately, the non-Unicode string `chr(196).chr(172)` has that byte sequence as well. So you can't tell just by looking -- this is what makes Unicode input an interesting problem.
In general, you either have to know what you're dealing with, or you have to guess. The API function `is_utf8_string` can help; it'll tell you if a string contains only valid UTF-8 characters, and the chances of a non-UTF-8 string looking like valid UTF-8 become very small very quickly with increasing string length. On a character-by-character basis, `isUTF8_CHAR` will tell you whether the current character in a string is valid UTF-8.
###
How does UTF-8 represent Unicode characters?
As mentioned above, UTF-8 uses a variable number of bytes to store a character. Characters with values 0...127 are stored in one byte, just like good ol' ASCII. Character 128 is stored as `v194.128`; this continues up to character 191, which is `v194.191`. Now we've run out of bits (191 is binary `10111111`) so we move on; character 192 is `v195.128`. And so it goes on, moving to three bytes at character 2048. ["Unicode Encodings" in perlunicode](perlunicode#Unicode-Encodings) has pictures of how this works.
Assuming you know you're dealing with a UTF-8 string, you can find out how long the first character in it is with the `UTF8SKIP` macro:
```
char *utf = "\305\233\340\240\201";
I32 len;
len = UTF8SKIP(utf); /* len is 2 here */
utf += len;
len = UTF8SKIP(utf); /* len is 3 here */
```
Another way to skip over characters in a UTF-8 string is to use `utf8_hop`, which takes a string and a number of characters to skip over. You're on your own about bounds checking, though, so don't use it lightly.
All bytes in a multi-byte UTF-8 character will have the high bit set, so you can test if you need to do something special with this character like this (the `UTF8_IS_INVARIANT()` is a macro that tests whether the byte is encoded as a single byte even in UTF-8):
```
U8 *utf; /* Initialize this to point to the beginning of the
sequence to convert */
U8 *utf_end; /* Initialize this to 1 beyond the end of the sequence
pointed to by 'utf' */
UV uv; /* Returned code point; note: a UV, not a U8, not a
char */
STRLEN len; /* Returned length of character in bytes */
if (!UTF8_IS_INVARIANT(*utf))
/* Must treat this as UTF-8 */
uv = utf8_to_uvchr_buf(utf, utf_end, &len);
else
/* OK to treat this character as a byte */
uv = *utf;
```
You can also see in that example that we use `utf8_to_uvchr_buf` to get the value of the character; the inverse function `uvchr_to_utf8` is available for putting a UV into UTF-8:
```
if (!UVCHR_IS_INVARIANT(uv))
/* Must treat this as UTF8 */
utf8 = uvchr_to_utf8(utf8, uv);
else
/* OK to treat this character as a byte */
*utf8++ = uv;
```
You **must** convert characters to UVs using the above functions if you're ever in a situation where you have to match UTF-8 and non-UTF-8 characters. You may not skip over UTF-8 characters in this case. If you do this, you'll lose the ability to match hi-bit non-UTF-8 characters; for instance, if your UTF-8 string contains `v196.172`, and you skip that character, you can never match a `chr(200)` in a non-UTF-8 string. So don't do that!
(Note that we don't have to test for invariant characters in the examples above. The functions work on any well-formed UTF-8 input. It's just that its faster to avoid the function overhead when it's not needed.)
###
How does Perl store UTF-8 strings?
Currently, Perl deals with UTF-8 strings and non-UTF-8 strings slightly differently. A flag in the SV, `SVf_UTF8`, indicates that the string is internally encoded as UTF-8. Without it, the byte value is the codepoint number and vice versa. This flag is only meaningful if the SV is `SvPOK` or immediately after stringification via `SvPV` or a similar macro. You can check and manipulate this flag with the following macros:
```
SvUTF8(sv)
SvUTF8_on(sv)
SvUTF8_off(sv)
```
This flag has an important effect on Perl's treatment of the string: if UTF-8 data is not properly distinguished, regular expressions, `length`, `substr` and other string handling operations will have undesirable (wrong) results.
The problem comes when you have, for instance, a string that isn't flagged as UTF-8, and contains a byte sequence that could be UTF-8 -- especially when combining non-UTF-8 and UTF-8 strings.
Never forget that the `SVf_UTF8` flag is separate from the PV value; you need to be sure you don't accidentally knock it off while you're manipulating SVs. More specifically, you cannot expect to do this:
```
SV *sv;
SV *nsv;
STRLEN len;
char *p;
p = SvPV(sv, len);
frobnicate(p);
nsv = newSVpvn(p, len);
```
The `char*` string does not tell you the whole story, and you can't copy or reconstruct an SV just by copying the string value. Check if the old SV has the UTF8 flag set (*after* the `SvPV` call), and act accordingly:
```
p = SvPV(sv, len);
is_utf8 = SvUTF8(sv);
frobnicate(p, is_utf8);
nsv = newSVpvn(p, len);
if (is_utf8)
SvUTF8_on(nsv);
```
In the above, your `frobnicate` function has been changed to be made aware of whether or not it's dealing with UTF-8 data, so that it can handle the string appropriately.
Since just passing an SV to an XS function and copying the data of the SV is not enough to copy the UTF8 flags, even less right is just passing a `char *` to an XS function.
For full generality, use the [`DO_UTF8`](perlapi#DO_UTF8) macro to see if the string in an SV is to be *treated* as UTF-8. This takes into account if the call to the XS function is being made from within the scope of [`use bytes`](bytes). If so, the underlying bytes that comprise the UTF-8 string are to be exposed, rather than the character they represent. But this pragma should only really be used for debugging and perhaps low-level testing at the byte level. Hence most XS code need not concern itself with this, but various areas of the perl core do need to support it.
And this isn't the whole story. Starting in Perl v5.12, strings that aren't encoded in UTF-8 may also be treated as Unicode under various conditions (see ["ASCII Rules versus Unicode Rules" in perlunicode](perlunicode#ASCII-Rules-versus-Unicode-Rules)). This is only really a problem for characters whose ordinals are between 128 and 255, and their behavior varies under ASCII versus Unicode rules in ways that your code cares about (see ["The "Unicode Bug"" in perlunicode](perlunicode#The-%22Unicode-Bug%22)). There is no published API for dealing with this, as it is subject to change, but you can look at the code for `pp_lc` in *pp.c* for an example as to how it's currently done.
###
How do I pass a Perl string to a C library?
A Perl string, conceptually, is an opaque sequence of code points. Many C libraries expect their inputs to be "classical" C strings, which are arrays of octets 1-255, terminated with a NUL byte. Your job when writing an interface between Perl and a C library is to define the mapping between Perl and that library.
Generally speaking, `SvPVbyte` and related macros suit this task well. These assume that your Perl string is a "byte string", i.e., is either raw, undecoded input into Perl or is pre-encoded to, e.g., UTF-8.
Alternatively, if your C library expects UTF-8 text, you can use `SvPVutf8` and related macros. This has the same effect as encoding to UTF-8 then calling the corresponding `SvPVbyte`-related macro.
Some C libraries may expect other encodings (e.g., UTF-16LE). To give Perl strings to such libraries you must either do that encoding in Perl then use `SvPVbyte`, or use an intermediary C library to convert from however Perl stores the string to the desired encoding.
Take care also that NULs in your Perl string don't confuse the C library. If possible, give the string's length to the C library; if that's not possible, consider rejecting strings that contain NUL bytes.
####
What about `SvPV`, `SvPV_nolen`, etc.?
Consider a 3-character Perl string `$foo = "\x64\x78\x8c"`. Perl can store these 3 characters either of two ways:
* bytes: 0x64 0x78 0x8c
* UTF-8: 0x64 0x78 0xc2 0x8c
Now let's say you convert `$foo` to a C string thus:
```
STRLEN strlen;
char *str = SvPV(foo_sv, strlen);
```
At this point `str` could point to a 3-byte C string or a 4-byte one.
Generally speaking, we want `str` to be the same regardless of how Perl stores `$foo`, so the ambiguity here is undesirable. `SvPVbyte` and `SvPVutf8` solve that by giving predictable output: use `SvPVbyte` if your C library expects byte strings, or `SvPVutf8` if it expects UTF-8.
If your C library happens to support both encodings, then `SvPV`--always in tandem with lookups to `SvUTF8`!--may be safe and (slightly) more efficient.
**TESTING** **TIP:** Use <utf8>'s `upgrade` and `downgrade` functions in your tests to ensure consistent handling regardless of Perl's internal encoding.
###
How do I convert a string to UTF-8?
If you're mixing UTF-8 and non-UTF-8 strings, it is necessary to upgrade the non-UTF-8 strings to UTF-8. If you've got an SV, the easiest way to do this is:
```
sv_utf8_upgrade(sv);
```
However, you must not do this, for example:
```
if (!SvUTF8(left))
sv_utf8_upgrade(left);
```
If you do this in a binary operator, you will actually change one of the strings that came into the operator, and, while it shouldn't be noticeable by the end user, it can cause problems in deficient code.
Instead, `bytes_to_utf8` will give you a UTF-8-encoded **copy** of its string argument. This is useful for having the data available for comparisons and so on, without harming the original SV. There's also `utf8_to_bytes` to go the other way, but naturally, this will fail if the string contains any characters above 255 that can't be represented in a single byte.
###
How do I compare strings?
["sv\_cmp" in perlapi](perlapi#sv_cmp) and ["sv\_cmp\_flags" in perlapi](perlapi#sv_cmp_flags) do a lexigraphic comparison of two SV's, and handle UTF-8ness properly. Note, however, that Unicode specifies a much fancier mechanism for collation, available via the <Unicode::Collate> module.
To just compare two strings for equality/non-equality, you can just use [`memEQ()`](perlapi#memEQ) and [`memNE()`](perlapi#memEQ) as usual, except the strings must be both UTF-8 or not UTF-8 encoded.
To compare two strings case-insensitively, use [`foldEQ_utf8()`](perlapi#foldEQ_utf8) (the strings don't have to have the same UTF-8ness).
###
Is there anything else I need to know?
Not really. Just remember these things:
* There's no way to tell if a `char *` or `U8 *` string is UTF-8 or not. But you can tell if an SV is to be treated as UTF-8 by calling `DO_UTF8` on it, after stringifying it with `SvPV` or a similar macro. And, you can tell if SV is actually UTF-8 (even if it is not to be treated as such) by looking at its `SvUTF8` flag (again after stringifying it). Don't forget to set the flag if something should be UTF-8. Treat the flag as part of the PV, even though it's not -- if you pass on the PV to somewhere, pass on the flag too.
* If a string is UTF-8, **always** use `utf8_to_uvchr_buf` to get at the value, unless `UTF8_IS_INVARIANT(*s)` in which case you can use `*s`.
* When writing a character UV to a UTF-8 string, **always** use `uvchr_to_utf8`, unless `UVCHR_IS_INVARIANT(uv))` in which case you can use `*s = uv`.
* Mixing UTF-8 and non-UTF-8 strings is tricky. Use `bytes_to_utf8` to get a new string which is UTF-8 encoded, and then combine them.
Custom Operators
-----------------
Custom operator support is an experimental feature that allows you to define your own ops. This is primarily to allow the building of interpreters for other languages in the Perl core, but it also allows optimizations through the creation of "macro-ops" (ops which perform the functions of multiple ops which are usually executed together, such as `gvsv, gvsv, add`.)
This feature is implemented as a new op type, `OP_CUSTOM`. The Perl core does not "know" anything special about this op type, and so it will not be involved in any optimizations. This also means that you can define your custom ops to be any op structure -- unary, binary, list and so on -- you like.
It's important to know what custom operators won't do for you. They won't let you add new syntax to Perl, directly. They won't even let you add new keywords, directly. In fact, they won't change the way Perl compiles a program at all. You have to do those changes yourself, after Perl has compiled the program. You do this either by manipulating the op tree using a `CHECK` block and the `B::Generate` module, or by adding a custom peephole optimizer with the `optimize` module.
When you do this, you replace ordinary Perl ops with custom ops by creating ops with the type `OP_CUSTOM` and the `op_ppaddr` of your own PP function. This should be defined in XS code, and should look like the PP ops in `pp_*.c`. You are responsible for ensuring that your op takes the appropriate number of values from the stack, and you are responsible for adding stack marks if necessary.
You should also "register" your op with the Perl interpreter so that it can produce sensible error and warning messages. Since it is possible to have multiple custom ops within the one "logical" op type `OP_CUSTOM`, Perl uses the value of `o->op_ppaddr` to determine which custom op it is dealing with. You should create an `XOP` structure for each ppaddr you use, set the properties of the custom op with `XopENTRY_set`, and register the structure against the ppaddr using `Perl_custom_op_register`. A trivial example might look like:
```
static XOP my_xop;
static OP *my_pp(pTHX);
BOOT:
XopENTRY_set(&my_xop, xop_name, "myxop");
XopENTRY_set(&my_xop, xop_desc, "Useless custom op");
Perl_custom_op_register(aTHX_ my_pp, &my_xop);
```
The available fields in the structure are:
xop\_name A short name for your op. This will be included in some error messages, and will also be returned as `$op->name` by the [B](b) module, so it will appear in the output of module like <B::Concise>.
xop\_desc A short description of the function of the op.
xop\_class Which of the various `*OP` structures this op uses. This should be one of the `OA_*` constants from *op.h*, namely
OA\_BASEOP OA\_UNOP OA\_BINOP OA\_LOGOP OA\_LISTOP OA\_PMOP OA\_SVOP OA\_PADOP OA\_PVOP\_OR\_SVOP This should be interpreted as '`PVOP`' only. The `_OR_SVOP` is because the only core `PVOP`, `OP_TRANS`, can sometimes be a `SVOP` instead.
OA\_LOOP OA\_COP The other `OA_*` constants should not be used.
xop\_peep This member is of type `Perl_cpeep_t`, which expands to `void (*Perl_cpeep_t)(aTHX_ OP *o, OP *oldop)`. If it is set, this function will be called from `Perl_rpeep` when ops of this type are encountered by the peephole optimizer. *o* is the OP that needs optimizing; *oldop* is the previous OP optimized, whose `op_next` points to *o*.
`B::Generate` directly supports the creation of custom ops by name.
Stacks
------
Descriptions above occasionally refer to "the stack", but there are in fact many stack-like data structures within the perl interpreter. When otherwise unqualified, "the stack" usually refers to the value stack.
The various stacks have different purposes, and operate in slightly different ways. Their differences are noted below.
###
Value Stack
This stack stores the values that regular perl code is operating on, usually intermediate values of expressions within a statement. The stack itself is formed of an array of SV pointers.
The base of this stack is pointed to by the interpreter variable `PL_stack_base`, of type `SV **`.
The head of the stack is `PL_stack_sp`, and points to the most recently-pushed item.
Items are pushed to the stack by using the `PUSHs()` macro or its variants described above; `XPUSHs()`, `mPUSHs()`, `mXPUSHs()` and the typed versions. Note carefully that the non-`X` versions of these macros do not check the size of the stack and assume it to be big enough. These must be paired with a suitable check of the stack's size, such as the `EXTEND` macro to ensure it is large enough. For example
```
EXTEND(SP, 4);
mPUSHi(10);
mPUSHi(20);
mPUSHi(30);
mPUSHi(40);
```
This is slightly more performant than making four separate checks in four separate `mXPUSHi()` calls.
As a further performance optimisation, the various `PUSH` macros all operate using a local variable `SP`, rather than the interpreter-global variable `PL_stack_sp`. This variable is declared by the `dSP` macro - though it is normally implied by XSUBs and similar so it is rare you have to consider it directly. Once declared, the `PUSH` macros will operate only on this local variable, so before invoking any other perl core functions you must use the `PUTBACK` macro to return the value from the local `SP` variable back to the interpreter variable. Similarly, after calling a perl core function which may have had reason to move the stack or push/pop values to it, you must use the `SPAGAIN` macro which refreshes the local `SP` value back from the interpreter one.
Items are popped from the stack by using the `POPs` macro or its typed versions, There is also a macro `TOPs` that inspects the topmost item without removing it.
Note specifically that SV pointers on the value stack do not contribute to the overall reference count of the xVs being referred to. If newly-created xVs are being pushed to the stack you must arrange for them to be destroyed at a suitable time; usually by using one of the `mPUSH*` macros or `sv_2mortal()` to mortalise the xV.
###
Mark Stack
The value stack stores individual perl scalar values as temporaries between expressions. Some perl expressions operate on entire lists; for that purpose we need to know where on the stack each list begins. This is the purpose of the mark stack.
The mark stack stores integers as I32 values, which are the height of the value stack at the time before the list began; thus the mark itself actually points to the value stack entry one before the list. The list itself starts at `mark + 1`.
The base of this stack is pointed to by the interpreter variable `PL_markstack`, of type `I32 *`.
The head of the stack is `PL_markstack_ptr`, and points to the most recently-pushed item.
Items are pushed to the stack by using the `PUSHMARK()` macro. Even though the stack itself stores (value) stack indices as integers, the `PUSHMARK` macro should be given a stack pointer directly; it will calculate the index offset by comparing to the `PL_stack_sp` variable. Thus almost always the code to perform this is
```
PUSHMARK(SP);
```
Items are popped from the stack by the `POPMARK` macro. There is also a macro `TOPMARK` that inspects the topmost item without removing it. These macros return I32 index values directly. There is also the `dMARK` macro which declares a new SV double-pointer variable, called `mark`, which points at the marked stack slot; this is the usual macro that C code will use when operating on lists given on the stack.
As noted above, the `mark` variable itself will point at the most recently pushed value on the value stack before the list begins, and so the list itself starts at `mark + 1`. The values of the list may be iterated by code such as
```
for(SV **svp = mark + 1; svp <= PL_stack_sp; svp++) {
SV *item = *svp;
...
}
```
Note specifically in the case that the list is already empty, `mark` will equal `PL_stack_sp`.
Because the `mark` variable is converted to a pointer on the value stack, extra care must be taken if `EXTEND` or any of the `XPUSH` macros are invoked within the function, because the stack may need to be moved to extend it and so the existing pointer will now be invalid. If this may be a problem, a possible solution is to track the mark offset as an integer and track the mark itself later on after the stack had been moved.
```
I32 markoff = POPMARK;
...
SP **mark = PL_stack_base + markoff;
```
###
Temporaries Stack
As noted above, xV references on the main value stack do not contribute to the reference count of an xV, and so another mechanism is used to track when temporary values which live on the stack must be released. This is the job of the temporaries stack.
The temporaries stack stores pointers to xVs whose reference counts will be decremented soon.
The base of this stack is pointed to by the interpreter variable `PL_tmps_stack`, of type `SV **`.
The head of the stack is indexed by `PL_tmps_ix`, an integer which stores the index in the array of the most recently-pushed item.
There is no public API to directly push items to the temporaries stack. Instead, the API function `sv_2mortal()` is used to mortalize an xV, adding its address to the temporaries stack.
Likewise, there is no public API to read values from the temporaries stack. Instead, the macros `SAVETMPS` and `FREETMPS` are used. The `SAVETMPS` macro establishes the base levels of the temporaries stack, by capturing the current value of `PL_tmps_ix` into `PL_tmps_floor` and saving the previous value to the save stack. Thereafter, whenever `FREETMPS` is invoked all of the temporaries that have been pushed since that level are reclaimed.
While it is common to see these two macros in pairs within an `ENTER`/ `LEAVE` pair, it is not necessary to match them. It is permitted to invoke `FREETMPS` multiple times since the most recent `SAVETMPS`; for example in a loop iterating over elements of a list. While you can invoke `SAVETMPS` multiple times within a scope pair, it is unlikely to be useful. Subsequent invocations will move the temporaries floor further up, thus effectively trapping the existing temporaries to only be released at the end of the scope.
###
Save Stack
The save stack is used by perl to implement the `local` keyword and other similar behaviours; any cleanup operations that need to be performed when leaving the current scope. Items pushed to this stack generally capture the current value of some internal variable or state, which will be restored when the scope is unwound due to leaving, `return`, `die`, `goto` or other reasons.
Whereas other perl internal stacks store individual items all of the same type (usually SV pointers or integers), the items pushed to the save stack are formed of many different types, having multiple fields to them. For example, the `SAVEt_INT` type needs to store both the address of the `int` variable to restore, and the value to restore it to. This information could have been stored using fields of a `struct`, but would have to be large enough to store three pointers in the largest case, which would waste a lot of space in most of the smaller cases.
Instead, the stack stores information in a variable-length encoding of `ANY` structures. The final value pushed is stored in the `UV` field which encodes the kind of item held by the preceding items; the count and types of which will depend on what kind of item is being stored. The kind field is pushed last because that will be the first field to be popped when unwinding items from the stack.
The base of this stack is pointed to by the interpreter variable `PL_savestack`, of type `ANY *`.
The head of the stack is indexed by `PL_savestack_ix`, an integer which stores the index in the array at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item).
Items are pushed to the save stack by using the various `SAVE...()` macros. Many of these macros take a variable and store both its address and current value on the save stack, ensuring that value gets restored on scope exit.
```
SAVEI8(i8)
SAVEI16(i16)
SAVEI32(i32)
SAVEINT(i)
...
```
There are also a variety of other special-purpose macros which save particular types or values of interest. `SAVETMPS` has already been mentioned above. Others include `SAVEFREEPV` which arranges for a PV (i.e. a string buffer) to be freed, or `SAVEDESTRUCTOR` which arranges for a given function pointer to be invoked on scope exit. A full list of such macros can be found in *scope.h*.
There is no public API for popping individual values or items from the save stack. Instead, via the scope stack, the `ENTER` and `LEAVE` pair form a way to start and stop nested scopes. Leaving a nested scope via `LEAVE` will restore all of the saved values that had been pushed since the most recent `ENTER`.
###
Scope Stack
As with the mark stack to the value stack, the scope stack forms a pair with the save stack. The scope stack stores the height of the save stack at which nested scopes begin, and allows the save stack to be unwound back to that point when the scope is left.
When perl is built with debugging enabled, there is a second part to this stack storing human-readable string names describing the type of stack context. Each push operation saves the name as well as the height of the save stack, and each pop operation checks the topmost name with what is expected, causing an assertion failure if the name does not match.
The base of this stack is pointed to by the interpreter variable `PL_scopestack`, of type `I32 *`. If enabled, the scope stack names are stored in a separate array pointed to by `PL_scopestack_name`, of type `const char **`.
The head of the stack is indexed by `PL_scopestack_ix`, an integer which stores the index of the array or arrays at which the next item should be pushed. (Note that this is different to most other stacks, which reference the most recently-pushed item).
Values are pushed to the scope stack using the `ENTER` macro, which begins a new nested scope. Any items pushed to the save stack are then restored at the next nested invocation of the `LEAVE` macro.
Dynamic Scope and the Context Stack
------------------------------------
**Note:** this section describes a non-public internal API that is subject to change without notice.
###
Introduction to the context stack
In Perl, dynamic scoping refers to the runtime nesting of things like subroutine calls, evals etc, as well as the entering and exiting of block scopes. For example, the restoring of a `local`ised variable is determined by the dynamic scope.
Perl tracks the dynamic scope by a data structure called the context stack, which is an array of `PERL_CONTEXT` structures, and which is itself a big union for all the types of context. Whenever a new scope is entered (such as a block, a `for` loop, or a subroutine call), a new context entry is pushed onto the stack. Similarly when leaving a block or returning from a subroutine call etc. a context is popped. Since the context stack represents the current dynamic scope, it can be searched. For example, `next LABEL` searches back through the stack looking for a loop context that matches the label; `return` pops contexts until it finds a sub or eval context or similar; `caller` examines sub contexts on the stack.
Each context entry is labelled with a context type, `cx_type`. Typical context types are `CXt_SUB`, `CXt_EVAL` etc., as well as `CXt_BLOCK` and `CXt_NULL` which represent a basic scope (as pushed by `pp_enter`) and a sort block. The type determines which part of the context union are valid.
The main division in the context struct is between a substitution scope (`CXt_SUBST`) and block scopes, which are everything else. The former is just used while executing `s///e`, and won't be discussed further here.
All the block scope types share a common base, which corresponds to `CXt_BLOCK`. This stores the old values of various scope-related variables like `PL_curpm`, as well as information about the current scope, such as `gimme`. On scope exit, the old variables are restored.
Particular block scope types store extra per-type information. For example, `CXt_SUB` stores the currently executing CV, while the various for loop types might hold the original loop variable SV. On scope exit, the per-type data is processed; for example the CV has its reference count decremented, and the original loop variable is restored.
The macro `cxstack` returns the base of the current context stack, while `cxstack_ix` is the index of the current frame within that stack.
In fact, the context stack is actually part of a stack-of-stacks system; whenever something unusual is done such as calling a `DESTROY` or tie handler, a new stack is pushed, then popped at the end.
Note that the API described here changed considerably in perl 5.24; prior to that, big macros like `PUSHBLOCK` and `POPSUB` were used; in 5.24 they were replaced by the inline static functions described below. In addition, the ordering and detail of how these macros/function work changed in many ways, often subtly. In particular they didn't handle saving the savestack and temps stack positions, and required additional `ENTER`, `SAVETMPS` and `LEAVE` compared to the new functions. The old-style macros will not be described further.
###
Pushing contexts
For pushing a new context, the two basic functions are `cx = cx_pushblock()`, which pushes a new basic context block and returns its address, and a family of similar functions with names like `cx_pushsub(cx)` which populate the additional type-dependent fields in the `cx` struct. Note that `CXt_NULL` and `CXt_BLOCK` don't have their own push functions, as they don't store any data beyond that pushed by `cx_pushblock`.
The fields of the context struct and the arguments to the `cx_*` functions are subject to change between perl releases, representing whatever is convenient or efficient for that release.
A typical context stack pushing can be found in `pp_entersub`; the following shows a simplified and stripped-down example of a non-XS call, along with comments showing roughly what each function does.
```
dMARK;
U8 gimme = GIMME_V;
bool hasargs = cBOOL(PL_op->op_flags & OPf_STACKED);
OP *retop = PL_op->op_next;
I32 old_ss_ix = PL_savestack_ix;
CV *cv = ....;
/* ... make mortal copies of stack args which are PADTMPs here ... */
/* ... do any additional savestack pushes here ... */
/* Now push a new context entry of type 'CXt_SUB'; initially just
* doing the actions common to all block types: */
cx = cx_pushblock(CXt_SUB, gimme, MARK, old_ss_ix);
/* this does (approximately):
CXINC; /* cxstack_ix++ (grow if necessary) */
cx = CX_CUR(); /* and get the address of new frame */
cx->cx_type = CXt_SUB;
cx->blk_gimme = gimme;
cx->blk_oldsp = MARK - PL_stack_base;
cx->blk_oldsaveix = old_ss_ix;
cx->blk_oldcop = PL_curcop;
cx->blk_oldmarksp = PL_markstack_ptr - PL_markstack;
cx->blk_oldscopesp = PL_scopestack_ix;
cx->blk_oldpm = PL_curpm;
cx->blk_old_tmpsfloor = PL_tmps_floor;
PL_tmps_floor = PL_tmps_ix;
*/
/* then update the new context frame with subroutine-specific info,
* such as the CV about to be executed: */
cx_pushsub(cx, cv, retop, hasargs);
/* this does (approximately):
cx->blk_sub.cv = cv;
cx->blk_sub.olddepth = CvDEPTH(cv);
cx->blk_sub.prevcomppad = PL_comppad;
cx->cx_type |= (hasargs) ? CXp_HASARGS : 0;
cx->blk_sub.retop = retop;
SvREFCNT_inc_simple_void_NN(cv);
*/
```
Note that `cx_pushblock()` sets two new floors: for the args stack (to `MARK`) and the temps stack (to `PL_tmps_ix`). While executing at this scope level, every `nextstate` (amongst others) will reset the args and tmps stack levels to these floors. Note that since `cx_pushblock` uses the current value of `PL_tmps_ix` rather than it being passed as an arg, this dictates at what point `cx_pushblock` should be called. In particular, any new mortals which should be freed only on scope exit (rather than at the next `nextstate`) should be created first.
Most callers of `cx_pushblock` simply set the new args stack floor to the top of the previous stack frame, but for `CXt_LOOP_LIST` it stores the items being iterated over on the stack, and so sets `blk_oldsp` to the top of these items instead. Note that, contrary to its name, `blk_oldsp` doesn't always represent the value to restore `PL_stack_sp` to on scope exit.
Note the early capture of `PL_savestack_ix` to `old_ss_ix`, which is later passed as an arg to `cx_pushblock`. In the case of `pp_entersub`, this is because, although most values needing saving are stored in fields of the context struct, an extra value needs saving only when the debugger is running, and it doesn't make sense to bloat the struct for this rare case. So instead it is saved on the savestack. Since this value gets calculated and saved before the context is pushed, it is necessary to pass the old value of `PL_savestack_ix` to `cx_pushblock`, to ensure that the saved value gets freed during scope exit. For most users of `cx_pushblock`, where nothing needs pushing on the save stack, `PL_savestack_ix` is just passed directly as an arg to `cx_pushblock`.
Note that where possible, values should be saved in the context struct rather than on the save stack; it's much faster that way.
Normally `cx_pushblock` should be immediately followed by the appropriate `cx_pushfoo`, with nothing between them; this is because if code in-between could die (e.g. a warning upgraded to fatal), then the context stack unwinding code in `dounwind` would see (in the example above) a `CXt_SUB` context frame, but without all the subroutine-specific fields set, and crashes would soon ensue.
Where the two must be separate, initially set the type to `CXt_NULL` or `CXt_BLOCK`, and later change it to `CXt_foo` when doing the `cx_pushfoo`. This is exactly what `pp_enteriter` does, once it's determined which type of loop it's pushing.
###
Popping contexts
Contexts are popped using `cx_popsub()` etc. and `cx_popblock()`. Note however, that unlike `cx_pushblock`, neither of these functions actually decrement the current context stack index; this is done separately using `CX_POP()`.
There are two main ways that contexts are popped. During normal execution as scopes are exited, functions like `pp_leave`, `pp_leaveloop` and `pp_leavesub` process and pop just one context using `cx_popfoo` and `cx_popblock`. On the other hand, things like `pp_return` and `next` may have to pop back several scopes until a sub or loop context is found, and exceptions (such as `die`) need to pop back contexts until an eval context is found. Both of these are accomplished by `dounwind()`, which is capable of processing and popping all contexts above the target one.
Here is a typical example of context popping, as found in `pp_leavesub` (simplified slightly):
```
U8 gimme;
PERL_CONTEXT *cx;
SV **oldsp;
OP *retop;
cx = CX_CUR();
gimme = cx->blk_gimme;
oldsp = PL_stack_base + cx->blk_oldsp; /* last arg of previous frame */
if (gimme == G_VOID)
PL_stack_sp = oldsp;
else
leave_adjust_stacks(oldsp, oldsp, gimme, 0);
CX_LEAVE_SCOPE(cx);
cx_popsub(cx);
cx_popblock(cx);
retop = cx->blk_sub.retop;
CX_POP(cx);
return retop;
```
The steps above are in a very specific order, designed to be the reverse order of when the context was pushed. The first thing to do is to copy and/or protect any return arguments and free any temps in the current scope. Scope exits like an rvalue sub normally return a mortal copy of their return args (as opposed to lvalue subs). It is important to make this copy before the save stack is popped or variables are restored, or bad things like the following can happen:
```
sub f { my $x =...; $x } # $x freed before we get to copy it
sub f { /(...)/; $1 } # PL_curpm restored before $1 copied
```
Although we wish to free any temps at the same time, we have to be careful not to free any temps which are keeping return args alive; nor to free the temps we have just created while mortal copying return args. Fortunately, `leave_adjust_stacks()` is capable of making mortal copies of return args, shifting args down the stack, and only processing those entries on the temps stack that are safe to do so.
In void context no args are returned, so it's more efficient to skip calling `leave_adjust_stacks()`. Also in void context, a `nextstate` op is likely to be imminently called which will do a `FREETMPS`, so there's no need to do that either.
The next step is to pop savestack entries: `CX_LEAVE_SCOPE(cx)` is just defined as `LEAVE_SCOPE(cx->blk_oldsaveix)`. Note that during the popping, it's possible for perl to call destructors, call `STORE` to undo localisations of tied vars, and so on. Any of these can die or call `exit()`. In this case, `dounwind()` will be called, and the current context stack frame will be re-processed. Thus it is vital that all steps in popping a context are done in such a way to support reentrancy. The other alternative, of decrementing `cxstack_ix` *before* processing the frame, would lead to leaks and the like if something died halfway through, or overwriting of the current frame.
`CX_LEAVE_SCOPE` itself is safely re-entrant: if only half the savestack items have been popped before dying and getting trapped by eval, then the `CX_LEAVE_SCOPE`s in `dounwind` or `pp_leaveeval` will continue where the first one left off.
The next step is the type-specific context processing; in this case `cx_popsub`. In part, this looks like:
```
cv = cx->blk_sub.cv;
CvDEPTH(cv) = cx->blk_sub.olddepth;
cx->blk_sub.cv = NULL;
SvREFCNT_dec(cv);
```
where its processing the just-executed CV. Note that before it decrements the CV's reference count, it nulls the `blk_sub.cv`. This means that if it re-enters, the CV won't be freed twice. It also means that you can't rely on such type-specific fields having useful values after the return from `cx_popfoo`.
Next, `cx_popblock` restores all the various interpreter vars to their previous values or previous high water marks; it expands to:
```
PL_markstack_ptr = PL_markstack + cx->blk_oldmarksp;
PL_scopestack_ix = cx->blk_oldscopesp;
PL_curpm = cx->blk_oldpm;
PL_curcop = cx->blk_oldcop;
PL_tmps_floor = cx->blk_old_tmpsfloor;
```
Note that it *doesn't* restore `PL_stack_sp`; as mentioned earlier, which value to restore it to depends on the context type (specifically `for (list) {}`), and what args (if any) it returns; and that will already have been sorted out earlier by `leave_adjust_stacks()`.
Finally, the context stack pointer is actually decremented by `CX_POP(cx)`. After this point, it's possible that that the current context frame could be overwritten by other contexts being pushed. Although things like ties and `DESTROY` are supposed to work within a new context stack, it's best not to assume this. Indeed on debugging builds, `CX_POP(cx)` deliberately sets `cx` to null to detect code that is still relying on the field values in that context frame. Note in the `pp_leavesub()` example above, we grab `blk_sub.retop` *before* calling `CX_POP`.
###
Redoing contexts
Finally, there is `cx_topblock(cx)`, which acts like a super-`nextstate` as regards to resetting various vars to their base values. It is used in places like `pp_next`, `pp_redo` and `pp_goto` where rather than exiting a scope, we want to re-initialise the scope. As well as resetting `PL_stack_sp` like `nextstate`, it also resets `PL_markstack_ptr`, `PL_scopestack_ix` and `PL_curpm`. Note that it doesn't do a `FREETMPS`.
Slab-based operator allocation
-------------------------------
**Note:** this section describes a non-public internal API that is subject to change without notice.
Perl's internal error-handling mechanisms implement `die` (and its internal equivalents) using longjmp. If this occurs during lexing, parsing or compilation, we must ensure that any ops allocated as part of the compilation process are freed. (Older Perl versions did not adequately handle this situation: when failing a parse, they would leak ops that were stored in C `auto` variables and not linked anywhere else.)
To handle this situation, Perl uses *op slabs* that are attached to the currently-compiling CV. A slab is a chunk of allocated memory. New ops are allocated as regions of the slab. If the slab fills up, a new one is created (and linked from the previous one). When an error occurs and the CV is freed, any ops remaining are freed.
Each op is preceded by two pointers: one points to the next op in the slab, and the other points to the slab that owns it. The next-op pointer is needed so that Perl can iterate over a slab and free all its ops. (Op structures are of different sizes, so the slab's ops can't merely be treated as a dense array.) The slab pointer is needed for accessing a reference count on the slab: when the last op on a slab is freed, the slab itself is freed.
The slab allocator puts the ops at the end of the slab first. This will tend to allocate the leaves of the op tree first, and the layout will therefore hopefully be cache-friendly. In addition, this means that there's no need to store the size of the slab (see below on why slabs vary in size), because Perl can follow pointers to find the last op.
It might seem possible to eliminate slab reference counts altogether, by having all ops implicitly attached to `PL_compcv` when allocated and freed when the CV is freed. That would also allow `op_free` to skip `FreeOp` altogether, and thus free ops faster. But that doesn't work in those cases where ops need to survive beyond their CVs, such as re-evals.
The CV also has to have a reference count on the slab. Sometimes the first op created is immediately freed. If the reference count of the slab reaches 0, then it will be freed with the CV still pointing to it.
CVs use the `CVf_SLABBED` flag to indicate that the CV has a reference count on the slab. When this flag is set, the slab is accessible via `CvSTART` when `CvROOT` is not set, or by subtracting two pointers `(2*sizeof(I32 *))` from `CvROOT` when it is set. The alternative to this approach of sneaking the slab into `CvSTART` during compilation would be to enlarge the `xpvcv` struct by another pointer. But that would make all CVs larger, even though slab-based op freeing is typically of benefit only for programs that make significant use of string eval.
When the `CVf_SLABBED` flag is set, the CV takes responsibility for freeing the slab. If `CvROOT` is not set when the CV is freed or undeffed, it is assumed that a compilation error has occurred, so the op slab is traversed and all the ops are freed.
Under normal circumstances, the CV forgets about its slab (decrementing the reference count) when the root is attached. So the slab reference counting that happens when ops are freed takes care of freeing the slab. In some cases, the CV is told to forget about the slab (`cv_forget_slab`) precisely so that the ops can survive after the CV is done away with.
Forgetting the slab when the root is attached is not strictly necessary, but avoids potential problems with `CvROOT` being written over. There is code all over the place, both in core and on CPAN, that does things with `CvROOT`, so forgetting the slab makes things more robust and avoids potential problems.
Since the CV takes ownership of its slab when flagged, that flag is never copied when a CV is cloned, as one CV could free a slab that another CV still points to, since forced freeing of ops ignores the reference count (but asserts that it looks right).
To avoid slab fragmentation, freed ops are marked as freed and attached to the slab's freed chain (an idea stolen from DBM::Deep). Those freed ops are reused when possible. Not reusing freed ops would be simpler, but it would result in significantly higher memory usage for programs with large `if (DEBUG) {...}` blocks.
`SAVEFREEOP` is slightly problematic under this scheme. Sometimes it can cause an op to be freed after its CV. If the CV has forcibly freed the ops on its slab and the slab itself, then we will be fiddling with a freed slab. Making `SAVEFREEOP` a no-op doesn't help, as sometimes an op can be savefreed when there is no compilation error, so the op would never be freed. It holds a reference count on the slab, so the whole slab would leak. So `SAVEFREEOP` now sets a special flag on the op (`->op_savefree`). The forced freeing of ops after a compilation error won't free any ops thus marked.
Since many pieces of code create tiny subroutines consisting of only a few ops, and since a huge slab would be quite a bit of baggage for those to carry around, the first slab is always very small. To avoid allocating too many slabs for a single CV, each subsequent slab is twice the size of the previous.
Smartmatch expects to be able to allocate an op at run time, run it, and then throw it away. For that to work the op is simply malloced when `PL_compcv` hasn't been set up. So all slab-allocated ops are marked as such (`->op_slabbed`), to distinguish them from malloced ops.
AUTHORS
-------
Until May 1997, this document was maintained by Jeff Okamoto <[email protected]>. It is now maintained as part of Perl itself by the Perl 5 Porters <[email protected]>.
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy.
SEE ALSO
---------
<perlapi>, <perlintern>, <perlxs>, <perlembed>
| programming_docs |
perl Test2::Event::Pass Test2::Event::Pass
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Pass - Event for a simple passing assertion
DESCRIPTION
-----------
This is an optimal representation of a passing assertion.
SYNOPSIS
--------
```
use Test2::API qw/context/;
sub pass {
my ($name) = @_;
my $ctx = context();
$ctx->pass($name);
$ctx->release;
}
```
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Fatal Fatal
=====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [BEST PRACTICE](#BEST-PRACTICE)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Fatal - Replace functions with equivalents which succeed or die
SYNOPSIS
--------
```
use Fatal qw(open close);
open(my $fh, "<", $filename); # No need to check errors!
use File::Copy qw(move);
use Fatal qw(move);
move($file1, $file2); # No need to check errors!
sub juggle { . . . }
Fatal->import('juggle');
```
BEST PRACTICE
--------------
**Fatal has been obsoleted by the new <autodie> pragma.** Please use <autodie> in preference to `Fatal`. <autodie> supports lexical scoping, throws real exception objects, and provides much nicer error messages.
The use of `:void` with Fatal is discouraged.
DESCRIPTION
-----------
`Fatal` provides a way to conveniently replace functions which normally return a false value when they fail with equivalents which raise exceptions if they are not successful. This lets you use these functions without having to test their return values explicitly on each call. Exceptions can be caught using `eval{}`. See <perlfunc> and <perlvar> for details.
The do-or-die equivalents are set up simply by calling Fatal's `import` routine, passing it the names of the functions to be replaced. You may wrap both user-defined functions and overridable CORE operators (except `exec`, `system`, `print`, or any other built-in that cannot be expressed via prototypes) in this way.
If the symbol `:void` appears in the import list, then functions named later in that import list raise an exception only when these are called in void context--that is, when their return values are ignored. For example
```
use Fatal qw/:void open close/;
# properly checked, so no exception raised on error
if (not open(my $fh, '<', '/bogotic') {
warn "Can't open /bogotic: $!";
}
# not checked, so error raises an exception
close FH;
```
The use of `:void` is discouraged, as it can result in exceptions not being thrown if you *accidentally* call a method without void context. Use <autodie> instead if you need to be able to disable autodying/Fatal behaviour for a small block of code.
DIAGNOSTICS
-----------
Bad subroutine name for Fatal: %s You've called `Fatal` with an argument that doesn't look like a subroutine name, nor a switch that this version of Fatal understands.
%s is not a Perl subroutine You've asked `Fatal` to try and replace a subroutine which does not exist, or has not yet been defined.
%s is neither a builtin, nor a Perl subroutine You've asked `Fatal` to replace a subroutine, but it's not a Perl built-in, and `Fatal` couldn't find it as a regular subroutine. It either doesn't exist or has not yet been defined.
Cannot make the non-overridable %s fatal You've tried to use `Fatal` on a Perl built-in that can't be overridden, such as `print` or `system`, which means that `Fatal` can't help you, although some other modules might. See the ["SEE ALSO"](#SEE-ALSO) section of this documentation.
Internal error: %s You've found a bug in `Fatal`. Please report it using the `perlbug` command.
BUGS
----
`Fatal` clobbers the context in which a function is called and always makes it a scalar context, except when the `:void` tag is used. This problem does not exist in <autodie>.
"Used only once" warnings can be generated when `autodie` or `Fatal` is used with package filehandles (eg, `FILE`). It's strongly recommended you use scalar filehandles instead.
AUTHOR
------
Original module by Lionel Cons (CERN).
Prototype updates by Ilya Zakharevich <[email protected]>.
<autodie> support, bugfixes, extended diagnostics, `system` support, and major overhauling by Paul Fenwick <[email protected]>
LICENSE
-------
This module is free software, you may distribute it under the same terms as Perl itself.
SEE ALSO
---------
<autodie> for a nicer way to use lexical Fatal.
<IPC::System::Simple> for a similar idea for calls to `system()` and backticks.
perl CPAN::Meta::History::Meta_1_4 CPAN::Meta::History::Meta\_1\_4
===============================
CONTENTS
--------
* [NAME](#NAME)
* [PREFACE](#PREFACE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FORMAT](#FORMAT)
* [TERMINOLOGY](#TERMINOLOGY)
* [HEADER](#HEADER)
* [FIELDS](#FIELDS)
+ [meta-spec](#meta-spec)
+ [name](#name)
+ [version](#version)
+ [abstract](#abstract)
+ [author](#author)
+ [license](#license)
+ [distribution\_type](#distribution_type)
+ [requires](#requires)
+ [recommends](#recommends)
+ [build\_requires](#build_requires)
+ [configure\_requires](#configure_requires)
+ [conflicts](#conflicts)
+ [dynamic\_config](#dynamic_config)
+ [private](#private)
+ [provides](#provides)
+ [no\_index](#no_index)
- [file](#file)
- [directory](#directory)
- [package](#package)
- [namespace](#namespace)
+ [keywords](#keywords)
+ [resources](#resources)
+ [generated\_by](#generated_by)
* [VERSION SPECIFICATIONS](#VERSION-SPECIFICATIONS)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
CPAN::Meta::History::Meta\_1\_4 - Version 1.4 metadata specification for META.yml
PREFACE
-------
This is a historical copy of the version 1.4 specification for *META.yml* files, copyright by Ken Williams and licensed under the same terms as Perl itself.
Modifications from the original:
* Various spelling corrections
* Include list of valid licenses from <Module::Build> 0.2807 rather than linking to the module, with minor updates to text and links to reflect versions at the time of publication.
* Fixed some dead links to point to active resources.
SYNOPSIS
--------
```
--- #YAML:1.0
name: Module-Build
abstract: Build and install Perl modules
version: 0.20
author:
- Ken Williams <[email protected]>
license: perl
distribution_type: module
requires:
Config: 0
Cwd: 0
Data::Dumper: 0
ExtUtils::Install: 0
File::Basename: 0
File::Compare: 0
File::Copy: 0
File::Find: 0
File::Path: 0
File::Spec: 0
IO::File: 0
perl: 5.005_03
recommends:
Archive::Tar: 1.00
ExtUtils::Install: 0.3
ExtUtils::ParseXS: 2.02
Pod::Text: 0
YAML: 0.35
build_requires:
Test: 0
resources:
license: http://dev.perl.org/licenses/
meta-spec:
version: 1.4
url: http://module-build.sourceforge.net/META-spec-v1.3.html
generated_by: Module::Build version 0.20
```
DESCRIPTION
-----------
This document describes version 1.4 of the *META.yml* specification.
The *META.yml* file describes important properties of contributed Perl distributions such as the ones found on CPAN. It is typically created by tools like Module::Build, Module::Install, and ExtUtils::MakeMaker.
The fields in the *META.yml* file are meant to be helpful for people maintaining module collections (like CPAN), for people writing installation tools (like CPAN.pm or CPANPLUS), or just for people who want to know some stuff about a distribution before downloading it and starting to install it.
*Note: The latest stable version of this specification can always be found at <http://module-build.sourceforge.net/META-spec-current.html>, and the latest development version (which may include things that won't make it into the stable version) can always be found at <http://module-build.sourceforge.net/META-spec-blead.html>.*
FORMAT
------
*META.yml* files are written in the YAML format (see <http://www.yaml.org/>).
See the following links to learn why we chose YAML instead of, say, XML or Data::Dumper:
* [Module::Build design plans](http://www.nntp.perl.org/group/perl.makemaker/2002/04/msg407.html)
* [Not keen on YAML](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1353.html)
* [META Concerns](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1385.html)
TERMINOLOGY
-----------
distribution This is the primary object described by the *META.yml* specification. In the context of this document it usually refers to a collection of modules, scripts, and/or documents that are distributed together for other developers to use. Examples of distributions are `Class-Container`, `libwww-perl`, or `DBI`.
module This refers to a reusable library of code typically contained in a single file. Currently, we primarily talk of perl modules, but this specification should be open enough to apply to other languages as well (ex. python, ruby). Examples of modules are `Class::Container`, `LWP::Simple`, or `DBD::File`.
HEADER
------
The first line of a *META.yml* file should be a valid YAML document header like `"--- #YAML:1.0"`.
FIELDS
------
The rest of the *META.yml* file is one big YAML mapping whose keys are described here.
###
meta-spec
Example:
```
meta-spec:
version: 1.4
url: http://module-build.sourceforge.net/META-spec-v1.3.html
```
(Spec 1.1) [required] {URL} This field indicates the location of the version of the META.yml specification used.
### name
Example:
```
name: Module-Build
```
(Spec 1.0) [required] {string} The name of the distribution which is often created by taking the "main module" in the distribution and changing "::" to "-". Sometimes it's completely different, however, as in the case of the libwww-perl distribution (see <http://search.cpan.org/dist/libwww-perl/>).
### version
Example:
```
version: 0.20
```
(Spec 1.0) [required] {version} The version of the distribution to which the *META.yml* file refers.
### abstract
Example:
```
abstract: Build and install Perl modules.
```
(Spec 1.1) [required] {string} A short description of the purpose of the distribution.
### author
Example:
```
author:
- Ken Williams <[email protected]>
```
(Spec 1.1) [required] {list of strings} A YAML sequence indicating the author(s) of the distribution. The preferred form is author-name <email-address>.
### license
Example:
```
license: perl
```
(Spec 1.0) [required] {string} The license under which this distribution may be used and redistributed.
Must be one of the following licenses:
apache The distribution is licensed under the Apache Software License version 1.1 (<http://opensource.org/licenses/Apache-1.1>).
artistic The distribution is licensed under the Artistic License version 1, as specified by the Artistic file in the standard perl distribution (<http://opensource.org/licenses/Artistic-Perl-1.0>).
bsd The distribution is licensed under the BSD 3-Clause License (<http://opensource.org/licenses/BSD-3-Clause>).
gpl The distribution is distributed under the terms of the GNU General Public License version 2 (<http://opensource.org/licenses/GPL-2.0>).
lgpl The distribution is distributed under the terms of the GNU Lesser General Public License version 2 (<http://opensource.org/licenses/LGPL-2.1>).
mit The distribution is licensed under the MIT License (<http://opensource.org/licenses/MIT>).
mozilla The distribution is licensed under the Mozilla Public License. (<http://opensource.org/licenses/MPL-1.0> or <http://opensource.org/licenses/MPL-1.1>)
open\_source The distribution is licensed under some other Open Source Initiative-approved license listed at <http://www.opensource.org/licenses/>.
perl The distribution may be copied and redistributed under the same terms as perl itself (this is by far the most common licensing option for modules on CPAN). This is a dual license, in which the user may choose between either the GPL or the Artistic license.
restrictive The distribution may not be redistributed without special permission from the author and/or copyright holder.
unrestricted The distribution is licensed under a license that is not approved by [www.opensource.org](http://www.opensource.org/) but that allows distribution without restrictions.
### distribution\_type
Example:
```
distribution_type: module
```
(Spec 1.0) [optional] {string} What kind of stuff is contained in this distribution. Most things on CPAN are `module`s (which can also mean a collection of modules), but some things are `script`s.
Unfortunately this field is basically meaningless, since many distributions are hybrids of several kinds of things, or some new thing, or subjectively different in focus depending on who's using them. Tools like Module::Build and MakeMaker will likely stop generating this field.
### requires
Example:
```
requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl prerequisites this distribution requires for proper operation. The keys are the names of the prerequisites (module names or 'perl'), and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
### recommends
Example:
```
recommends:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl prerequisites this distribution recommends for enhanced operation. The keys are the names of the prerequisites (module names or 'perl'), and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
*ALTERNATIVE: It may be desirable to present to the user which features depend on which modules so they can make an informed decision about which recommended modules to install.*
Example:
```
optional_features:
foo:
description: Provides the ability to blah.
requires:
Data::Dumper: 0
File::Find: 1.03
```
*(Spec 1.1) [optional] {map} A YAML mapping of names for optional features which are made available when its requirements are met. For each feature a description is provided along with any of ["requires"](#requires), ["build\_requires"](#build_requires), and ["conflicts"](#conflicts), which have the same meaning in this subcontext as described elsewhere in this document.*
### build\_requires
Example:
```
build_requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl prerequisites required for building and/or testing of this distribution. The keys are the names of the prerequisites (module names or 'perl'), and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS). These dependencies are not required after the distribution is installed.
### configure\_requires
Example:
```
configure_requires:
Module::Build: 0.2809
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.4) [optional] {map} A YAML mapping indicating the Perl prerequisites required before configuring this distribution. The keys are the names of the prerequisites (module names or 'perl'), and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS). These dependencies are not required after the distribution is installed.
### conflicts
Example:
```
conflicts:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating any items that cannot be installed while this distribution is installed. This is a pretty uncommon situation. The keys for `conflicts` are the item names (module names or 'perl'), and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
### dynamic\_config
Example:
```
dynamic_config: 0
```
(Spec 1.0) [optional] {boolean} A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed when building this distribution, or whether it can be built, tested and installed solely from consulting its metadata file. The main reason to set this to a true value is that your module performs some dynamic configuration (asking questions, sensing the environment, etc.) as part of its build/install process.
Currently Module::Build doesn't actually do anything with this flag - it's probably going to be up to higher-level tools like CPAN to do something useful with it. It can potentially bring lots of security, packaging, and convenience improvements.
If this field is omitted, it defaults to 1 (true).
### private
*(Deprecated)* (Spec 1.0) [optional] {map} This field has been renamed to ["no\_index"](#no_index). See below.
### provides
Example:
```
provides:
Foo::Bar:
file: lib/Foo/Bar.pm
version: 0.27_02
Foo::Bar::Blah:
file: lib/Foo/Bar/Blah.pm
Foo::Bar::Baz:
file: lib/Foo/Bar/Baz.pm
version: 0.3
```
(Spec 1.1) [optional] {map} A YAML mapping that describes all packages provided by this distribution. This information can be (and, in some cases, is) used by distribution and automation mechanisms like PAUSE, CPAN, and search.cpan.org to build indexes saying in which distribution various packages can be found.
When using tools like <Module::Build> that can generate the `provides` mapping for your distribution automatically, make sure you examine what it generates to make sure it makes sense - indexers will usually trust the `provides` field if it's present, rather than scanning through the distribution files themselves to figure out packages and versions. This is a good thing, because it means you can use the `provides` field to tell the indexers precisely what you want indexed about your distribution, rather than relying on them to essentially guess what you want indexed.
### no\_index
Example:
```
no_index:
file:
- My/Module.pm
directory:
- My/Private
package:
- My::Module::Stuff
namespace:
- My::Module::Stuff
```
(Spec 1.1) [optional] {map} A YAML mapping that describes any files, directories, packages, and namespaces that are private (i.e. implementation artifacts) that are not of interest to searching and indexing tools. This is useful when no `provides` field is present.
For example, <http://search.cpan.org/> excludes items listed in `no_index` when searching for POD, meaning files in these directories will not converted to HTML and made public - which is useful if you have example or test PODs that you don't want the search engine to go through.
#### file
(Spec 1.1) [optional] Exclude any listed file(s).
#### directory
(Spec 1.1) [optional] Exclude anything below the listed directory(ies).
[Note: previous editions of the spec had `dir` instead of `directory`, but I think MakeMaker and various users started using `directory`, so in deference we switched to that.]
#### package
(Spec 1.1) [optional] Exclude the listed package(s).
#### namespace
(Spec 1.1) [optional] Excludes anything below the listed namespace(s), but *not* the listed namespace(s) its self.
### keywords
Example:
```
keywords:
- make
- build
- install
```
(Spec 1.1) [optional] {list} A sequence of keywords/phrases that describe this distribution.
### resources
Example:
```
resources:
license: http://dev.perl.org/licenses/
homepage: http://sourceforge.net/projects/module-build
bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=Module-Build
repository: http://sourceforge.net/cvs/?group_id=45731
MailingList: http://lists.sourceforge.net/lists/listinfo/module-build-general
```
(Spec 1.1) [optional] {map} A mapping of any URL resources related to this distribution. All-lower-case keys, such as `homepage`, `license`, and `bugtracker`, are reserved by this specification, as they have "official" meanings defined here in this specification. If you'd like to add your own "special" entries (like the "MailingList" entry above), use at least one upper-case letter.
The current set of official keys is:
homepage The official home of this project on the web.
license An URL for an official statement of this distribution's license.
bugtracker An URL for a bug tracker (e.g. Bugzilla or RT queue) for this project.
### generated\_by
Example:
```
generated_by: Module::Build version 0.20
```
(Spec 1.0) [required] {string} Indicates the tool that was used to create this *META.yml* file. It's good form to include both the name of the tool and its version, but this field is essentially opaque, at least for the moment. If *META.yml* was generated by hand, it is suggested that the author be specified here.
[Note: My *meta\_stats.pl* script which I use to gather statistics regarding *META.yml* usage prefers the form listed above, i.e. it splits on /\s+version\s+/ taking the first field as the name of the tool that generated the file and the second field as version of that tool. RWS]
VERSION SPECIFICATIONS
-----------------------
Some fields require a version specification (ex. ["requires"](#requires), ["recommends"](#recommends), ["build\_requires"](#build_requires), etc.) to indicate the particular version(s) of some other module that may be required as a prerequisite. This section details the version specification formats that are currently supported.
The simplest format for a version specification is just the version number itself, e.g. `2.4`. This means that **at least** version 2.4 must be present. To indicate that **any** version of a prerequisite is okay, even if the prerequisite doesn't define a version at all, use the version `0`.
You may also use the operators < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and != (not equal). For example, the specification `< 2.0` means that any version of the prerequisite less than 2.0 is suitable.
For more complicated situations, version specifications may be AND-ed together using commas. The specification `>= 1.2, != 1.5, < 2.0` indicates a version that must be **at least** 1.2, **less than** 2.0, and **not equal to** 1.5.
SEE ALSO
---------
[CPAN](http://www.cpan.org/)
[CPAN.pm](cpan)
[CPANPLUS](cpanplus)
<Data::Dumper>
<ExtUtils::MakeMaker>
<Module::Build>
<Module::Install>
[XML](http://www.w3.org/XML/)
[YAML](http://www.yaml.org/)
HISTORY
-------
March 14, 2003 (Pi day) * Created version 1.0 of this document.
May 8, 2003 * Added the ["dynamic\_config"](#dynamic_config) field, which was missing from the initial version.
November 13, 2003 * Added more YAML rationale articles.
* Fixed existing link to YAML discussion thread to point to new <http://nntp.x.perl.org/group/> site.
* Added and deprecated the ["private"](#private) field.
* Added ["abstract"](#abstract), `configure`, `requires_packages`, `requires_os`, `excludes_os`, and ["no\_index"](#no_index) fields.
* Bumped version.
November 16, 2003 * Added `generation`, `authored_by` fields.
* Add alternative proposal to the ["recommends"](#recommends) field.
* Add proposal for a `requires_build_tools` field.
December 9, 2003 * Added link to latest version of this specification on CPAN.
* Added section ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
* Chang name from Module::Build::META-spec to CPAN::META::Specification.
* Add proposal for `auto_regenerate` field.
December 15, 2003 * Add `index` field as a compliment to ["no\_index"](#no_index)
* Add ["keywords"](#keywords) field as a means to aid searching distributions.
* Add ["TERMINOLOGY"](#TERMINOLOGY) section to explain certain terms that may be ambiguous.
July 26, 2005 * Removed a bunch of items (generation, requires\_build\_tools, requires\_packages, configure, requires\_os, excludes\_os, auto\_regenerate) that have never actually been supported, but were more like records of brainstorming.
* Changed `authored_by` to ["author"](#author), since that's always been what it's actually called in actual *META.yml* files.
* Added the "==" operator to the list of supported version-checking operators.
* Noted that the ["distribution\_type"](#distribution_type) field is basically meaningless, and shouldn't really be used.
* Clarified ["dynamic\_config"](#dynamic_config) a bit.
August 23, 2005 * Removed the name `CPAN::META::Specification`, since that implies a module that doesn't actually exist.
June 12, 2007 * Added ["configure\_requires"](#configure_requires).
| programming_docs |
perl perlreapi perlreapi
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Callbacks](#Callbacks)
+ [comp](#comp)
+ [exec](#exec)
+ [intuit](#intuit)
+ [checkstr](#checkstr)
+ [free](#free)
+ [Numbered capture callbacks](#Numbered-capture-callbacks)
- [numbered\_buff\_FETCH](#numbered_buff_FETCH)
- [numbered\_buff\_STORE](#numbered_buff_STORE)
- [numbered\_buff\_LENGTH](#numbered_buff_LENGTH)
+ [Named capture callbacks](#Named-capture-callbacks)
- [named\_buff](#named_buff)
- [named\_buff\_iter](#named_buff_iter)
+ [qr\_package](#qr_package)
+ [dupe](#dupe)
+ [op\_comp](#op_comp)
* [The REGEXP structure](#The-REGEXP-structure)
+ [engine](#engine)
+ [mother\_re](#mother_re)
+ [extflags](#extflags)
+ [minlen minlenret](#minlen-minlenret)
+ [gofs](#gofs)
+ [substrs](#substrs)
+ [nparens, lastparen, and lastcloseparen](#nparens,-lastparen,-and-lastcloseparen)
+ [intflags](#intflags)
+ [pprivate](#pprivate)
+ [offs](#offs)
+ [precomp prelen](#precomp-prelen)
+ [paren\_names](#paren_names)
+ [substrs](#substrs1)
+ [subbeg sublen saved\_copy suboffset subcoffset](#subbeg-sublen-saved_copy-suboffset-subcoffset)
+ [wrapped wraplen](#wrapped-wraplen)
+ [seen\_evals](#seen_evals)
+ [refcnt](#refcnt)
* [HISTORY](#HISTORY)
* [AUTHORS](#AUTHORS)
* [LICENSE](#LICENSE)
NAME
----
perlreapi - Perl regular expression plugin interface
DESCRIPTION
-----------
As of Perl 5.9.5 there is a new interface for plugging and using regular expression engines other than the default one.
Each engine is supposed to provide access to a constant structure of the following format:
```
typedef struct regexp_engine {
REGEXP* (*comp) (pTHX_
const SV * const pattern, const U32 flags);
I32 (*exec) (pTHX_
REGEXP * const rx,
char* stringarg,
char* strend, char* strbeg,
SSize_t minend, SV* sv,
void* data, U32 flags);
char* (*intuit) (pTHX_
REGEXP * const rx, SV *sv,
const char * const strbeg,
char *strpos, char *strend, U32 flags,
struct re_scream_pos_data_s *data);
SV* (*checkstr) (pTHX_ REGEXP * const rx);
void (*free) (pTHX_ REGEXP * const rx);
void (*numbered_buff_FETCH) (pTHX_
REGEXP * const rx,
const I32 paren,
SV * const sv);
void (*numbered_buff_STORE) (pTHX_
REGEXP * const rx,
const I32 paren,
SV const * const value);
I32 (*numbered_buff_LENGTH) (pTHX_
REGEXP * const rx,
const SV * const sv,
const I32 paren);
SV* (*named_buff) (pTHX_
REGEXP * const rx,
SV * const key,
SV * const value,
U32 flags);
SV* (*named_buff_iter) (pTHX_
REGEXP * const rx,
const SV * const lastkey,
const U32 flags);
SV* (*qr_package)(pTHX_ REGEXP * const rx);
#ifdef USE_ITHREADS
void* (*dupe) (pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
#endif
REGEXP* (*op_comp) (...);
```
When a regexp is compiled, its `engine` field is then set to point at the appropriate structure, so that when it needs to be used Perl can find the right routines to do so.
In order to install a new regexp handler, `$^H{regcomp}` is set to an integer which (when casted appropriately) resolves to one of these structures. When compiling, the `comp` method is executed, and the resulting `regexp` structure's engine field is expected to point back at the same structure.
The pTHX\_ symbol in the definition is a macro used by Perl under threading to provide an extra argument to the routine holding a pointer back to the interpreter that is executing the regexp. So under threading all routines get an extra argument.
Callbacks
---------
### comp
```
REGEXP* comp(pTHX_ const SV * const pattern, const U32 flags);
```
Compile the pattern stored in `pattern` using the given `flags` and return a pointer to a prepared `REGEXP` structure that can perform the match. See ["The REGEXP structure"](#The-REGEXP-structure) below for an explanation of the individual fields in the REGEXP struct.
The `pattern` parameter is the scalar that was used as the pattern. Previous versions of Perl would pass two `char*` indicating the start and end of the stringified pattern; the following snippet can be used to get the old parameters:
```
STRLEN plen;
char* exp = SvPV(pattern, plen);
char* xend = exp + plen;
```
Since any scalar can be passed as a pattern, it's possible to implement an engine that does something with an array (`"ook" =~ [ qw/ eek hlagh / ]`) or with the non-stringified form of a compiled regular expression (`"ook" =~ qr/eek/`). Perl's own engine will always stringify everything using the snippet above, but that doesn't mean other engines have to.
The `flags` parameter is a bitfield which indicates which of the `msixpn` flags the regex was compiled with. It also contains additional info, such as if `use locale` is in effect.
The `eogc` flags are stripped out before being passed to the comp routine. The regex engine does not need to know if any of these are set, as those flags should only affect what Perl does with the pattern and its match variables, not how it gets compiled and executed.
By the time the comp callback is called, some of these flags have already had effect (noted below where applicable). However most of their effect occurs after the comp callback has run, in routines that read the `rx->extflags` field which it populates.
In general the flags should be preserved in `rx->extflags` after compilation, although the regex engine might want to add or delete some of them to invoke or disable some special behavior in Perl. The flags along with any special behavior they cause are documented below:
The pattern modifiers:
`/m` - RXf\_PMf\_MULTILINE If this is in `rx->extflags` it will be passed to `Perl_fbm_instr` by `pp_split` which will treat the subject string as a multi-line string.
`/s` - RXf\_PMf\_SINGLELINE
`/i` - RXf\_PMf\_FOLD
`/x` - RXf\_PMf\_EXTENDED If present on a regex, `"#"` comments will be handled differently by the tokenizer in some cases.
TODO: Document those cases.
`/p` - RXf\_PMf\_KEEPCOPY TODO: Document this
Character set The character set rules are determined by an enum that is contained in this field. This is still experimental and subject to change, but the current interface returns the rules by use of the in-line function `get_regex_charset(const U32 flags)`. The only currently documented value returned from it is REGEX\_LOCALE\_CHARSET, which is set if `use locale` is in effect. If present in `rx->extflags`, `split` will use the locale dependent definition of whitespace when RXf\_SKIPWHITE or RXf\_WHITE is in effect. ASCII whitespace is defined as per [isSPACE](perlapi#isSPACE), and by the internal macros `is_utf8_space` under UTF-8, and `isSPACE_LC` under `use locale`.
Additional flags:
RXf\_SPLIT This flag was removed in perl 5.18.0. `split ' '` is now special-cased solely in the parser. RXf\_SPLIT is still #defined, so you can test for it. This is how it used to work:
If `split` is invoked as `split ' '` or with no arguments (which really means `split(' ', $_)`, see [split](perlfunc#split)), Perl will set this flag. The regex engine can then check for it and set the SKIPWHITE and WHITE extflags. To do this, the Perl engine does:
```
if (flags & RXf_SPLIT && r->prelen == 1 && r->precomp[0] == ' ')
r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
```
These flags can be set during compilation to enable optimizations in the `split` operator.
RXf\_SKIPWHITE This flag was removed in perl 5.18.0. It is still #defined, so you can set it, but doing so will have no effect. This is how it used to work:
If the flag is present in `rx->extflags` `split` will delete whitespace from the start of the subject string before it's operated on. What is considered whitespace depends on if the subject is a UTF-8 string and if the `RXf_PMf_LOCALE` flag is set.
If RXf\_WHITE is set in addition to this flag, `split` will behave like `split " "` under the Perl engine.
RXf\_START\_ONLY Tells the split operator to split the target string on newlines (`\n`) without invoking the regex engine.
Perl's engine sets this if the pattern is `/^/` (`plen == 1 && *exp == '^'`), even under `/^/s`; see [split](perlfunc). Of course a different regex engine might want to use the same optimizations with a different syntax.
RXf\_WHITE Tells the split operator to split the target string on whitespace without invoking the regex engine. The definition of whitespace varies depending on if the target string is a UTF-8 string and on if RXf\_PMf\_LOCALE is set.
Perl's engine sets this flag if the pattern is `\s+`.
RXf\_NULL Tells the split operator to split the target string on characters. The definition of character varies depending on if the target string is a UTF-8 string.
Perl's engine sets this flag on empty patterns, this optimization makes `split //` much faster than it would otherwise be. It's even faster than `unpack`.
RXf\_NO\_INPLACE\_SUBST Added in perl 5.18.0, this flag indicates that a regular expression might perform an operation that would interfere with inplace substitution. For instance it might contain lookbehind, or assign to non-magical variables (such as $REGMARK and $REGERROR) during matching. `s///` will skip certain optimisations when this is set.
### exec
```
I32 exec(pTHX_ REGEXP * const rx,
char *stringarg, char* strend, char* strbeg,
SSize_t minend, SV* sv,
void* data, U32 flags);
```
Execute a regexp. The arguments are
rx The regular expression to execute.
sv This is the SV to be matched against. Note that the actual char array to be matched against is supplied by the arguments described below; the SV is just used to determine UTF8ness, `pos()` etc.
strbeg Pointer to the physical start of the string.
strend Pointer to the character following the physical end of the string (i.e. the `\0`, if any).
stringarg Pointer to the position in the string where matching should start; it might not be equal to `strbeg` (for example in a later iteration of `/.../g`).
minend Minimum length of string (measured in bytes from `stringarg`) that must match; if the engine reaches the end of the match but hasn't reached this position in the string, it should fail.
data Optimisation data; subject to change.
flags Optimisation flags; subject to change.
### intuit
```
char* intuit(pTHX_
REGEXP * const rx,
SV *sv,
const char * const strbeg,
char *strpos,
char *strend,
const U32 flags,
struct re_scream_pos_data_s *data);
```
Find the start position where a regex match should be attempted, or possibly if the regex engine should not be run because the pattern can't match. This is called, as appropriate, by the core, depending on the values of the `extflags` member of the `regexp` structure.
Arguments:
```
rx: the regex to match against
sv: the SV being matched: only used for utf8 flag; the string
itself is accessed via the pointers below. Note that on
something like an overloaded SV, SvPOK(sv) may be false
and the string pointers may point to something unrelated to
the SV itself.
strbeg: real beginning of string
strpos: the point in the string at which to begin matching
strend: pointer to the byte following the last char of the string
flags currently unused; set to 0
data: currently unused; set to NULL
```
### checkstr
```
SV* checkstr(pTHX_ REGEXP * const rx);
```
Return a SV containing a string that must appear in the pattern. Used by `split` for optimising matches.
### free
```
void free(pTHX_ REGEXP * const rx);
```
Called by Perl when it is freeing a regexp pattern so that the engine can release any resources pointed to by the `pprivate` member of the `regexp` structure. This is only responsible for freeing private data; Perl will handle releasing anything else contained in the `regexp` structure.
###
Numbered capture callbacks
Called to get/set the value of `$``, `$'`, `$&` and their named equivalents, ${^PREMATCH}, ${^POSTMATCH} and ${^MATCH}, as well as the numbered capture groups (`$1`, `$2`, ...).
The `paren` parameter will be `1` for `$1`, `2` for `$2` and so forth, and have these symbolic values for the special variables:
```
${^PREMATCH} RX_BUFF_IDX_CARET_PREMATCH
${^POSTMATCH} RX_BUFF_IDX_CARET_POSTMATCH
${^MATCH} RX_BUFF_IDX_CARET_FULLMATCH
$` RX_BUFF_IDX_PREMATCH
$' RX_BUFF_IDX_POSTMATCH
$& RX_BUFF_IDX_FULLMATCH
```
Note that in Perl 5.17.3 and earlier, the last three constants were also used for the caret variants of the variables.
The names have been chosen by analogy with <Tie::Scalar> methods names with an additional **LENGTH** callback for efficiency. However named capture variables are currently not tied internally but implemented via magic.
#### numbered\_buff\_FETCH
```
void numbered_buff_FETCH(pTHX_ REGEXP * const rx, const I32 paren,
SV * const sv);
```
Fetch a specified numbered capture. `sv` should be set to the scalar to return, the scalar is passed as an argument rather than being returned from the function because when it's called Perl already has a scalar to store the value, creating another one would be redundant. The scalar can be set with `sv_setsv`, `sv_setpvn` and friends, see <perlapi>.
This callback is where Perl untaints its own capture variables under taint mode (see <perlsec>). See the `Perl_reg_numbered_buff_fetch` function in *regcomp.c* for how to untaint capture variables if that's something you'd like your engine to do as well.
#### numbered\_buff\_STORE
```
void (*numbered_buff_STORE) (pTHX_
REGEXP * const rx,
const I32 paren,
SV const * const value);
```
Set the value of a numbered capture variable. `value` is the scalar that is to be used as the new value. It's up to the engine to make sure this is used as the new value (or reject it).
Example:
```
if ("ook" =~ /(o*)/) {
# 'paren' will be '1' and 'value' will be 'ee'
$1 =~ tr/o/e/;
}
```
Perl's own engine will croak on any attempt to modify the capture variables, to do this in another engine use the following callback (copied from `Perl_reg_numbered_buff_store`):
```
void
Example_reg_numbered_buff_store(pTHX_
REGEXP * const rx,
const I32 paren,
SV const * const value)
{
PERL_UNUSED_ARG(rx);
PERL_UNUSED_ARG(paren);
PERL_UNUSED_ARG(value);
if (!PL_localizing)
Perl_croak(aTHX_ PL_no_modify);
}
```
Actually Perl will not *always* croak in a statement that looks like it would modify a numbered capture variable. This is because the STORE callback will not be called if Perl can determine that it doesn't have to modify the value. This is exactly how tied variables behave in the same situation:
```
package CaptureVar;
use parent 'Tie::Scalar';
sub TIESCALAR { bless [] }
sub FETCH { undef }
sub STORE { die "This doesn't get called" }
package main;
tie my $sv => "CaptureVar";
$sv =~ y/a/b/;
```
Because `$sv` is `undef` when the `y///` operator is applied to it, the transliteration won't actually execute and the program won't `die`. This is different to how 5.8 and earlier versions behaved since the capture variables were READONLY variables then; now they'll just die when assigned to in the default engine.
#### numbered\_buff\_LENGTH
```
I32 numbered_buff_LENGTH (pTHX_
REGEXP * const rx,
const SV * const sv,
const I32 paren);
```
Get the `length` of a capture variable. There's a special callback for this so that Perl doesn't have to do a FETCH and run `length` on the result, since the length is (in Perl's case) known from an offset stored in `rx->offs`, this is much more efficient:
```
I32 s1 = rx->offs[paren].start;
I32 s2 = rx->offs[paren].end;
I32 len = t1 - s1;
```
This is a little bit more complex in the case of UTF-8, see what `Perl_reg_numbered_buff_length` does with [is\_utf8\_string\_loclen](perlapi#is_utf8_string_loclen).
###
Named capture callbacks
Called to get/set the value of `%+` and `%-`, as well as by some utility functions in <re>.
There are two callbacks, `named_buff` is called in all the cases the FETCH, STORE, DELETE, CLEAR, EXISTS and SCALAR <Tie::Hash> callbacks would be on changes to `%+` and `%-` and `named_buff_iter` in the same cases as FIRSTKEY and NEXTKEY.
The `flags` parameter can be used to determine which of these operations the callbacks should respond to. The following flags are currently defined:
Which <Tie::Hash> operation is being performed from the Perl level on `%+` or `%+`, if any:
```
RXapif_FETCH
RXapif_STORE
RXapif_DELETE
RXapif_CLEAR
RXapif_EXISTS
RXapif_SCALAR
RXapif_FIRSTKEY
RXapif_NEXTKEY
```
If `%+` or `%-` is being operated on, if any.
```
RXapif_ONE /* %+ */
RXapif_ALL /* %- */
```
If this is being called as `re::regname`, `re::regnames` or `re::regnames_count`, if any. The first two will be combined with `RXapif_ONE` or `RXapif_ALL`.
```
RXapif_REGNAME
RXapif_REGNAMES
RXapif_REGNAMES_COUNT
```
Internally `%+` and `%-` are implemented with a real tied interface via <Tie::Hash::NamedCapture>. The methods in that package will call back into these functions. However the usage of <Tie::Hash::NamedCapture> for this purpose might change in future releases. For instance this might be implemented by magic instead (would need an extension to mgvtbl).
#### named\_buff
```
SV* (*named_buff) (pTHX_ REGEXP * const rx, SV * const key,
SV * const value, U32 flags);
```
#### named\_buff\_iter
```
SV* (*named_buff_iter) (pTHX_
REGEXP * const rx,
const SV * const lastkey,
const U32 flags);
```
### qr\_package
```
SV* qr_package(pTHX_ REGEXP * const rx);
```
The package the qr// magic object is blessed into (as seen by `ref qr//`). It is recommended that engines change this to their package name for identification regardless of if they implement methods on the object.
The package this method returns should also have the internal `Regexp` package in its `@ISA`. `qr//->isa("Regexp")` should always be true regardless of what engine is being used.
Example implementation might be:
```
SV*
Example_qr_package(pTHX_ REGEXP * const rx)
{
PERL_UNUSED_ARG(rx);
return newSVpvs("re::engine::Example");
}
```
Any method calls on an object created with `qr//` will be dispatched to the package as a normal object.
```
use re::engine::Example;
my $re = qr//;
$re->meth; # dispatched to re::engine::Example::meth()
```
To retrieve the `REGEXP` object from the scalar in an XS function use the `SvRX` macro, see ["REGEXP Functions" in perlapi](perlapi#REGEXP-Functions).
```
void meth(SV * rv)
PPCODE:
REGEXP * re = SvRX(sv);
```
### dupe
```
void* dupe(pTHX_ REGEXP * const rx, CLONE_PARAMS *param);
```
On threaded builds a regexp may need to be duplicated so that the pattern can be used by multiple threads. This routine is expected to handle the duplication of any private data pointed to by the `pprivate` member of the `regexp` structure. It will be called with the preconstructed new `regexp` structure as an argument, the `pprivate` member will point at the **old** private structure, and it is this routine's responsibility to construct a copy and return a pointer to it (which Perl will then use to overwrite the field as passed to this routine.)
This allows the engine to dupe its private data but also if necessary modify the final structure if it really must.
On unthreaded builds this field doesn't exist.
### op\_comp
This is private to the Perl core and subject to change. Should be left null.
The REGEXP structure
---------------------
The REGEXP struct is defined in *regexp.h*. All regex engines must be able to correctly build such a structure in their ["comp"](#comp) routine.
The REGEXP structure contains all the data that Perl needs to be aware of to properly work with the regular expression. It includes data about optimisations that Perl can use to determine if the regex engine should really be used, and various other control info that is needed to properly execute patterns in various contexts, such as if the pattern anchored in some way, or what flags were used during the compile, or if the program contains special constructs that Perl needs to be aware of.
In addition it contains two fields that are intended for the private use of the regex engine that compiled the pattern. These are the `intflags` and `pprivate` members. `pprivate` is a void pointer to an arbitrary structure, whose use and management is the responsibility of the compiling engine. Perl will never modify either of these values.
```
typedef struct regexp {
/* what engine created this regexp? */
const struct regexp_engine* engine;
/* what re is this a lightweight copy of? */
struct regexp* mother_re;
/* Information about the match that the Perl core uses to manage
* things */
U32 extflags; /* Flags used both externally and internally */
I32 minlen; /* mininum possible number of chars in */
string to match */
I32 minlenret; /* mininum possible number of chars in $& */
U32 gofs; /* chars left of pos that we search from */
/* substring data about strings that must appear
in the final match, used for optimisations */
struct reg_substr_data *substrs;
U32 nparens; /* number of capture groups */
/* private engine specific data */
U32 intflags; /* Engine Specific Internal flags */
void *pprivate; /* Data private to the regex engine which
created this object. */
/* Data about the last/current match. These are modified during
* matching*/
U32 lastparen; /* highest close paren matched ($+) */
U32 lastcloseparen; /* last close paren matched ($^N) */
regexp_paren_pair *offs; /* Array of offsets for (@-) and
(@+) */
char *subbeg; /* saved or original string so \digit works
forever. */
SV_SAVED_COPY /* If non-NULL, SV which is COW from original */
I32 sublen; /* Length of string pointed by subbeg */
I32 suboffset; /* byte offset of subbeg from logical start of
str */
I32 subcoffset; /* suboffset equiv, but in chars (for @-/@+) */
/* Information about the match that isn't often used */
I32 prelen; /* length of precomp */
const char *precomp; /* pre-compilation regular expression */
char *wrapped; /* wrapped version of the pattern */
I32 wraplen; /* length of wrapped */
I32 seen_evals; /* number of eval groups in the pattern - for
security checks */
HV *paren_names; /* Optional hash of paren names */
/* Refcount of this regexp */
I32 refcnt; /* Refcount of this regexp */
} regexp;
```
The fields are discussed in more detail below:
### `engine`
This field points at a `regexp_engine` structure which contains pointers to the subroutines that are to be used for performing a match. It is the compiling routine's responsibility to populate this field before returning the regexp object.
Internally this is set to `NULL` unless a custom engine is specified in `$^H{regcomp}`, Perl's own set of callbacks can be accessed in the struct pointed to by `RE_ENGINE_PTR`.
### `mother_re`
TODO, see commit 28d8d7f41a.
### `extflags`
This will be used by Perl to see what flags the regexp was compiled with, this will normally be set to the value of the flags parameter by the [comp](#comp) callback. See the [comp](#comp) documentation for valid flags.
###
`minlen` `minlenret`
The minimum string length (in characters) required for the pattern to match. This is used to prune the search space by not bothering to match any closer to the end of a string than would allow a match. For instance there is no point in even starting the regex engine if the minlen is 10 but the string is only 5 characters long. There is no way that the pattern can match.
`minlenret` is the minimum length (in characters) of the string that would be found in $& after a match.
The difference between `minlen` and `minlenret` can be seen in the following pattern:
```
/ns(?=\d)/
```
where the `minlen` would be 3 but `minlenret` would only be 2 as the \d is required to match but is not actually included in the matched content. This distinction is particularly important as the substitution logic uses the `minlenret` to tell if it can do in-place substitutions (these can result in considerable speed-up).
### `gofs`
Left offset from pos() to start match at.
### `substrs`
Substring data about strings that must appear in the final match. This is currently only used internally by Perl's engine, but might be used in the future for all engines for optimisations.
###
`nparens`, `lastparen`, and `lastcloseparen`
These fields are used to keep track of: how many paren capture groups there are in the pattern; which was the highest paren to be closed (see ["$+" in perlvar](perlvar#%24%2B)); and which was the most recent paren to be closed (see ["$^N" in perlvar](perlvar#%24%5EN)).
### `intflags`
The engine's private copy of the flags the pattern was compiled with. Usually this is the same as `extflags` unless the engine chose to modify one of them.
### `pprivate`
A void\* pointing to an engine-defined data structure. The Perl engine uses the `regexp_internal` structure (see ["Base Structures" in perlreguts](perlreguts#Base-Structures)) but a custom engine should use something else.
### `offs`
A `regexp_paren_pair` structure which defines offsets into the string being matched which correspond to the `$&` and `$1`, `$2` etc. captures, the `regexp_paren_pair` struct is defined as follows:
```
typedef struct regexp_paren_pair {
I32 start;
I32 end;
} regexp_paren_pair;
```
If `->offs[num].start` or `->offs[num].end` is `-1` then that capture group did not match. `->offs[0].start/end` represents `$&` (or `${^MATCH}` under `/p`) and `->offs[paren].end` matches `$$paren` where `$paren` = 1>.
###
`precomp` `prelen`
Used for optimisations. `precomp` holds a copy of the pattern that was compiled and `prelen` its length. When a new pattern is to be compiled (such as inside a loop) the internal `regcomp` operator checks if the last compiled `REGEXP`'s `precomp` and `prelen` are equivalent to the new one, and if so uses the old pattern instead of compiling a new one.
The relevant snippet from `Perl_pp_regcomp`:
```
if (!re || !re->precomp || re->prelen != (I32)len ||
memNE(re->precomp, t, len))
/* Compile a new pattern */
```
### `paren_names`
This is a hash used internally to track named capture groups and their offsets. The keys are the names of the buffers the values are dualvars, with the IV slot holding the number of buffers with the given name and the pv being an embedded array of I32. The values may also be contained independently in the data array in cases where named backreferences are used.
### `substrs`
Holds information on the longest string that must occur at a fixed offset from the start of the pattern, and the longest string that must occur at a floating offset from the start of the pattern. Used to do Fast-Boyer-Moore searches on the string to find out if its worth using the regex engine at all, and if so where in the string to search.
###
`subbeg` `sublen` `saved_copy` `suboffset` `subcoffset`
Used during the execution phase for managing search and replace patterns, and for providing the text for `$&`, `$1` etc. `subbeg` points to a buffer (either the original string, or a copy in the case of `RX_MATCH_COPIED(rx)`), and `sublen` is the length of the buffer. The `RX_OFFS` start and end indices index into this buffer.
In the presence of the `REXEC_COPY_STR` flag, but with the addition of the `REXEC_COPY_SKIP_PRE` or `REXEC_COPY_SKIP_POST` flags, an engine can choose not to copy the full buffer (although it must still do so in the presence of `RXf_PMf_KEEPCOPY` or the relevant bits being set in `PL_sawampersand`). In this case, it may set `suboffset` to indicate the number of bytes from the logical start of the buffer to the physical start (i.e. `subbeg`). It should also set `subcoffset`, the number of characters in the offset. The latter is needed to support `@-` and `@+` which work in characters, not bytes.
###
`wrapped` `wraplen`
Stores the string `qr//` stringifies to. The Perl engine for example stores `(?^:eek)` in the case of `qr/eek/`.
When using a custom engine that doesn't support the `(?:)` construct for inline modifiers, it's probably best to have `qr//` stringify to the supplied pattern, note that this will create undesired patterns in cases such as:
```
my $x = qr/a|b/; # "a|b"
my $y = qr/c/i; # "c"
my $z = qr/$x$y/; # "a|bc"
```
There's no solution for this problem other than making the custom engine understand a construct like `(?:)`.
### `seen_evals`
This stores the number of eval groups in the pattern. This is used for security purposes when embedding compiled regexes into larger patterns with `qr//`.
### `refcnt`
The number of times the structure is referenced. When this falls to 0, the regexp is automatically freed by a call to `pregfree`. This should be set to 1 in each engine's ["comp"](#comp) routine.
HISTORY
-------
Originally part of <perlreguts>.
AUTHORS
-------
Originally written by Yves Orton, expanded by Ævar Arnfjörð Bjarmason.
LICENSE
-------
Copyright 2006 Yves Orton and 2007 Ævar Arnfjörð Bjarmason.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl IO::Uncompress::Base IO::Uncompress::Base
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::Base - Base Class for IO::Uncompress modules
SYNOPSIS
--------
```
use IO::Uncompress::Base ;
```
DESCRIPTION
-----------
This module is not intended for direct use in application code. Its sole purpose is to be sub-classed by IO::Uncompress modules.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlandroid perlandroid
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Cross-compilation](#Cross-compilation)
+ [Get the Android Native Development Kit (NDK)](#Get-the-Android-Native-Development-Kit-(NDK))
+ [Determine the architecture you'll be cross-compiling for](#Determine-the-architecture-you'll-be-cross-compiling-for)
+ [Set up a standalone toolchain](#Set-up-a-standalone-toolchain)
+ [adb or ssh?](#adb-or-ssh?)
- [adb](#adb1)
- [ssh](#ssh)
+ [Configure and beyond](#Configure-and-beyond)
- [Notes](#Notes)
* [Native Builds](#Native-Builds)
+ [CCTools](#CCTools)
+ [Termux](#Termux)
* [AUTHOR](#AUTHOR)
NAME
----
perlandroid - Perl under Android
SYNOPSIS
--------
The first portions of this document contains instructions to cross-compile Perl for Android 2.0 and later, using the binaries provided by Google. The latter portions describe how to build perl native using one of the toolchains available on the Play Store.
DESCRIPTION
-----------
This document describes how to set up your host environment when attempting to build Perl for Android.
Cross-compilation
------------------
These instructions assume an Unixish build environment on your host system; they've been tested on Linux and OS X, and may work on Cygwin and MSYS. While Google also provides an NDK for Windows, these steps won't work native there, although it may be possible to cross-compile through different means.
If your host system's architecture is 32 bits, remember to change the `x86_64`'s below to `x86`'s. On a similar vein, the examples below use the 4.8 toolchain; if you want to use something older or newer (for example, the 4.4.3 toolchain included in the 8th revision of the NDK), just change those to the relevant version.
###
Get the Android Native Development Kit (NDK)
You can download the NDK from <https://developer.android.com/tools/sdk/ndk/index.html>. You'll want the normal, non-legacy version.
###
Determine the architecture you'll be cross-compiling for
There's three possible options: arm-linux-androideabi for ARM, mipsel-linux-android for MIPS, and simply x86 for x86. As of 2014, most Android devices run on ARM, so that is generally a safe bet.
With those two in hand, you should add
```
$ANDROID_NDK/toolchains/$TARGETARCH-4.8/prebuilt/`uname | tr '[A-Z]' '[a-z]'`-x86_64/bin
```
to your `PATH`, where `$ANDROID_NDK` is the location where you unpacked the NDK, and `$TARGETARCH` is your target's architecture.
###
Set up a standalone toolchain
This creates a working sysroot that we can feed to Configure later.
```
$ export ANDROID_TOOLCHAIN=/tmp/my-toolchain-$TARGETARCH
$ export SYSROOT=$ANDROID_TOOLCHAIN/sysroot
$ $ANDROID_NDK/build/tools/make-standalone-toolchain.sh \
--platform=android-9 \
--install-dir=$ANDROID_TOOLCHAIN \
--system=`uname | tr '[A-Z]' '[a-z]'`-x86_64 \
--toolchain=$TARGETARCH-4.8
```
###
adb or ssh?
adb is the Android Debug Bridge. For our purposes, it's basically a way of establishing an ssh connection to an Android device without having to install anything on the device itself, as long as the device is either on the same local network as the host, or it is connected to the host through USB.
Perl can be cross-compiled using either adb or a normal ssh connection; in general, if you can connect your device to the host using a USB port, or if you don't feel like installing an sshd app on your device, you may want to use adb, although you may be forced to switch to ssh if your device is not rooted and you're unlucky -- more on that later. Alternatively, if you're cross-compiling to an emulator, you'll have to use adb.
#### adb
To use adb, download the Android SDK from <https://developer.android.com/sdk/index.html>. The "SDK Tools Only" version should suffice -- if you downloaded the ADT Bundle, you can find the sdk under *$ADT\_BUNDLE/sdk/*.
Add *$ANDROID\_SDK/platform-tools* to your `PATH`, which should give you access to adb. You'll now have to find your device's name using `adb devices`, and later pass that to Configure through `-Dtargethost=$DEVICE`.
However, before calling Configure, you need to check if using adb is a viable choice in the first place. Because Android doesn't have a */tmp*, nor does it allow executables in the sdcard, we need to find somewhere in the device for Configure to put some files in, as well as for the tests to run in. If your device is rooted, then you're good. Try running these:
```
$ export TARGETDIR=/mnt/asec/perl
$ adb -s $DEVICE shell "echo sh -c '\"mkdir $TARGETDIR\"' | su --"
```
Which will create the directory we need, and you can move on to the next step. */mnt/asec* is mounted as a tmpfs in Android, but it's only accessible to root.
If your device is not rooted, you may still be in luck. Try running this:
```
$ export TARGETDIR=/data/local/tmp/perl
$ adb -s $DEVICE shell "mkdir $TARGETDIR"
```
If the command works, you can move to the next step, but beware: **You'll have to remove the directory from the device once you are done! Unlike */mnt/asec*, */data/local/tmp* may not get automatically garbage collected once you shut off the phone**.
If neither of those work, then you can't use adb to cross-compile to your device. Either try rooting it, or go for the ssh route.
#### ssh
To use ssh, you'll need to install and run a sshd app and set it up properly. There are several paid and free apps that do this rather easily, so you should be able to spot one on the store. Remember that Perl requires a passwordless connection, so set up a public key.
Note that several apps spew crap to stderr every time you connect, which can throw off Configure. You may need to monkeypatch the part of Configure that creates `run-ssh` to have it discard stderr.
Since you're using ssh, you'll have to pass some extra arguments to Configure:
```
-Dtargetrun=ssh -Dtargethost=$TARGETHOST -Dtargetuser=$TARGETUSER -Dtargetport=$TARGETPORT
```
###
Configure and beyond
With all of the previous done, you're now ready to call Configure.
If using adb, a "basic" Configure line will look like this:
```
$ ./Configure -des -Dusedevel -Dusecrosscompile -Dtargetrun=adb \
-Dcc=$TARGETARCH-gcc \
-Dsysroot=$SYSROOT \
-Dtargetdir=$TARGETDIR \
-Dtargethost=$DEVICE
```
If using ssh, it's not too different -- we just change targetrun to ssh, and pass in targetuser and targetport. It ends up looking like this:
```
$ ./Configure -des -Dusedevel -Dusecrosscompile -Dtargetrun=ssh \
-Dcc=$TARGETARCH-gcc \
-Dsysroot=$SYSROOT \
-Dtargetdir=$TARGETDIR \
-Dtargethost="$TARGETHOST" \
-Dtargetuser=$TARGETUSER \
-Dtargetport=$TARGETPORT
```
Now you're ready to run `make` and `make test`!
As a final word of warning, if you're using adb, `make test` may appear to hang; this is because it doesn't output anything until it finishes running all tests. You can check its progress by logging into the device, moving to *$TARGETDIR*, and looking at the file *output.stdout*.
#### Notes
* If you are targetting x86 Android, you will have to change `$TARGETARCH-gcc` to `i686-linux-android-gcc`.
* On some older low-end devices -- think early 2.2 era -- some tests, particularly *t/re/uniprops.t*, may crash the phone, causing it to turn itself off once, and then back on again.
Native Builds
--------------
While Google doesn't provide a native toolchain for Android, you can still get one from the Play Store.
### CCTools
You may be able to get the CCTools app, which is free. Keep in mind that you want a full toolchain; some apps tend to default to installing only a barebones version without some important utilities, like ar or nm.
Once you have the toolchain set up properly, the only remaining hurdle is actually locating where in the device it was installed in. For example, CCTools installs its toolchain in */data/data/com.pdaxrom.cctools/root/cctools*. With the path in hand, compiling perl is little more than:
```
export SYSROOT=<location of the native toolchain>
export LD_LIBRARY_PATH="$SYSROOT/lib:`pwd`:`pwd`/lib:`pwd`/lib/auto:$LD_LIBRARY_PATH"
sh Configure -des -Dsysroot=$SYSROOT -Alibpth="/system/lib /vendor/lib"
```
### Termux
[Termux](https://termux.com/) provides an Android terminal emulator and Linux environment. It comes with a cross-compiled perl already installed.
Natively compiling perl 5.30 or later should be as straightforward as:
```
sh Configure -des -Alibpth="/system/lib /vendor/lib"
```
This certainly works on Android 8.1 (Oreo) at least...
AUTHOR
------
Brian Fraser <[email protected]>
perl Test2::Event::V2 Test2::Event::V2
================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
+ [USING A CONTEXT](#USING-A-CONTEXT)
+ [USING THE CONSTRUCTOR](#USING-THE-CONSTRUCTOR)
* [METHODS](#METHODS)
+ [MUTATION](#MUTATION)
+ [LEGACY SUPPORT METHODS](#LEGACY-SUPPORT-METHODS)
* [THIRD PARTY META-DATA](#THIRD-PARTY-META-DATA)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::V2 - Second generation event.
DESCRIPTION
-----------
This is the event type that should be used instead of <Test2::Event> or its legacy subclasses.
SYNOPSIS
--------
###
USING A CONTEXT
```
use Test2::API qw/context/;
sub my_tool {
my $ctx = context();
my $event = $ctx->send_ev2(info => [{tag => 'NOTE', details => "This is a note"}]);
$ctx->release;
return $event;
}
```
###
USING THE CONSTRUCTOR
```
use Test2::Event::V2;
my $e = Test2::Event::V2->new(
trace => {frame => [$PKG, $FILE, $LINE, $SUBNAME]},
info => [{tag => 'NOTE', details => "This is a note"}],
);
```
METHODS
-------
This class inherits from <Test2::Event>.
$fd = $e->facet\_data() This will return a hashref of facet data. Each facet hash will be a shallow copy of the original.
$about = $e->about() This will return the 'about' facet hashref.
**NOTE:** This will return the internal hashref, not a copy.
$trace = $e->trace() This will return the 'trace' facet, normally blessed (but this is not enforced when the trace is set using `set_trace()`.
**NOTE:** This will return the internal trace, not a copy.
### MUTATION
$e->add\_amnesty({...}) Inherited from <Test2::Event>. This can be used to add 'amnesty' facets to an existing event. Each new item is added to the **END** of the list.
**NOTE:** Items **ARE** blessed when added.
$e->add\_hub({...}) Inherited from <Test2::Event>. This is used by hubs to stamp events as they pass through. New items are added to the **START** of the list.
**NOTE:** Items **ARE NOT** blessed when added.
$e->set\_uuid($UUID) Inherited from <Test2::Event>, overridden to also vivify/mutate the 'about' facet.
$e->set\_trace($trace) Inherited from <Test2::Event> which allows you to change the trace.
**Note:** This method does not bless/clone the trace for you. Many things will expect the trace to be blessed, so you should probably do that.
###
LEGACY SUPPORT METHODS
These are all imported from <Test2::Util::Facets2Legacy>, see that module or <Test2::Event> for documentation on what they do.
causes\_fail diagnostics global increments\_count no\_display sets\_plan subtest\_id summary terminate
THIRD PARTY META-DATA
----------------------
This object consumes <Test2::Util::ExternalMeta> which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Tie::Scalar Tie::Scalar
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tie::Scalar vs Tie::StdScalar](#Tie::Scalar-vs-Tie::StdScalar)
* [MORE INFORMATION](#MORE-INFORMATION)
NAME
----
Tie::Scalar, Tie::StdScalar - base class definitions for tied scalars
SYNOPSIS
--------
```
package NewScalar;
require Tie::Scalar;
@ISA = qw(Tie::Scalar);
sub FETCH { ... } # Provide a needed method
sub TIESCALAR { ... } # Overrides inherited method
package NewStdScalar;
require Tie::Scalar;
@ISA = qw(Tie::StdScalar);
# All methods provided by default, so define
# only what needs be overridden
sub FETCH { ... }
package main;
tie $new_scalar, 'NewScalar';
tie $new_std_scalar, 'NewStdScalar';
```
DESCRIPTION
-----------
This module provides some skeletal methods for scalar-tying classes. See <perltie> for a list of the functions required in tying a scalar to a package. The basic **Tie::Scalar** package provides a `new` method, as well as methods `TIESCALAR`, `FETCH` and `STORE`. The **Tie::StdScalar** package provides all the methods specified in <perltie>. It inherits from **Tie::Scalar** and causes scalars tied to it to behave exactly like the built-in scalars, allowing for selective overloading of methods. The `new` method is provided as a means of legacy support for classes that forget to provide their own `TIESCALAR` method.
For developers wishing to write their own tied-scalar classes, the methods are summarized below. The <perltie> section not only documents these, but has sample code as well:
TIESCALAR classname, LIST The method invoked by the command `tie $scalar, classname`. Associates a new scalar instance with the specified class. `LIST` would represent additional arguments (along the lines of [AnyDBM\_File](anydbm_file) and compatriots) needed to complete the association.
FETCH this Retrieve the value of the tied scalar referenced by *this*.
STORE this, value Store data *value* in the tied scalar referenced by *this*.
DESTROY this Free the storage associated with the tied scalar referenced by *this*. This is rarely needed, as Perl manages its memory quite well. But the option exists, should a class wish to perform specific actions upon the destruction of an instance.
###
Tie::Scalar vs Tie::StdScalar
`Tie::Scalar` provides all the necessary methods, but one should realize they do not do anything useful. Calling `Tie::Scalar::FETCH` or `Tie::Scalar::STORE` results in a (trappable) croak. And if you inherit from `Tie::Scalar`, you *must* provide either a `new` or a `TIESCALAR` method.
If you are looking for a class that does everything for you that you don't define yourself, use the `Tie::StdScalar` class, not the `Tie::Scalar` one.
MORE INFORMATION
-----------------
The <perltie> section uses a good example of tying scalars by associating process IDs with priority.
perl Test::Harness::Beyond Test::Harness::Beyond
=====================
CONTENTS
--------
* [NAME](#NAME)
* [Beyond make test](#Beyond-make-test)
+ [Saved State](#Saved-State)
+ [Parallel Testing](#Parallel-Testing)
+ [Non-Perl Tests](#Non-Perl-Tests)
+ [Mixing it up](#Mixing-it-up)
+ [Rolling My Own](#Rolling-My-Own)
+ [Deeper Customisation](#Deeper-Customisation)
+ [Callbacks](#Callbacks)
+ [Parsing TAP](#Parsing-TAP)
+ [Getting Support](#Getting-Support)
NAME
----
Test::Harness::Beyond - Beyond make test
Beyond make test
-----------------
Test::Harness is responsible for running test scripts, analysing their output and reporting success or failure. When I type *make test* (or *./Build test*) for a module, Test::Harness is usually used to run the tests (not all modules use Test::Harness but the majority do).
To start exploring some of the features of Test::Harness I need to switch from *make test* to the *prove* command (which ships with Test::Harness). For the following examples I'll also need a recent version of Test::Harness installed; 3.14 is current as I write.
For the examples I'm going to assume that we're working with a 'normal' Perl module distribution. Specifically I'll assume that typing *make* or *./Build* causes the built, ready-to-install module code to be available below ./blib/lib and ./blib/arch and that there's a directory called 't' that contains our tests. Test::Harness isn't hardwired to that configuration but it saves me from explaining which files live where for each example.
Back to *prove*; like *make test* it runs a test suite - but it provides far more control over which tests are executed, in what order and how their results are reported. Typically *make test* runs all the test scripts below the 't' directory. To do the same thing with prove I type:
```
prove -rb t
```
The switches here are -r to recurse into any directories below 't' and -b which adds ./blib/lib and ./blib/arch to Perl's include path so that the tests can find the code they will be testing. If I'm testing a module of which an earlier version is already installed I need to be careful about the include path to make sure I'm not running my tests against the installed version rather than the new one that I'm working on.
Unlike *make test*, typing *prove* doesn't automatically rebuild my module. If I forget to make before prove I will be testing against older versions of those files - which inevitably leads to confusion. I either get into the habit of typing
```
make && prove -rb t
```
or - if I have no XS code that needs to be built I use the modules below *lib* instead
```
prove -Ilib -r t
```
So far I've shown you nothing that *make test* doesn't do. Let's fix that.
###
Saved State
If I have failing tests in a test suite that consists of more than a handful of scripts and takes more than a few seconds to run it rapidly becomes tedious to run the whole test suite repeatedly as I track down the problems.
I can tell prove just to run the tests that are failing like this:
```
prove -b t/this_fails.t t/so_does_this.t
```
That speeds things up but I have to make a note of which tests are failing and make sure that I run those tests. Instead I can use prove's --state switch and have it keep track of failing tests for me. First I do a complete run of the test suite and tell prove to save the results:
```
prove -rb --state=save t
```
That stores a machine readable summary of the test run in a file called '.prove' in the current directory. If I have failures I can then run just the failing scripts like this:
```
prove -b --state=failed
```
I can also tell prove to save the results again so that it updates its idea of which tests failed:
```
prove -b --state=failed,save
```
As soon as one of my failing tests passes it will be removed from the list of failed tests. Eventually I fix them all and prove can find no failing tests to run:
```
Files=0, Tests=0, 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU)
Result: NOTESTS
```
As I work on a particular part of my module it's most likely that the tests that cover that code will fail. I'd like to run the whole test suite but have it prioritize these 'hot' tests. I can tell prove to do this:
```
prove -rb --state=hot,save t
```
All the tests will run but those that failed most recently will be run first. If no tests have failed since I started saving state all tests will run in their normal order. This combines full test coverage with early notification of failures.
The --state switch supports a number of options; for example to run failed tests first followed by all remaining tests ordered by the timestamps of the test scripts - and save the results - I can use
```
prove -rb --state=failed,new,save t
```
See the prove documentation (type prove --man) for the full list of state options.
When I tell prove to save state it writes a file called '.prove' ('\_prove' on Windows) in the current directory. It's a YAML document so it's quite easy to write tools of your own that work on the saved test state - but the format isn't officially documented so it might change without (much) warning in the future.
###
Parallel Testing
If my tests take too long to run I may be able to speed them up by running multiple test scripts in parallel. This is particularly effective if the tests are I/O bound or if I have multiple CPU cores. I tell prove to run my tests in parallel like this:
```
prove -rb -j 9 t
```
The -j switch enables parallel testing; the number that follows it is the maximum number of tests to run in parallel. Sometimes tests that pass when run sequentially will fail when run in parallel. For example if two different test scripts use the same temporary file or attempt to listen on the same socket I'll have problems running them in parallel. If I see unexpected failures I need to check my tests to work out which of them are trampling on the same resource and rename temporary files or add locks as appropriate.
To get the most performance benefit I want to have the test scripts that take the longest to run start first - otherwise I'll be waiting for the one test that takes nearly a minute to complete after all the others are done. I can use the --state switch to run the tests in slowest to fastest order:
```
prove -rb -j 9 --state=slow,save t
```
###
Non-Perl Tests
The Test Anything Protocol (http://testanything.org/) isn't just for Perl. Just about any language can be used to write tests that output TAP. There are TAP based testing libraries for C, C++, PHP, Python and many others. If I can't find a TAP library for my language of choice it's easy to generate valid TAP. It looks like this:
```
1..3
ok 1 - init OK
ok 2 - opened file
not ok 3 - appended to file
```
The first line is the plan - it specifies the number of tests I'm going to run so that it's easy to check that the test script didn't exit before running all the expected tests. The following lines are the test results - 'ok' for pass, 'not ok' for fail. Each test has a number and, optionally, a description. And that's it. Any language that can produce output like that on STDOUT can be used to write tests.
Recently I've been rekindling a two-decades-old interest in Forth. Evidently I have a masochistic streak that even Perl can't satisfy. I want to write tests in Forth and run them using prove (you can find my gforth TAP experiments at https://svn.hexten.net/andy/Forth/Testing/). I can use the --exec switch to tell prove to run the tests using gforth like this:
```
prove -r --exec gforth t
```
Alternately, if the language used to write my tests allows a shebang line I can use that to specify the interpreter. Here's a test written in PHP:
```
#!/usr/bin/php
<?php
print "1..2\n";
print "ok 1\n";
print "not ok 2\n";
?>
```
If I save that as t/phptest.t the shebang line will ensure that it runs correctly along with all my other tests.
###
Mixing it up
Subtle interdependencies between test programs can mask problems - for example an earlier test may neglect to remove a temporary file that affects the behaviour of a later test. To find this kind of problem I use the --shuffle and --reverse options to run my tests in random or reversed order.
###
Rolling My Own
If I need a feature that prove doesn't provide I can easily write my own.
Typically you'll want to change how TAP gets *input* into and *output* from the parser. <App::Prove> supports arbitrary plugins, and <TAP::Harness> supports custom *formatters* and *source handlers* that you can load using either <prove> or <Module::Build>; there are many examples to base mine on. For more details see <App::Prove>, <TAP::Parser::SourceHandler>, and <TAP::Formatter::Base>.
If writing a plugin is not enough, you can write your own test harness; one of the motives for the 3.00 rewrite of Test::Harness was to make it easier to subclass and extend.
The Test::Harness module is a compatibility wrapper around TAP::Harness. For new applications I should use TAP::Harness directly. As we'll see, prove uses TAP::Harness.
When I run prove it processes its arguments, figures out which test scripts to run and then passes control to TAP::Harness to run the tests, parse, analyse and present the results. By subclassing TAP::Harness I can customise many aspects of the test run.
I want to log my test results in a database so I can track them over time. To do this I override the summary method in TAP::Harness. I start with a simple prototype that dumps the results as a YAML document:
```
package My::TAP::Harness;
use base 'TAP::Harness';
use YAML;
sub summary {
my ( $self, $aggregate ) = @_;
print Dump( $aggregate );
$self->SUPER::summary( $aggregate );
}
1;
```
I need to tell prove to use my My::TAP::Harness. If My::TAP::Harness is on Perl's @INC include path I can
```
prove --harness=My::TAP::Harness -rb t
```
If I don't have My::TAP::Harness installed on @INC I need to provide the correct path to perl when I run prove:
```
perl -Ilib `which prove` --harness=My::TAP::Harness -rb t
```
I can incorporate these options into my own version of prove. It's pretty simple. Most of the work of prove is handled by App::Prove. The important code in prove is just:
```
use App::Prove;
my $app = App::Prove->new;
$app->process_args(@ARGV);
exit( $app->run ? 0 : 1 );
```
If I write a subclass of App::Prove I can customise any aspect of the test runner while inheriting all of prove's behaviour. Here's myprove:
```
#!/usr/bin/env perl use lib qw( lib ); # Add ./lib to @INC
use App::Prove;
my $app = App::Prove->new;
# Use custom TAP::Harness subclass
$app->harness( 'My::TAP::Harness' );
$app->process_args( @ARGV ); exit( $app->run ? 0 : 1 );
```
Now I can run my tests like this
```
./myprove -rb t
```
###
Deeper Customisation
Now that I know how to subclass and replace TAP::Harness I can replace any other part of the harness. To do that I need to know which classes are responsible for which functionality. Here's a brief guided tour; the default class for each component is shown in parentheses. Normally any replacements I write will be subclasses of these default classes.
When I run my tests TAP::Harness creates a scheduler (TAP::Parser::Scheduler) to work out the running order for the tests, an aggregator (TAP::Parser::Aggregator) to collect and analyse the test results and a formatter (TAP::Formatter::Console) to display those results.
If I'm running my tests in parallel there may also be a multiplexer (TAP::Parser::Multiplexer) - the component that allows multiple tests to run simultaneously.
Once it has created those helpers TAP::Harness starts running the tests. For each test it creates a new parser (TAP::Parser) which is responsible for running the test script and parsing its output.
To replace any of these components I call one of these harness methods with the name of the replacement class:
```
aggregator_class
formatter_class
multiplexer_class
parser_class
scheduler_class
```
For example, to replace the aggregator I would
```
$harness->aggregator_class( 'My::Aggregator' );
```
Alternately I can supply the names of my substitute classes to the TAP::Harness constructor:
```
my $harness = TAP::Harness->new(
{ aggregator_class => 'My::Aggregator' }
);
```
If I need to reach even deeper into the internals of the harness I can replace the classes that TAP::Parser uses to execute test scripts and tokenise their output. Before running a test script TAP::Parser creates a grammar (TAP::Parser::Grammar) to decode the raw TAP into tokens, a result factory (TAP::Parser::ResultFactory) to turn the decoded TAP results into objects and, depending on whether it's running a test script or reading TAP from a file, scalar or array a source or an iterator (TAP::Parser::IteratorFactory).
Each of these objects may be replaced by calling one of these parser methods:
```
source_class
perl_source_class
grammar_class
iterator_factory_class
result_factory_class
```
### Callbacks
As an alternative to subclassing the components I need to change I can attach callbacks to the default classes. TAP::Harness exposes these callbacks:
```
parser_args Tweak the parameters used to create the parser
made_parser Just made a new parser
before_runtests About to run tests
after_runtests Have run all tests
after_test Have run an individual test script
```
TAP::Parser also supports callbacks; bailout, comment, plan, test, unknown, version and yaml are called for the corresponding TAP result types, ALL is called for all results, ELSE is called for all results for which a named callback is not installed and EOF is called once at the end of each TAP stream.
To install a callback I pass the name of the callback and a subroutine reference to TAP::Harness or TAP::Parser's callback method:
```
$harness->callback( after_test => sub {
my ( $script, $desc, $parser ) = @_;
} );
```
I can also pass callbacks to the constructor:
```
my $harness = TAP::Harness->new({
callbacks => {
after_test => sub {
my ( $script, $desc, $parser ) = @_;
# Do something interesting here
}
}
});
```
When it comes to altering the behaviour of the test harness there's more than one way to do it. Which way is best depends on my requirements. In general if I only want to observe test execution without changing the harness' behaviour (for example to log test results to a database) I choose callbacks. If I want to make the harness behave differently subclassing gives me more control.
###
Parsing TAP
Perhaps I don't need a complete test harness. If I already have a TAP test log that I need to parse all I need is TAP::Parser and the various classes it depends upon. Here's the code I need to run a test and parse its TAP output
```
use TAP::Parser;
my $parser = TAP::Parser->new( { source => 't/simple.t' } );
while ( my $result = $parser->next ) {
print $result->as_string, "\n";
}
```
Alternately I can pass an open filehandle as source and have the parser read from that rather than attempting to run a test script:
```
open my $tap, '<', 'tests.tap'
or die "Can't read TAP transcript ($!)\n";
my $parser = TAP::Parser->new( { source => $tap } );
while ( my $result = $parser->next ) {
print $result->as_string, "\n";
}
```
This approach is useful if I need to convert my TAP based test results into some other representation. See TAP::Convert::TET (http://search.cpan.org/dist/TAP-Convert-TET/) for an example of this approach.
###
Getting Support
The Test::Harness developers hang out on the tapx-dev mailing list[1]. For discussion of general, language independent TAP issues there's the tap-l[2] list. Finally there's a wiki dedicated to the Test Anything Protocol[3]. Contributions to the wiki, patches and suggestions are all welcome.
[1] <http://www.hexten.net/mailman/listinfo/tapx-dev> [2] <http://testanything.org/mailman/listinfo/tap-l> [3] <http://testanything.org/>
| programming_docs |
perl DB_File DB\_File
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Using DB\_File with Berkeley DB version 2 or greater](#Using-DB_File-with-Berkeley-DB-version-2-or-greater)
+ [Interface to Berkeley DB](#Interface-to-Berkeley-DB)
+ [Opening a Berkeley DB Database File](#Opening-a-Berkeley-DB-Database-File)
+ [Default Parameters](#Default-Parameters)
+ [In Memory Databases](#In-Memory-Databases)
* [DB\_HASH](#DB_HASH1)
+ [A Simple Example](#A-Simple-Example)
* [DB\_BTREE](#DB_BTREE1)
+ [Changing the BTREE sort order](#Changing-the-BTREE-sort-order)
+ [Handling Duplicate Keys](#Handling-Duplicate-Keys)
+ [The get\_dup() Method](#The-get_dup()-Method)
+ [The find\_dup() Method](#The-find_dup()-Method)
+ [The del\_dup() Method](#The-del_dup()-Method)
+ [Matching Partial Keys](#Matching-Partial-Keys)
* [DB\_RECNO](#DB_RECNO1)
+ [The 'bval' Option](#The-'bval'-Option)
+ [A Simple Example](#A-Simple-Example1)
+ [Extra RECNO Methods](#Extra-RECNO-Methods)
+ [Another Example](#Another-Example)
* [THE API INTERFACE](#THE-API-INTERFACE)
* [DBM FILTERS](#DBM-FILTERS)
+ [DBM Filter Low-level API](#DBM-Filter-Low-level-API)
+ [The Filter](#The-Filter)
+ [An Example -- the NULL termination problem.](#An-Example-the-NULL-termination-problem.)
+ [Another Example -- Key is a C int.](#Another-Example-Key-is-a-C-int.)
* [HINTS AND TIPS](#HINTS-AND-TIPS)
+ [Locking: The Trouble with fd](#Locking:-The-Trouble-with-fd)
+ [Safe ways to lock a database](#Safe-ways-to-lock-a-database)
+ [Sharing Databases With C Applications](#Sharing-Databases-With-C-Applications)
+ [The untie() Gotcha](#The-untie()-Gotcha)
* [COMMON QUESTIONS](#COMMON-QUESTIONS)
+ [Why is there Perl source in my database?](#Why-is-there-Perl-source-in-my-database?)
+ [How do I store complex data structures with DB\_File?](#How-do-I-store-complex-data-structures-with-DB_File?)
+ [What does "wide character in subroutine entry" mean?](#What-does-%22wide-character-in-subroutine-entry%22-mean?)
+ [What does "Invalid Argument" mean?](#What-does-%22Invalid-Argument%22-mean?)
+ [What does "Bareword 'DB\_File' not allowed" mean?](#What-does-%22Bareword-'DB_File'-not-allowed%22-mean?)
* [REFERENCES](#REFERENCES)
* [HISTORY](#HISTORY)
* [BUGS](#BUGS)
* [SUPPORT](#SUPPORT)
* [AVAILABILITY](#AVAILABILITY)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DB\_File - Perl5 access to Berkeley DB version 1.x
SYNOPSIS
--------
```
use DB_File;
[$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
[$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
[$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
$status = $X->del($key [, $flags]) ;
$status = $X->put($key, $value [, $flags]) ;
$status = $X->get($key, $value [, $flags]) ;
$status = $X->seq($key, $value, $flags) ;
$status = $X->sync([$flags]) ;
$status = $X->fd ;
# BTREE only
$count = $X->get_dup($key) ;
@list = $X->get_dup($key) ;
%list = $X->get_dup($key, 1) ;
$status = $X->find_dup($key, $value) ;
$status = $X->del_dup($key, $value) ;
# RECNO only
$a = $X->length;
$a = $X->pop ;
$X->push(list);
$a = $X->shift;
$X->unshift(list);
@r = $X->splice(offset, length, elements);
# DBM Filters
$old_filter = $db->filter_store_key ( sub { ... } ) ;
$old_filter = $db->filter_store_value( sub { ... } ) ;
$old_filter = $db->filter_fetch_key ( sub { ... } ) ;
$old_filter = $db->filter_fetch_value( sub { ... } ) ;
untie %hash ;
untie @array ;
```
DESCRIPTION
-----------
**DB\_File** is a module which allows Perl programs to make use of the facilities provided by Berkeley DB version 1.x (if you have a newer version of DB, see ["Using DB\_File with Berkeley DB version 2 or greater"](#Using-DB_File-with-Berkeley-DB-version-2-or-greater)). It is assumed that you have a copy of the Berkeley DB manual pages at hand when reading this documentation. The interface defined here mirrors the Berkeley DB interface closely.
Berkeley DB is a C library which provides a consistent interface to a number of database formats. **DB\_File** provides an interface to all three of the database types currently supported by Berkeley DB.
The file types are:
**DB\_HASH** This database type allows arbitrary key/value pairs to be stored in data files. This is equivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though, the files created using DB\_HASH are not compatible with any of the other packages mentioned.
A default hashing algorithm, which will be adequate for most applications, is built into Berkeley DB. If you do need to use your own hashing algorithm it is possible to write your own in Perl and have **DB\_File** use it instead.
**DB\_BTREE** The btree format allows arbitrary key/value pairs to be stored in a sorted, balanced binary tree.
As with the DB\_HASH format, it is possible to provide a user defined Perl routine to perform the comparison of keys. By default, though, the keys are stored in lexical order.
**DB\_RECNO** DB\_RECNO allows both fixed-length and variable-length flat text files to be manipulated using the same key/value pair interface as in DB\_HASH and DB\_BTREE. In this case the key will consist of a record (line) number.
###
Using DB\_File with Berkeley DB version 2 or greater
Although **DB\_File** is intended to be used with Berkeley DB version 1, it can also be used with version 2, 3 or 4. In this case the interface is limited to the functionality provided by Berkeley DB 1.x. Anywhere the version 2 or greater interface differs, **DB\_File** arranges for it to work like version 1. This feature allows **DB\_File** scripts that were built with version 1 to be migrated to version 2 or greater without any changes.
If you want to make use of the new features available in Berkeley DB 2.x or greater, use the Perl module [BerkeleyDB](https://metacpan.org/pod/BerkeleyDB) instead.
**Note:** The database file format has changed multiple times in Berkeley DB version 2, 3 and 4. If you cannot recreate your databases, you must dump any existing databases with either the `db_dump` or the `db_dump185` utility that comes with Berkeley DB. Once you have rebuilt DB\_File to use Berkeley DB version 2 or greater, your databases can be recreated using `db_load`. Refer to the Berkeley DB documentation for further details.
Please read ["COPYRIGHT"](#COPYRIGHT) before using version 2.x or greater of Berkeley DB with DB\_File.
###
Interface to Berkeley DB
**DB\_File** allows access to Berkeley DB files using the tie() mechanism in Perl 5 (for full details, see ["tie()" in perlfunc](perlfunc#tie%28%29)). This facility allows **DB\_File** to access Berkeley DB files using either an associative array (for DB\_HASH & DB\_BTREE file types) or an ordinary array (for the DB\_RECNO file type).
In addition to the tie() interface, it is also possible to access most of the functions provided in the Berkeley DB API directly. See ["THE API INTERFACE"](#THE-API-INTERFACE).
###
Opening a Berkeley DB Database File
Berkeley DB uses the function dbopen() to open or create a database. Here is the C prototype for dbopen():
```
DB*
dbopen (const char * file, int flags, int mode,
DBTYPE type, const void * openinfo)
```
The parameter `type` is an enumeration which specifies which of the 3 interface methods (DB\_HASH, DB\_BTREE or DB\_RECNO) is to be used. Depending on which of these is actually chosen, the final parameter, *openinfo* points to a data structure which allows tailoring of the specific interface method.
This interface is handled slightly differently in **DB\_File**. Here is an equivalent call using **DB\_File**:
```
tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
```
The `filename`, `flags` and `mode` parameters are the direct equivalent of their dbopen() counterparts. The final parameter $DB\_HASH performs the function of both the `type` and `openinfo` parameters in dbopen().
In the example above $DB\_HASH is actually a pre-defined reference to a hash object. **DB\_File** has three of these pre-defined references. Apart from $DB\_HASH, there is also $DB\_BTREE and $DB\_RECNO.
The keys allowed in each of these pre-defined references is limited to the names used in the equivalent C structure. So, for example, the $DB\_HASH reference will only allow keys called `bsize`, `cachesize`, `ffactor`, `hash`, `lorder` and `nelem`.
To change one of these elements, just assign to it like this:
```
$DB_HASH->{'cachesize'} = 10000 ;
```
The three predefined variables $DB\_HASH, $DB\_BTREE and $DB\_RECNO are usually adequate for most applications. If you do need to create extra instances of these objects, constructors are available for each file type.
Here are examples of the constructors and the valid options available for DB\_HASH, DB\_BTREE and DB\_RECNO respectively.
```
$a = DB_File::HASHINFO->new();
$a->{'bsize'} ;
$a->{'cachesize'} ;
$a->{'ffactor'};
$a->{'hash'} ;
$a->{'lorder'} ;
$a->{'nelem'} ;
$b = DB_File::BTREEINFO->new();
$b->{'flags'} ;
$b->{'cachesize'} ;
$b->{'maxkeypage'} ;
$b->{'minkeypage'} ;
$b->{'psize'} ;
$b->{'compare'} ;
$b->{'prefix'} ;
$b->{'lorder'} ;
$c = DB_File::RECNOINFO->new();
$c->{'bval'} ;
$c->{'cachesize'} ;
$c->{'psize'} ;
$c->{'flags'} ;
$c->{'lorder'} ;
$c->{'reclen'} ;
$c->{'bfname'} ;
```
The values stored in the hashes above are mostly the direct equivalent of their C counterpart. Like their C counterparts, all are set to a default values - that means you don't have to set *all* of the values when you only want to change one. Here is an example:
```
$a = DB_File::HASHINFO->new();
$a->{'cachesize'} = 12345 ;
tie %y, 'DB_File', "filename", $flags, 0777, $a ;
```
A few of the options need extra discussion here. When used, the C equivalent of the keys `hash`, `compare` and `prefix` store pointers to C functions. In **DB\_File** these keys are used to store references to Perl subs. Below are templates for each of the subs:
```
sub hash
{
my ($data) = @_ ;
...
# return the hash value for $data
return $hash ;
}
sub compare
{
my ($key, $key2) = @_ ;
...
# return 0 if $key1 eq $key2
# -1 if $key1 lt $key2
# 1 if $key1 gt $key2
return (-1 , 0 or 1) ;
}
sub prefix
{
my ($key, $key2) = @_ ;
...
# return number of bytes of $key2 which are
# necessary to determine that it is greater than $key1
return $bytes ;
}
```
See ["Changing the BTREE sort order"](#Changing-the-BTREE-sort-order) for an example of using the `compare` template.
If you are using the DB\_RECNO interface and you intend making use of `bval`, you should check out ["The 'bval' Option"](#The-%27bval%27-Option).
###
Default Parameters
It is possible to omit some or all of the final 4 parameters in the call to `tie` and let them take default values. As DB\_HASH is the most common file format used, the call:
```
tie %A, "DB_File", "filename" ;
```
is equivalent to:
```
tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
```
It is also possible to omit the filename parameter as well, so the call:
```
tie %A, "DB_File" ;
```
is equivalent to:
```
tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
```
See ["In Memory Databases"](#In-Memory-Databases) for a discussion on the use of `undef` in place of a filename.
###
In Memory Databases
Berkeley DB allows the creation of in-memory databases by using NULL (that is, a `(char *)0` in C) in place of the filename. **DB\_File** uses `undef` instead of NULL to provide this functionality.
DB\_HASH
--------
The DB\_HASH file format is probably the most commonly used of the three file formats that **DB\_File** supports. It is also very straightforward to use.
###
A Simple Example
This example shows how to create a database, add key/value pairs to the database, delete keys/value pairs and finally how to enumerate the contents of the database.
```
use warnings ;
use strict ;
use DB_File ;
our (%h, $k, $v) ;
unlink "fruit" ;
tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0666, $DB_HASH
or die "Cannot open file 'fruit': $!\n";
# Add a few key/value pairs to the file
$h{"apple"} = "red" ;
$h{"orange"} = "orange" ;
$h{"banana"} = "yellow" ;
$h{"tomato"} = "red" ;
# Check for existence of a key
print "Banana Exists\n\n" if $h{"banana"} ;
# Delete a key/value pair.
delete $h{"apple"} ;
# print the contents of the file
while (($k, $v) = each %h)
{ print "$k -> $v\n" }
untie %h ;
```
here is the output:
```
Banana Exists
orange -> orange
tomato -> red
banana -> yellow
```
Note that the like ordinary associative arrays, the order of the keys retrieved is in an apparently random order.
DB\_BTREE
---------
The DB\_BTREE format is useful when you want to store data in a given order. By default the keys will be stored in lexical order, but as you will see from the example shown in the next section, it is very easy to define your own sorting function.
###
Changing the BTREE sort order
This script shows how to override the default sorting algorithm that BTREE uses. Instead of using the normal lexical ordering, a case insensitive compare function will be used.
```
use warnings ;
use strict ;
use DB_File ;
my %h ;
sub Compare
{
my ($key1, $key2) = @_ ;
"\L$key1" cmp "\L$key2" ;
}
# specify the Perl sub that will do the comparison
$DB_BTREE->{'compare'} = \&Compare ;
unlink "tree" ;
tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open file 'tree': $!\n" ;
# Add a key/value pair to the file
$h{'Wall'} = 'Larry' ;
$h{'Smith'} = 'John' ;
$h{'mouse'} = 'mickey' ;
$h{'duck'} = 'donald' ;
# Delete
delete $h{"duck"} ;
# Cycle through the keys printing them in order.
# Note it is not necessary to sort the keys as
# the btree will have kept them in order automatically.
foreach (keys %h)
{ print "$_\n" }
untie %h ;
```
Here is the output from the code above.
```
mouse
Smith
Wall
```
There are a few point to bear in mind if you want to change the ordering in a BTREE database:
1. The new compare function must be specified when you create the database.
2. You cannot change the ordering once the database has been created. Thus you must use the same compare function every time you access the database.
3. Duplicate keys are entirely defined by the comparison function. In the case-insensitive example above, the keys: 'KEY' and 'key' would be considered duplicates, and assigning to the second one would overwrite the first. If duplicates are allowed for (with the R\_DUP flag discussed below), only a single copy of duplicate keys is stored in the database --- so (again with example above) assigning three values to the keys: 'KEY', 'Key', and 'key' would leave just the first key: 'KEY' in the database with three values. For some situations this results in information loss, so care should be taken to provide fully qualified comparison functions when necessary. For example, the above comparison routine could be modified to additionally compare case-sensitively if two keys are equal in the case insensitive comparison:
```
sub compare {
my($key1, $key2) = @_;
lc $key1 cmp lc $key2 ||
$key1 cmp $key2;
}
```
And now you will only have duplicates when the keys themselves are truly the same. (note: in versions of the db library prior to about November 1996, such duplicate keys were retained so it was possible to recover the original keys in sets of keys that compared as equal).
###
Handling Duplicate Keys
The BTREE file type optionally allows a single key to be associated with an arbitrary number of values. This option is enabled by setting the flags element of `$DB_BTREE` to R\_DUP when creating the database.
There are some difficulties in using the tied hash interface if you want to manipulate a BTREE database with duplicate keys. Consider this code:
```
use warnings ;
use strict ;
use DB_File ;
my ($filename, %h) ;
$filename = "tree" ;
unlink $filename ;
# Enable duplicate records
$DB_BTREE->{'flags'} = R_DUP ;
tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
# Add some key/value pairs to the file
$h{'Wall'} = 'Larry' ;
$h{'Wall'} = 'Brick' ; # Note the duplicate key
$h{'Wall'} = 'Brick' ; # Note the duplicate key and value
$h{'Smith'} = 'John' ;
$h{'mouse'} = 'mickey' ;
# iterate through the associative array
# and print each key/value pair.
foreach (sort keys %h)
{ print "$_ -> $h{$_}\n" }
untie %h ;
```
Here is the output:
```
Smith -> John
Wall -> Larry
Wall -> Larry
Wall -> Larry
mouse -> mickey
```
As you can see 3 records have been successfully created with key `Wall` - the only thing is, when they are retrieved from the database they *seem* to have the same value, namely `Larry`. The problem is caused by the way that the associative array interface works. Basically, when the associative array interface is used to fetch the value associated with a given key, it will only ever retrieve the first value.
Although it may not be immediately obvious from the code above, the associative array interface can be used to write values with duplicate keys, but it cannot be used to read them back from the database.
The way to get around this problem is to use the Berkeley DB API method called `seq`. This method allows sequential access to key/value pairs. See ["THE API INTERFACE"](#THE-API-INTERFACE) for details of both the `seq` method and the API in general.
Here is the script above rewritten using the `seq` API method.
```
use warnings ;
use strict ;
use DB_File ;
my ($filename, $x, %h, $status, $key, $value) ;
$filename = "tree" ;
unlink $filename ;
# Enable duplicate records
$DB_BTREE->{'flags'} = R_DUP ;
$x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
# Add some key/value pairs to the file
$h{'Wall'} = 'Larry' ;
$h{'Wall'} = 'Brick' ; # Note the duplicate key
$h{'Wall'} = 'Brick' ; # Note the duplicate key and value
$h{'Smith'} = 'John' ;
$h{'mouse'} = 'mickey' ;
# iterate through the btree using seq
# and print each key/value pair.
$key = $value = 0 ;
for ($status = $x->seq($key, $value, R_FIRST) ;
$status == 0 ;
$status = $x->seq($key, $value, R_NEXT) )
{ print "$key -> $value\n" }
undef $x ;
untie %h ;
```
that prints:
```
Smith -> John
Wall -> Brick
Wall -> Brick
Wall -> Larry
mouse -> mickey
```
This time we have got all the key/value pairs, including the multiple values associated with the key `Wall`.
To make life easier when dealing with duplicate keys, **DB\_File** comes with a few utility methods.
###
The get\_dup() Method
The `get_dup` method assists in reading duplicate values from BTREE databases. The method can take the following forms:
```
$count = $x->get_dup($key) ;
@list = $x->get_dup($key) ;
%list = $x->get_dup($key, 1) ;
```
In a scalar context the method returns the number of values associated with the key, `$key`.
In list context, it returns all the values which match `$key`. Note that the values will be returned in an apparently random order.
In list context, if the second parameter is present and evaluates TRUE, the method returns an associative array. The keys of the associative array correspond to the values that matched in the BTREE and the values of the array are a count of the number of times that particular value occurred in the BTREE.
So assuming the database created above, we can use `get_dup` like this:
```
use warnings ;
use strict ;
use DB_File ;
my ($filename, $x, %h) ;
$filename = "tree" ;
# Enable duplicate records
$DB_BTREE->{'flags'} = R_DUP ;
$x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
my $cnt = $x->get_dup("Wall") ;
print "Wall occurred $cnt times\n" ;
my %hash = $x->get_dup("Wall", 1) ;
print "Larry is there\n" if $hash{'Larry'} ;
print "There are $hash{'Brick'} Brick Walls\n" ;
my @list = sort $x->get_dup("Wall") ;
print "Wall => [@list]\n" ;
@list = $x->get_dup("Smith") ;
print "Smith => [@list]\n" ;
@list = $x->get_dup("Dog") ;
print "Dog => [@list]\n" ;
```
and it will print:
```
Wall occurred 3 times
Larry is there
There are 2 Brick Walls
Wall => [Brick Brick Larry]
Smith => [John]
Dog => []
```
###
The find\_dup() Method
```
$status = $X->find_dup($key, $value) ;
```
This method checks for the existence of a specific key/value pair. If the pair exists, the cursor is left pointing to the pair and the method returns 0. Otherwise the method returns a non-zero value.
Assuming the database from the previous example:
```
use warnings ;
use strict ;
use DB_File ;
my ($filename, $x, %h, $found) ;
$filename = "tree" ;
# Enable duplicate records
$DB_BTREE->{'flags'} = R_DUP ;
$x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
$found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
print "Larry Wall is $found there\n" ;
$found = ( $x->find_dup("Wall", "Harry") == 0 ? "" : "not") ;
print "Harry Wall is $found there\n" ;
undef $x ;
untie %h ;
```
prints this
```
Larry Wall is there
Harry Wall is not there
```
###
The del\_dup() Method
```
$status = $X->del_dup($key, $value) ;
```
This method deletes a specific key/value pair. It returns 0 if they exist and have been deleted successfully. Otherwise the method returns a non-zero value.
Again assuming the existence of the `tree` database
```
use warnings ;
use strict ;
use DB_File ;
my ($filename, $x, %h, $found) ;
$filename = "tree" ;
# Enable duplicate records
$DB_BTREE->{'flags'} = R_DUP ;
$x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
$x->del_dup("Wall", "Larry") ;
$found = ( $x->find_dup("Wall", "Larry") == 0 ? "" : "not") ;
print "Larry Wall is $found there\n" ;
undef $x ;
untie %h ;
```
prints this
```
Larry Wall is not there
```
###
Matching Partial Keys
The BTREE interface has a feature which allows partial keys to be matched. This functionality is *only* available when the `seq` method is used along with the R\_CURSOR flag.
```
$x->seq($key, $value, R_CURSOR) ;
```
Here is the relevant quote from the dbopen man page where it defines the use of the R\_CURSOR flag with seq:
```
Note, for the DB_BTREE access method, the returned key is not
necessarily an exact match for the specified key. The returned key
is the smallest key greater than or equal to the specified key,
permitting partial key matches and range searches.
```
In the example script below, the `match` sub uses this feature to find and print the first matching key/value pair given a partial key.
```
use warnings ;
use strict ;
use DB_File ;
use Fcntl ;
my ($filename, $x, %h, $st, $key, $value) ;
sub match
{
my $key = shift ;
my $value = 0;
my $orig_key = $key ;
$x->seq($key, $value, R_CURSOR) ;
print "$orig_key\t-> $key\t-> $value\n" ;
}
$filename = "tree" ;
unlink $filename ;
$x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_BTREE
or die "Cannot open $filename: $!\n";
# Add some key/value pairs to the file
$h{'mouse'} = 'mickey' ;
$h{'Wall'} = 'Larry' ;
$h{'Walls'} = 'Brick' ;
$h{'Smith'} = 'John' ;
$key = $value = 0 ;
print "IN ORDER\n" ;
for ($st = $x->seq($key, $value, R_FIRST) ;
$st == 0 ;
$st = $x->seq($key, $value, R_NEXT) )
{ print "$key -> $value\n" }
print "\nPARTIAL MATCH\n" ;
match "Wa" ;
match "A" ;
match "a" ;
undef $x ;
untie %h ;
```
Here is the output:
```
IN ORDER
Smith -> John
Wall -> Larry
Walls -> Brick
mouse -> mickey
PARTIAL MATCH
Wa -> Wall -> Larry
A -> Smith -> John
a -> mouse -> mickey
```
DB\_RECNO
---------
DB\_RECNO provides an interface to flat text files. Both variable and fixed length records are supported.
In order to make RECNO more compatible with Perl, the array offset for all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
As with normal Perl arrays, a RECNO array can be accessed using negative indexes. The index -1 refers to the last element of the array, -2 the second last, and so on. Attempting to access an element before the start of the array will raise a fatal run-time error.
###
The 'bval' Option
The operation of the bval option warrants some discussion. Here is the definition of bval from the Berkeley DB 1.85 recno manual page:
```
The delimiting byte to be used to mark the end of a
record for variable-length records, and the pad charac-
ter for fixed-length records. If no value is speci-
fied, newlines (``\n'') are used to mark the end of
variable-length records and fixed-length records are
padded with spaces.
```
The second sentence is wrong. In actual fact bval will only default to `"\n"` when the openinfo parameter in dbopen is NULL. If a non-NULL openinfo parameter is used at all, the value that happens to be in bval will be used. That means you always have to specify bval when making use of any of the options in the openinfo parameter. This documentation error will be fixed in the next release of Berkeley DB.
That clarifies the situation with regards Berkeley DB itself. What about **DB\_File**? Well, the behavior defined in the quote above is quite useful, so **DB\_File** conforms to it.
That means that you can specify other options (e.g. cachesize) and still have bval default to `"\n"` for variable length records, and space for fixed length records.
Also note that the bval option only allows you to specify a single byte as a delimiter.
###
A Simple Example
Here is a simple example that uses RECNO (if you are using a version of Perl earlier than 5.004\_57 this example won't work -- see ["Extra RECNO Methods"](#Extra-RECNO-Methods) for a workaround).
```
use warnings ;
use strict ;
use DB_File ;
my $filename = "text" ;
unlink $filename ;
my @h ;
tie @h, "DB_File", $filename, O_RDWR|O_CREAT, 0666, $DB_RECNO
or die "Cannot open file 'text': $!\n" ;
# Add a few key/value pairs to the file
$h[0] = "orange" ;
$h[1] = "blue" ;
$h[2] = "yellow" ;
push @h, "green", "black" ;
my $elements = scalar @h ;
print "The array contains $elements entries\n" ;
my $last = pop @h ;
print "popped $last\n" ;
unshift @h, "white" ;
my $first = shift @h ;
print "shifted $first\n" ;
# Check for existence of a key
print "Element 1 Exists with value $h[1]\n" if $h[1] ;
# use a negative index
print "The last element is $h[-1]\n" ;
print "The 2nd last element is $h[-2]\n" ;
untie @h ;
```
Here is the output from the script:
```
The array contains 5 entries
popped black
shifted white
Element 1 Exists with value blue
The last element is green
The 2nd last element is yellow
```
###
Extra RECNO Methods
If you are using a version of Perl earlier than 5.004\_57, the tied array interface is quite limited. In the example script above `push`, `pop`, `shift`, `unshift` or determining the array length will not work with a tied array.
To make the interface more useful for older versions of Perl, a number of methods are supplied with **DB\_File** to simulate the missing array operations. All these methods are accessed via the object returned from the tie call.
Here are the methods:
**$X->push(list) ;**
Pushes the elements of `list` to the end of the array.
**$value = $X->pop ;**
Removes and returns the last element of the array.
**$X->shift**
Removes and returns the first element of the array.
**$X->unshift(list) ;**
Pushes the elements of `list` to the start of the array.
**$X->length**
Returns the number of elements in the array.
**$X->splice(offset, length, elements);**
Returns a splice of the array.
###
Another Example
Here is a more complete example that makes use of some of the methods described above. It also makes use of the API interface directly (see ["THE API INTERFACE"](#THE-API-INTERFACE)).
```
use warnings ;
use strict ;
my (@h, $H, $file, $i) ;
use DB_File ;
use Fcntl ;
$file = "text" ;
unlink $file ;
$H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0666, $DB_RECNO
or die "Cannot open file $file: $!\n" ;
# first create a text file to play with
$h[0] = "zero" ;
$h[1] = "one" ;
$h[2] = "two" ;
$h[3] = "three" ;
$h[4] = "four" ;
# Print the records in order.
#
# The length method is needed here because evaluating a tied
# array in a scalar context does not return the number of
# elements in the array.
print "\nORIGINAL\n" ;
foreach $i (0 .. $H->length - 1) {
print "$i: $h[$i]\n" ;
}
# use the push & pop methods
$a = $H->pop ;
$H->push("last") ;
print "\nThe last record was [$a]\n" ;
# and the shift & unshift methods
$a = $H->shift ;
$H->unshift("first") ;
print "The first record was [$a]\n" ;
# Use the API to add a new record after record 2.
$i = 2 ;
$H->put($i, "Newbie", R_IAFTER) ;
# and a new record before record 1.
$i = 1 ;
$H->put($i, "New One", R_IBEFORE) ;
# delete record 3
$H->del(3) ;
# now print the records in reverse order
print "\nREVERSE\n" ;
for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
{ print "$i: $h[$i]\n" }
# same again, but use the API functions instead
print "\nREVERSE again\n" ;
my ($s, $k, $v) = (0, 0, 0) ;
for ($s = $H->seq($k, $v, R_LAST) ;
$s == 0 ;
$s = $H->seq($k, $v, R_PREV))
{ print "$k: $v\n" }
undef $H ;
untie @h ;
```
and this is what it outputs:
```
ORIGINAL
0: zero
1: one
2: two
3: three
4: four
The last record was [four]
The first record was [zero]
REVERSE
5: last
4: three
3: Newbie
2: one
1: New One
0: first
REVERSE again
5: last
4: three
3: Newbie
2: one
1: New One
0: first
```
Notes:
1. Rather than iterating through the array, `@h` like this:
```
foreach $i (@h)
```
it is necessary to use either this:
```
foreach $i (0 .. $H->length - 1)
```
or this:
```
for ($a = $H->get($k, $v, R_FIRST) ;
$a == 0 ;
$a = $H->get($k, $v, R_NEXT) )
```
2. Notice that both times the `put` method was used the record index was specified using a variable, `$i`, rather than the literal value itself. This is because `put` will return the record number of the inserted line via that parameter.
THE API INTERFACE
------------------
As well as accessing Berkeley DB using a tied hash or array, it is also possible to make direct use of most of the API functions defined in the Berkeley DB documentation.
To do this you need to store a copy of the object returned from the tie.
```
$db = tie %hash, "DB_File", "filename" ;
```
Once you have done that, you can access the Berkeley DB API functions as **DB\_File** methods directly like this:
```
$db->put($key, $value, R_NOOVERWRITE) ;
```
**Important:** If you have saved a copy of the object returned from `tie`, the underlying database file will *not* be closed until both the tied variable is untied and all copies of the saved object are destroyed.
```
use DB_File ;
$db = tie %hash, "DB_File", "filename"
or die "Cannot tie filename: $!" ;
...
undef $db ;
untie %hash ;
```
See ["The untie() Gotcha"](#The-untie%28%29-Gotcha) for more details.
All the functions defined in <dbopen> are available except for close() and dbopen() itself. The **DB\_File** method interface to the supported functions have been implemented to mirror the way Berkeley DB works whenever possible. In particular note that:
* The methods return a status value. All return 0 on success. All return -1 to signify an error and set `$!` to the exact error code. The return code 1 generally (but not always) means that the key specified did not exist in the database.
Other return codes are defined. See below and in the Berkeley DB documentation for details. The Berkeley DB documentation should be used as the definitive source.
* Whenever a Berkeley DB function returns data via one of its parameters, the equivalent **DB\_File** method does exactly the same.
* If you are careful, it is possible to mix API calls with the tied hash/array interface in the same piece of code. Although only a few of the methods used to implement the tied interface currently make use of the cursor, you should always assume that the cursor has been changed any time the tied hash/array interface is used. As an example, this code will probably not do what you expect:
```
$X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
or die "Cannot tie $filename: $!" ;
# Get the first key/value pair and set the cursor
$X->seq($key, $value, R_FIRST) ;
# this line will modify the cursor
$count = scalar keys %x ;
# Get the second key/value pair.
# oops, it didn't, it got the last key/value pair!
$X->seq($key, $value, R_NEXT) ;
```
The code above can be rearranged to get around the problem, like this:
```
$X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
or die "Cannot tie $filename: $!" ;
# this line will modify the cursor
$count = scalar keys %x ;
# Get the first key/value pair and set the cursor
$X->seq($key, $value, R_FIRST) ;
# Get the second key/value pair.
# worked this time.
$X->seq($key, $value, R_NEXT) ;
```
All the constants defined in <dbopen> for use in the flags parameters in the methods defined below are also available. Refer to the Berkeley DB documentation for the precise meaning of the flags values.
Below is a list of the methods available.
**$status = $X->get($key, $value [, $flags]) ;**
Given a key (`$key`) this method reads the value associated with it from the database. The value read from the database is returned in the `$value` parameter.
If the key does not exist the method returns 1.
No flags are currently defined for this method.
**$status = $X->put($key, $value [, $flags]) ;**
Stores the key/value pair in the database.
If you use either the R\_IAFTER or R\_IBEFORE flags, the `$key` parameter will have the record number of the inserted key/value pair set.
Valid flags are R\_CURSOR, R\_IAFTER, R\_IBEFORE, R\_NOOVERWRITE and R\_SETCURSOR.
**$status = $X->del($key [, $flags]) ;**
Removes all key/value pairs with key `$key` from the database.
A return code of 1 means that the requested key was not in the database.
R\_CURSOR is the only valid flag at present.
**$status = $X->fd ;**
Returns the file descriptor for the underlying database.
See ["Locking: The Trouble with fd"](#Locking%3A-The-Trouble-with-fd) for an explanation for why you should not use `fd` to lock your database.
**$status = $X->seq($key, $value, $flags) ;**
This interface allows sequential retrieval from the database. See <dbopen> for full details.
Both the `$key` and `$value` parameters will be set to the key/value pair read from the database.
The flags parameter is mandatory. The valid flag values are R\_CURSOR, R\_FIRST, R\_LAST, R\_NEXT and R\_PREV.
**$status = $X->sync([$flags]) ;**
Flushes any cached buffers to disk.
R\_RECNOSYNC is the only valid flag at present.
DBM FILTERS
------------
A DBM Filter is a piece of code that is be used when you *always* want to make the same transformation to all keys and/or values in a DBM database. An example is when you need to encode your data in UTF-8 before writing to the database and then decode the UTF-8 when reading from the database file.
There are two ways to use a DBM Filter.
1. Using the low-level API defined below.
2. Using the [DBM\_Filter](dbm_filter) module. This module hides the complexity of the API defined below and comes with a number of "canned" filters that cover some of the common use-cases.
Use of the [DBM\_Filter](dbm_filter) module is recommended.
###
DBM Filter Low-level API
There are four methods associated with DBM Filters. All work identically, and each is used to install (or uninstall) a single DBM Filter. Each expects a single parameter, namely a reference to a sub. The only difference between them is the place that the filter is installed.
To summarise:
**filter\_store\_key** If a filter has been installed with this method, it will be invoked every time you write a key to a DBM database.
**filter\_store\_value** If a filter has been installed with this method, it will be invoked every time you write a value to a DBM database.
**filter\_fetch\_key** If a filter has been installed with this method, it will be invoked every time you read a key from a DBM database.
**filter\_fetch\_value** If a filter has been installed with this method, it will be invoked every time you read a value from a DBM database.
You can use any combination of the methods, from none, to all four.
All filter methods return the existing filter, if present, or `undef` in not.
To delete a filter pass `undef` to it.
###
The Filter
When each filter is called by Perl, a local copy of `$_` will contain the key or value to be filtered. Filtering is achieved by modifying the contents of `$_`. The return code from the filter is ignored.
###
An Example -- the NULL termination problem.
Consider the following scenario. You have a DBM database that you need to share with a third-party C application. The C application assumes that *all* keys and values are NULL terminated. Unfortunately when Perl writes to DBM databases it doesn't use NULL termination, so your Perl application will have to manage NULL termination itself. When you write to the database you will have to use something like this:
```
$hash{"$key\0"} = "$value\0" ;
```
Similarly the NULL needs to be taken into account when you are considering the length of existing keys/values.
It would be much better if you could ignore the NULL terminations issue in the main application code and have a mechanism that automatically added the terminating NULL to all keys and values whenever you write to the database and have them removed when you read from the database. As I'm sure you have already guessed, this is a problem that DBM Filters can fix very easily.
```
use warnings ;
use strict ;
use DB_File ;
my %hash ;
my $filename = "filt" ;
unlink $filename ;
my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
or die "Cannot open $filename: $!\n" ;
# Install DBM Filters
$db->filter_fetch_key ( sub { s/\0$// } ) ;
$db->filter_store_key ( sub { $_ .= "\0" } ) ;
$db->filter_fetch_value( sub { s/\0$// } ) ;
$db->filter_store_value( sub { $_ .= "\0" } ) ;
$hash{"abc"} = "def" ;
my $a = $hash{"ABC"} ;
# ...
undef $db ;
untie %hash ;
```
Hopefully the contents of each of the filters should be self-explanatory. Both "fetch" filters remove the terminating NULL, and both "store" filters add a terminating NULL.
###
Another Example -- Key is a C int.
Here is another real-life example. By default, whenever Perl writes to a DBM database it always writes the key and value as strings. So when you use this:
```
$hash{12345} = "something" ;
```
the key 12345 will get stored in the DBM database as the 5 byte string "12345". If you actually want the key to be stored in the DBM database as a C int, you will have to use `pack` when writing, and `unpack` when reading.
Here is a DBM Filter that does it:
```
use warnings ;
use strict ;
use DB_File ;
my %hash ;
my $filename = "filt" ;
unlink $filename ;
my $db = tie %hash, 'DB_File', $filename, O_CREAT|O_RDWR, 0666, $DB_HASH
or die "Cannot open $filename: $!\n" ;
$db->filter_fetch_key ( sub { $_ = unpack("i", $_) } ) ;
$db->filter_store_key ( sub { $_ = pack ("i", $_) } ) ;
$hash{123} = "def" ;
# ...
undef $db ;
untie %hash ;
```
This time only two filters have been used -- we only need to manipulate the contents of the key, so it wasn't necessary to install any value filters.
HINTS AND TIPS
---------------
###
Locking: The Trouble with fd
Until version 1.72 of this module, the recommended technique for locking **DB\_File** databases was to flock the filehandle returned from the "fd" function. Unfortunately this technique has been shown to be fundamentally flawed (Kudos to David Harris for tracking this down). Use it at your own peril!
The locking technique went like this.
```
$db = tie(%db, 'DB_File', 'foo.db', O_CREAT|O_RDWR, 0644)
|| die "dbcreat foo.db $!";
$fd = $db->fd;
open(DB_FH, "+<&=$fd") || die "dup $!";
flock (DB_FH, LOCK_EX) || die "flock: $!";
...
$db{"Tom"} = "Jerry" ;
...
flock(DB_FH, LOCK_UN);
undef $db;
untie %db;
close(DB_FH);
```
In simple terms, this is what happens:
1. Use "tie" to open the database.
2. Lock the database with fd & flock.
3. Read & Write to the database.
4. Unlock and close the database.
Here is the crux of the problem. A side-effect of opening the **DB\_File** database in step 2 is that an initial block from the database will get read from disk and cached in memory.
To see why this is a problem, consider what can happen when two processes, say "A" and "B", both want to update the same **DB\_File** database using the locking steps outlined above. Assume process "A" has already opened the database and has a write lock, but it hasn't actually updated the database yet (it has finished step 2, but not started step 3 yet). Now process "B" tries to open the same database - step 1 will succeed, but it will block on step 2 until process "A" releases the lock. The important thing to notice here is that at this point in time both processes will have cached identical initial blocks from the database.
Now process "A" updates the database and happens to change some of the data held in the initial buffer. Process "A" terminates, flushing all cached data to disk and releasing the database lock. At this point the database on disk will correctly reflect the changes made by process "A".
With the lock released, process "B" can now continue. It also updates the database and unfortunately it too modifies the data that was in its initial buffer. Once that data gets flushed to disk it will overwrite some/all of the changes process "A" made to the database.
The result of this scenario is at best a database that doesn't contain what you expect. At worst the database will corrupt.
The above won't happen every time competing process update the same **DB\_File** database, but it does illustrate why the technique should not be used.
###
Safe ways to lock a database
Starting with version 2.x, Berkeley DB has internal support for locking. The companion module to this one, [BerkeleyDB](https://metacpan.org/pod/BerkeleyDB), provides an interface to this locking functionality. If you are serious about locking Berkeley DB databases, I strongly recommend using [BerkeleyDB](https://metacpan.org/pod/BerkeleyDB).
If using [BerkeleyDB](https://metacpan.org/pod/BerkeleyDB) isn't an option, there are a number of modules available on CPAN that can be used to implement locking. Each one implements locking differently and has different goals in mind. It is therefore worth knowing the difference, so that you can pick the right one for your application. Here are the three locking wrappers:
**Tie::DB\_Lock**
A **DB\_File** wrapper which creates copies of the database file for read access, so that you have a kind of a multiversioning concurrent read system. However, updates are still serial. Use for databases where reads may be lengthy and consistency problems may occur.
**Tie::DB\_LockFile**
A **DB\_File** wrapper that has the ability to lock and unlock the database while it is being used. Avoids the tie-before-flock problem by simply re-tie-ing the database when you get or drop a lock. Because of the flexibility in dropping and re-acquiring the lock in the middle of a session, this can be massaged into a system that will work with long updates and/or reads if the application follows the hints in the POD documentation.
**DB\_File::Lock**
An extremely lightweight **DB\_File** wrapper that simply flocks a lockfile before tie-ing the database and drops the lock after the untie. Allows one to use the same lockfile for multiple databases to avoid deadlock problems, if desired. Use for databases where updates are reads are quick and simple flock locking semantics are enough.
###
Sharing Databases With C Applications
There is no technical reason why a Berkeley DB database cannot be shared by both a Perl and a C application.
The vast majority of problems that are reported in this area boil down to the fact that C strings are NULL terminated, whilst Perl strings are not. See ["DBM FILTERS"](#DBM-FILTERS) for a generic way to work around this problem.
Here is a real example. Netscape 2.0 keeps a record of the locations you visit along with the time you last visited them in a DB\_HASH database. This is usually stored in the file *~/.netscape/history.db*. The key field in the database is the location string and the value field is the time the location was last visited stored as a 4 byte binary value.
If you haven't already guessed, the location string is stored with a terminating NULL. This means you need to be careful when accessing the database.
Here is a snippet of code that is loosely based on Tom Christiansen's *ggh* script (available from your nearest CPAN archive in *authors/id/TOMC/scripts/nshist.gz*).
```
use warnings ;
use strict ;
use DB_File ;
use Fcntl ;
my ($dotdir, $HISTORY, %hist_db, $href, $binary_time, $date) ;
$dotdir = $ENV{HOME} || $ENV{LOGNAME};
$HISTORY = "$dotdir/.netscape/history.db";
tie %hist_db, 'DB_File', $HISTORY
or die "Cannot open $HISTORY: $!\n" ;;
# Dump the complete database
while ( ($href, $binary_time) = each %hist_db ) {
# remove the terminating NULL
$href =~ s/\x00$// ;
# convert the binary time into a user friendly string
$date = localtime unpack("V", $binary_time);
print "$date $href\n" ;
}
# check for the existence of a specific key
# remember to add the NULL
if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
$date = localtime unpack("V", $binary_time) ;
print "Last visited mox.perl.com on $date\n" ;
}
else {
print "Never visited mox.perl.com\n"
}
untie %hist_db ;
```
###
The untie() Gotcha
If you make use of the Berkeley DB API, it is *very* strongly recommended that you read ["The untie Gotcha" in perltie](perltie#The-untie-Gotcha).
Even if you don't currently make use of the API interface, it is still worth reading it.
Here is an example which illustrates the problem from a **DB\_File** perspective:
```
use DB_File ;
use Fcntl ;
my %x ;
my $X ;
$X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
or die "Cannot tie first time: $!" ;
$x{123} = 456 ;
untie %x ;
tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
or die "Cannot tie second time: $!" ;
untie %x ;
```
When run, the script will produce this error message:
```
Cannot tie second time: Invalid argument at bad.file line 14.
```
Although the error message above refers to the second tie() statement in the script, the source of the problem is really with the untie() statement that precedes it.
Having read <perltie> you will probably have already guessed that the error is caused by the extra copy of the tied object stored in `$X`. If you haven't, then the problem boils down to the fact that the **DB\_File** destructor, DESTROY, will not be called until *all* references to the tied object are destroyed. Both the tied variable, `%x`, and `$X` above hold a reference to the object. The call to untie() will destroy the first, but `$X` still holds a valid reference, so the destructor will not get called and the database file *tst.fil* will remain open. The fact that Berkeley DB then reports the attempt to open a database that is already open via the catch-all "Invalid argument" doesn't help.
If you run the script with the `-w` flag the error message becomes:
```
untie attempted while 1 inner references still exist at bad.file line 12.
Cannot tie second time: Invalid argument at bad.file line 14.
```
which pinpoints the real problem. Finally the script can now be modified to fix the original problem by destroying the API object before the untie:
```
...
$x{123} = 456 ;
undef $X ;
untie %x ;
$X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
...
```
COMMON QUESTIONS
-----------------
###
Why is there Perl source in my database?
If you look at the contents of a database file created by DB\_File, there can sometimes be part of a Perl script included in it.
This happens because Berkeley DB uses dynamic memory to allocate buffers which will subsequently be written to the database file. Being dynamic, the memory could have been used for anything before DB malloced it. As Berkeley DB doesn't clear the memory once it has been allocated, the unused portions will contain random junk. In the case where a Perl script gets written to the database, the random junk will correspond to an area of dynamic memory that happened to be used during the compilation of the script.
Unless you don't like the possibility of there being part of your Perl scripts embedded in a database file, this is nothing to worry about.
###
How do I store complex data structures with DB\_File?
Although **DB\_File** cannot do this directly, there is a module which can layer transparently over **DB\_File** to accomplish this feat.
Check out the MLDBM module, available on CPAN in the directory *modules/by-module/MLDBM*.
###
What does "wide character in subroutine entry" mean?
You will usually get this message if you are working with UTF-8 data and want to read/write it from/to a Berkeley DB database file.
The easist way to deal with this issue is to use the pre-defined "utf8" **DBM\_Filter** (see [DBM\_Filter](dbm_filter)) that was designed to deal with this situation.
The example below shows what you need if *both* the key and value are expected to be in UTF-8.
```
use DB_File;
use DBM_Filter;
my $db = tie %h, 'DB_File', '/tmp/try.db', O_CREAT|O_RDWR, 0666, $DB_BTREE;
$db->Filter_Key_Push('utf8');
$db->Filter_Value_Push('utf8');
my $key = "\N{LATIN SMALL LETTER A WITH ACUTE}";
my $value = "\N{LATIN SMALL LETTER E WITH ACUTE}";
$h{ $key } = $value;
```
###
What does "Invalid Argument" mean?
You will get this error message when one of the parameters in the `tie` call is wrong. Unfortunately there are quite a few parameters to get wrong, so it can be difficult to figure out which one it is.
Here are a couple of possibilities:
1. Attempting to reopen a database without closing it.
2. Using the O\_WRONLY flag.
###
What does "Bareword 'DB\_File' not allowed" mean?
You will encounter this particular error message when you have the `strict 'subs'` pragma (or the full strict pragma) in your script. Consider this script:
```
use warnings ;
use strict ;
use DB_File ;
my %x ;
tie %x, DB_File, "filename" ;
```
Running it produces the error in question:
```
Bareword "DB_File" not allowed while "strict subs" in use
```
To get around the error, place the word `DB_File` in either single or double quotes, like this:
```
tie %x, "DB_File", "filename" ;
```
Although it might seem like a real pain, it is really worth the effort of having a `use strict` in all your scripts.
REFERENCES
----------
Articles that are either about **DB\_File** or make use of it.
1. *Full-Text Searching in Perl*, Tim Kientzle ([email protected]), Dr. Dobb's Journal, Issue 295, January 1999, pp 34-41
HISTORY
-------
Moved to the Changes file.
BUGS
----
Some older versions of Berkeley DB had problems with fixed length records using the RECNO file format. This problem has been fixed since version 1.85 of Berkeley DB.
I am sure there are bugs in the code. If you do find any, or can suggest any enhancements, I would welcome your comments.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/DB_File/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=DB_File>.
AVAILABILITY
------------
**DB\_File** comes with the standard Perl source distribution. Look in the directory *ext/DB\_File*. Given the amount of time between releases of Perl the version that ships with Perl is quite likely to be out of date, so the most recent version can always be found on CPAN (see ["CPAN" in perlmodlib](perlmodlib#CPAN) for details), in the directory *modules/by-module/DB\_File*.
**DB\_File** is designed to work with any version of Berkeley DB, but is limited to the functionality provided by version 1. If you want to make use of the new features available in Berkeley DB 2.x, or greater, use the Perl module [BerkeleyDB](https://metacpan.org/pod/BerkeleyDB) instead.
The official web site for Berkeley DB is <http://www.oracle.com/technology/products/berkeley-db/db/index.html>. All versions of Berkeley DB are available there.
Alternatively, Berkeley DB version 1 is available at your nearest CPAN archive in *src/misc/db.1.85.tar.gz*.
COPYRIGHT
---------
Copyright (c) 1995-2022 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Although **DB\_File** is covered by the Perl license, the library it makes use of, namely Berkeley DB, is not. Berkeley DB has its own copyright and its own license. Please take the time to read it.
Here are a few words taken from the Berkeley DB FAQ (at <http://www.oracle.com/technology/products/berkeley-db/db/index.html>) regarding the license:
```
Do I have to license DB to use it in Perl scripts?
No. The Berkeley DB license requires that software that uses
Berkeley DB be freely redistributable. In the case of Perl, that
software is Perl, and not your scripts. Any Perl scripts that you
write are your property, including scripts that make use of
Berkeley DB. Neither the Perl license nor the Berkeley DB license
place any restriction on what you may do with them.
```
If you are in any doubt about the license situation, contact either the Berkeley DB authors or the author of DB\_File. See ["AUTHOR"](#AUTHOR) for details.
SEE ALSO
---------
<perl>, [dbopen(3)](http://man.he.net/man3/dbopen), [hash(3)](http://man.he.net/man3/hash), [recno(3)](http://man.he.net/man3/recno), [btree(3)](http://man.he.net/man3/btree), <perldbmfilter>, [DBM\_Filter](dbm_filter)
AUTHOR
------
The DB\_File interface was written by Paul Marquess <[email protected]>.
| programming_docs |
perl CPAN::Version CPAN::Version
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LICENSE](#LICENSE)
NAME
----
CPAN::Version - utility functions to compare CPAN versions
SYNOPSIS
--------
```
use CPAN::Version;
CPAN::Version->vgt("1.1","1.1.1"); # 1 bc. 1.1 > 1.001001
CPAN::Version->vlt("1.1","1.1"); # 0 bc. 1.1 not < 1.1
CPAN::Version->vcmp("1.1","1.1.1"); # 1 bc. first is larger
CPAN::Version->vcmp("1.1.1","1.1"); # -1 bc. first is smaller
CPAN::Version->readable(v1.2.3); # "v1.2.3"
CPAN::Version->vstring("v1.2.3"); # v1.2.3
CPAN::Version->float2vv(1.002003); # "v1.2.3"
```
DESCRIPTION
-----------
This module mediates between some version that perl sees in a package and the version that is published by the CPAN indexer.
It's only written as a helper module for both CPAN.pm and CPANPLUS.pm.
As it stands it predates version.pm but has the same goal: make version strings visible and comparable.
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl base base
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [HISTORY](#HISTORY)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
base - Establish an ISA relationship with base classes at compile time
SYNOPSIS
--------
```
package Baz;
use base qw(Foo Bar);
```
DESCRIPTION
-----------
Unless you are using the `fields` pragma, consider this module discouraged in favor of the lighter-weight `parent`.
Allows you to both load one or more modules, while setting up inheritance from those modules at the same time. Roughly similar in effect to
```
package Baz;
BEGIN {
require Foo;
require Bar;
push @ISA, qw(Foo Bar);
}
```
When `base` tries to `require` a module, it will not die if it cannot find the module's file, but will die on any other error. After all this, should your base class be empty, containing no symbols, `base` will die. This is useful for inheriting from classes in the same file as yourself but where the filename does not match the base module name, like so:
```
# in Bar.pm
package Foo;
sub exclaim { "I can have such a thing?!" }
package Bar;
use base "Foo";
```
There is no *Foo.pm*, but because `Foo` defines a symbol (the `exclaim` subroutine), `base` will not die when the `require` fails to load *Foo.pm*.
`base` will also initialize the fields if one of the base classes has it. Multiple inheritance of fields is **NOT** supported, if two or more base classes each have inheritable fields the 'base' pragma will croak. See <fields> for a description of this feature.
The base class' `import` method is **not** called.
DIAGNOSTICS
-----------
Base class package "%s" is empty. base.pm was unable to require the base package, because it was not found in your path.
Class 'Foo' tried to inherit from itself Attempting to inherit from yourself generates a warning.
```
package Foo;
use base 'Foo';
```
HISTORY
-------
This module was introduced with Perl 5.004\_04.
CAVEATS
-------
Due to the limitations of the implementation, you must use base *before* you declare any of your own fields.
SEE ALSO
---------
<fields>
perl Pod::Simple::Debug Pod::Simple::Debug
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [GUTS](#GUTS)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::Debug -- put Pod::Simple into trace/debug mode
SYNOPSIS
--------
```
use Pod::Simple::Debug (5); # or some integer
```
Or:
```
my $debuglevel;
use Pod::Simple::Debug (\$debuglevel, 0);
...some stuff that uses Pod::Simple to do stuff, but which
you don't want debug output from...
$debug_level = 4;
...some stuff that uses Pod::Simple to do stuff, but which
you DO want debug output from...
$debug_level = 0;
```
DESCRIPTION
-----------
This is an internal module for controlling the debug level (a.k.a. trace level) of Pod::Simple. This is of interest only to Pod::Simple developers.
CAVEATS
-------
Note that you should load this module *before* loading Pod::Simple (or any Pod::Simple-based class). If you try loading Pod::Simple::Debug after &Pod::Simple::DEBUG is already defined, Pod::Simple::Debug will throw a fatal error to the effect that "It's too late to call Pod::Simple::Debug".
Note that the `use Pod::Simple::Debug (\$x, *somenum*)` mode will make Pod::Simple (et al) run rather slower, since &Pod::Simple::DEBUG won't be a constant sub anymore, and so Pod::Simple (et al) won't compile with constant-folding.
GUTS
----
Doing this:
```
use Pod::Simple::Debug (5); # or some integer
```
is basically equivalent to:
```
BEGIN { sub Pod::Simple::DEBUG () {5} } # or some integer
use Pod::Simple ();
```
And this:
```
use Pod::Simple::Debug (\$debug_level,0); # or some integer
```
is basically equivalent to this:
```
my $debug_level;
BEGIN { $debug_level = 0 }
BEGIN { sub Pod::Simple::DEBUG () { $debug_level }
use Pod::Simple ();
```
SEE ALSO
---------
<Pod::Simple>
The article "Constants in Perl", in *The Perl Journal* issue 21. See <http://interglacial.com/tpj/21/>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl perlfork perlfork
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Behavior of other Perl features in forked pseudo-processes](#Behavior-of-other-Perl-features-in-forked-pseudo-processes)
+ [Resource limits](#Resource-limits)
+ [Killing the parent process](#Killing-the-parent-process)
+ [Lifetime of the parent process and pseudo-processes](#Lifetime-of-the-parent-process-and-pseudo-processes)
* [CAVEATS AND LIMITATIONS](#CAVEATS-AND-LIMITATIONS)
* [PORTABILITY CAVEATS](#PORTABILITY-CAVEATS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlfork - Perl's fork() emulation
SYNOPSIS
--------
```
NOTE: As of the 5.8.0 release, fork() emulation has considerably
matured. However, there are still a few known bugs and differences
from real fork() that might affect you. See the "BUGS" and
"CAVEATS AND LIMITATIONS" sections below.
```
Perl provides a fork() keyword that corresponds to the Unix system call of the same name. On most Unix-like platforms where the fork() system call is available, Perl's fork() simply calls it.
On some platforms such as Windows where the fork() system call is not available, Perl can be built to emulate fork() at the interpreter level. While the emulation is designed to be as compatible as possible with the real fork() at the level of the Perl program, there are certain important differences that stem from the fact that all the pseudo child "processes" created this way live in the same real process as far as the operating system is concerned.
This document provides a general overview of the capabilities and limitations of the fork() emulation. Note that the issues discussed here are not applicable to platforms where a real fork() is available and Perl has been configured to use it.
DESCRIPTION
-----------
The fork() emulation is implemented at the level of the Perl interpreter. What this means in general is that running fork() will actually clone the running interpreter and all its state, and run the cloned interpreter in a separate thread, beginning execution in the new thread just after the point where the fork() was called in the parent. We will refer to the thread that implements this child "process" as the pseudo-process.
To the Perl program that called fork(), all this is designed to be transparent. The parent returns from the fork() with a pseudo-process ID that can be subsequently used in any process-manipulation functions; the child returns from the fork() with a value of `0` to signify that it is the child pseudo-process.
###
Behavior of other Perl features in forked pseudo-processes
Most Perl features behave in a natural way within pseudo-processes.
$$ or $PROCESS\_ID This special variable is correctly set to the pseudo-process ID. It can be used to identify pseudo-processes within a particular session. Note that this value is subject to recycling if any pseudo-processes are launched after others have been wait()-ed on.
%ENV Each pseudo-process maintains its own virtual environment. Modifications to %ENV affect the virtual environment, and are only visible within that pseudo-process, and in any processes (or pseudo-processes) launched from it.
chdir() and all other builtins that accept filenames Each pseudo-process maintains its own virtual idea of the current directory. Modifications to the current directory using chdir() are only visible within that pseudo-process, and in any processes (or pseudo-processes) launched from it. All file and directory accesses from the pseudo-process will correctly map the virtual working directory to the real working directory appropriately.
wait() and waitpid() wait() and waitpid() can be passed a pseudo-process ID returned by fork(). These calls will properly wait for the termination of the pseudo-process and return its status.
kill() `kill('KILL', ...)` can be used to terminate a pseudo-process by passing it the ID returned by fork(). The outcome of kill on a pseudo-process is unpredictable and it should not be used except under dire circumstances, because the operating system may not guarantee integrity of the process resources when a running thread is terminated. The process which implements the pseudo-processes can be blocked and the Perl interpreter hangs. Note that using `kill('KILL', ...)` on a pseudo-process() may typically cause memory leaks, because the thread that implements the pseudo-process does not get a chance to clean up its resources.
`kill('TERM', ...)` can also be used on pseudo-processes, but the signal will not be delivered while the pseudo-process is blocked by a system call, e.g. waiting for a socket to connect, or trying to read from a socket with no data available. Starting in Perl 5.14 the parent process will not wait for children to exit once they have been signalled with `kill('TERM', ...)` to avoid deadlock during process exit. You will have to explicitly call waitpid() to make sure the child has time to clean-up itself, but you are then also responsible that the child is not blocking on I/O either.
exec() Calling exec() within a pseudo-process actually spawns the requested executable in a separate process and waits for it to complete before exiting with the same exit status as that process. This means that the process ID reported within the running executable will be different from what the earlier Perl fork() might have returned. Similarly, any process manipulation functions applied to the ID returned by fork() will affect the waiting pseudo-process that called exec(), not the real process it is waiting for after the exec().
When exec() is called inside a pseudo-process then DESTROY methods and END blocks will still be called after the external process returns.
exit() exit() always exits just the executing pseudo-process, after automatically wait()-ing for any outstanding child pseudo-processes. Note that this means that the process as a whole will not exit unless all running pseudo-processes have exited. See below for some limitations with open filehandles.
Open handles to files, directories and network sockets All open handles are dup()-ed in pseudo-processes, so that closing any handles in one process does not affect the others. See below for some limitations.
###
Resource limits
In the eyes of the operating system, pseudo-processes created via the fork() emulation are simply threads in the same process. This means that any process-level limits imposed by the operating system apply to all pseudo-processes taken together. This includes any limits imposed by the operating system on the number of open file, directory and socket handles, limits on disk space usage, limits on memory size, limits on CPU utilization etc.
###
Killing the parent process
If the parent process is killed (either using Perl's kill() builtin, or using some external means) all the pseudo-processes are killed as well, and the whole process exits.
###
Lifetime of the parent process and pseudo-processes
During the normal course of events, the parent process and every pseudo-process started by it will wait for their respective pseudo-children to complete before they exit. This means that the parent and every pseudo-child created by it that is also a pseudo-parent will only exit after their pseudo-children have exited.
Starting with Perl 5.14 a parent will not wait() automatically for any child that has been signalled with `kill('TERM', ...)` to avoid a deadlock in case the child is blocking on I/O and never receives the signal.
CAVEATS AND LIMITATIONS
------------------------
BEGIN blocks The fork() emulation will not work entirely correctly when called from within a BEGIN block. The forked copy will run the contents of the BEGIN block, but will not continue parsing the source stream after the BEGIN block. For example, consider the following code:
```
BEGIN {
fork and exit; # fork child and exit the parent
print "inner\n";
}
print "outer\n";
```
This will print:
```
inner
```
rather than the expected:
```
inner
outer
```
This limitation arises from fundamental technical difficulties in cloning and restarting the stacks used by the Perl parser in the middle of a parse.
Open filehandles Any filehandles open at the time of the fork() will be dup()-ed. Thus, the files can be closed independently in the parent and child, but beware that the dup()-ed handles will still share the same seek pointer. Changing the seek position in the parent will change it in the child and vice-versa. One can avoid this by opening files that need distinct seek pointers separately in the child.
On some operating systems, notably Solaris and Unixware, calling `exit()` from a child process will flush and close open filehandles in the parent, thereby corrupting the filehandles. On these systems, calling `_exit()` is suggested instead. `_exit()` is available in Perl through the `POSIX` module. Please consult your system's manpages for more information on this.
Open directory handles Perl will completely read from all open directory handles until they reach the end of the stream. It will then seekdir() back to the original location and all future readdir() requests will be fulfilled from the cache buffer. That means that neither the directory handle held by the parent process nor the one held by the child process will see any changes made to the directory after the fork() call.
Note that rewinddir() has a similar limitation on Windows and will not force readdir() to read the directory again either. Only a newly opened directory handle will reflect changes to the directory.
Forking pipe open() not yet implemented The `open(FOO, "|-")` and `open(BAR, "-|")` constructs are not yet implemented. This limitation can be easily worked around in new code by creating a pipe explicitly. The following example shows how to write to a forked child:
```
# simulate open(FOO, "|-")
sub pipe_to_fork ($) {
my $parent = shift;
pipe my $child, $parent or die;
my $pid = fork();
die "fork() failed: $!" unless defined $pid;
if ($pid) {
close $child;
}
else {
close $parent;
open(STDIN, "<&=" . fileno($child)) or die;
}
$pid;
}
if (pipe_to_fork('FOO')) {
# parent
print FOO "pipe_to_fork\n";
close FOO;
}
else {
# child
while (<STDIN>) { print; }
exit(0);
}
```
And this one reads from the child:
```
# simulate open(FOO, "-|")
sub pipe_from_fork ($) {
my $parent = shift;
pipe $parent, my $child or die;
my $pid = fork();
die "fork() failed: $!" unless defined $pid;
if ($pid) {
close $child;
}
else {
close $parent;
open(STDOUT, ">&=" . fileno($child)) or die;
}
$pid;
}
if (pipe_from_fork('BAR')) {
# parent
while (<BAR>) { print; }
close BAR;
}
else {
# child
print "pipe_from_fork\n";
exit(0);
}
```
Forking pipe open() constructs will be supported in future.
Global state maintained by XSUBs External subroutines (XSUBs) that maintain their own global state may not work correctly. Such XSUBs will either need to maintain locks to protect simultaneous access to global data from different pseudo-processes, or maintain all their state on the Perl symbol table, which is copied naturally when fork() is called. A callback mechanism that provides extensions an opportunity to clone their state will be provided in the near future.
Interpreter embedded in larger application The fork() emulation may not behave as expected when it is executed in an application which embeds a Perl interpreter and calls Perl APIs that can evaluate bits of Perl code. This stems from the fact that the emulation only has knowledge about the Perl interpreter's own data structures and knows nothing about the containing application's state. For example, any state carried on the application's own call stack is out of reach.
Thread-safety of extensions Since the fork() emulation runs code in multiple threads, extensions calling into non-thread-safe libraries may not work reliably when calling fork(). As Perl's threading support gradually becomes more widely adopted even on platforms with a native fork(), such extensions are expected to be fixed for thread-safety.
PORTABILITY CAVEATS
--------------------
In portable Perl code, `kill(9, $child)` must not be used on forked processes. Killing a forked process is unsafe and has unpredictable results. See ["kill()"](#kill%28%29), above.
BUGS
----
* Having pseudo-process IDs be negative integers breaks down for the integer `-1` because the wait() and waitpid() functions treat this number as being special. The tacit assumption in the current implementation is that the system never allocates a thread ID of `1` for user threads. A better representation for pseudo-process IDs will be implemented in future.
* In certain cases, the OS-level handles created by the pipe(), socket(), and accept() operators are apparently not duplicated accurately in pseudo-processes. This only happens in some situations, but where it does happen, it may result in deadlocks between the read and write ends of pipe handles, or inability to send or receive data across socket handles.
* This document may be incomplete in some respects.
AUTHOR
------
Support for concurrent interpreters and the fork() emulation was implemented by ActiveState, with funding from Microsoft Corporation.
This document is authored and maintained by Gurusamy Sarathy <[email protected]>.
SEE ALSO
---------
["fork" in perlfunc](perlfunc#fork), <perlipc>
| programming_docs |
perl Compress::Raw::Bzip2 Compress::Raw::Bzip2
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Compression](#Compression)
+ [($z, $status) = new Compress::Raw::Bzip2 $appendOutput, $blockSize100k, $workfactor;](#(%24z,-%24status)-=-new-Compress::Raw::Bzip2-%24appendOutput,-%24blockSize100k,-%24workfactor;)
+ [$status = $bz->bzdeflate($input, $output);](#%24status-=-%24bz-%3Ebzdeflate(%24input,-%24output);)
+ [$status = $bz->bzflush($output);](#%24status-=-%24bz-%3Ebzflush(%24output);)
+ [$status = $bz->bzclose($output);](#%24status-=-%24bz-%3Ebzclose(%24output);)
+ [Example](#Example)
* [Uncompression](#Uncompression)
+ [($z, $status) = new Compress::Raw::Bunzip2 $appendOutput, $consumeInput, $small, $verbosity, $limitOutput;](#(%24z,-%24status)-=-new-Compress::Raw::Bunzip2-%24appendOutput,-%24consumeInput,-%24small,-%24verbosity,-%24limitOutput;)
+ [$status = $z->bzinflate($input, $output);](#%24status-=-%24z-%3Ebzinflate(%24input,-%24output);)
* [Misc](#Misc)
+ [my $version = Compress::Raw::Bzip2::bzlibversion();](#my-%24version-=-Compress::Raw::Bzip2::bzlibversion();)
* [Constants](#Constants)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Compress::Raw::Bzip2 - Low-Level Interface to bzip2 compression library
SYNOPSIS
--------
```
use Compress::Raw::Bzip2 ;
my ($bz, $status) = new Compress::Raw::Bzip2 [OPTS]
or die "Cannot create bzip2 object: $bzerno\n";
$status = $bz->bzdeflate($input, $output);
$status = $bz->bzflush($output);
$status = $bz->bzclose($output);
my ($bz, $status) = new Compress::Raw::Bunzip2 [OPTS]
or die "Cannot create bunzip2 object: $bzerno\n";
$status = $bz->bzinflate($input, $output);
my $version = Compress::Raw::Bzip2::bzlibversion();
```
DESCRIPTION
-----------
`Compress::Raw::Bzip2` provides an interface to the in-memory compression/uncompression functions from the bzip2 compression library.
Although the primary purpose for the existence of `Compress::Raw::Bzip2` is for use by the `IO::Compress::Bzip2` and `IO::Compress::Bunzip2` modules, it can be used on its own for simple compression/uncompression tasks.
Compression
-----------
###
($z, $status) = new Compress::Raw::Bzip2 $appendOutput, $blockSize100k, $workfactor;
Creates a new compression object.
If successful, it will return the initialised compression object, `$z` and a `$status` of `BZ_OK` in a list context. In scalar context it returns the deflation object, `$z`, only.
If not successful, the returned compression object, `$z`, will be *undef* and `$status` will hold the a *bzip2* error code.
Below is a list of the valid options:
**$appendOutput**
Controls whether the compressed data is appended to the output buffer in the `bzdeflate`, `bzflush` and `bzclose` methods.
Defaults to 1.
**$blockSize100k**
To quote the bzip2 documentation
```
blockSize100k specifies the block size to be used for compression. It
should be a value between 1 and 9 inclusive, and the actual block size
used is 100000 x this figure. 9 gives the best compression but takes
most memory.
```
Defaults to 1.
**$workfactor**
To quote the bzip2 documentation
```
This parameter controls how the compression phase behaves when
presented with worst case, highly repetitive, input data. If
compression runs into difficulties caused by repetitive data, the
library switches from the standard sorting algorithm to a fallback
algorithm. The fallback is slower than the standard algorithm by
perhaps a factor of three, but always behaves reasonably, no matter how
bad the input.
Lower values of workFactor reduce the amount of effort the standard
algorithm will expend before resorting to the fallback. You should set
this parameter carefully; too low, and many inputs will be handled by
the fallback algorithm and so compress rather slowly, too high, and
your average-to-worst case compression times can become very large. The
default value of 30 gives reasonable behaviour over a wide range of
circumstances.
Allowable values range from 0 to 250 inclusive. 0 is a special case,
equivalent to using the default value of 30.
```
Defaults to 0.
###
$status = $bz->bzdeflate($input, $output);
Reads the contents of `$input`, compresses it and writes the compressed data to `$output`.
Returns `BZ_RUN_OK` on success and a `bzip2` error code on failure.
If `appendOutput` is enabled in the constructor for the bzip2 object, the compressed data will be appended to `$output`. If not enabled, `$output` will be truncated before the compressed data is written to it.
###
$status = $bz->bzflush($output);
Flushes any pending compressed data to `$output`.
Returns `BZ_RUN_OK` on success and a `bzip2` error code on failure.
###
$status = $bz->bzclose($output);
Terminates the compressed data stream and flushes any pending compressed data to `$output`.
Returns `BZ_STREAM_END` on success and a `bzip2` error code on failure.
### Example
Uncompression
-------------
###
($z, $status) = new Compress::Raw::Bunzip2 $appendOutput, $consumeInput, $small, $verbosity, $limitOutput;
If successful, it will return the initialised uncompression object, `$z` and a `$status` of `BZ_OK` in a list context. In scalar context it returns the deflation object, `$z`, only.
If not successful, the returned uncompression object, `$z`, will be *undef* and `$status` will hold the a *bzip2* error code.
Below is a list of the valid options:
**$appendOutput**
Controls whether the compressed data is appended to the output buffer in the `bzinflate`, `bzflush` and `bzclose` methods.
Defaults to 1.
**$consumeInput**
**$small**
To quote the bzip2 documentation
```
If small is nonzero, the library will use an alternative decompression
algorithm which uses less memory but at the cost of decompressing more
slowly (roughly speaking, half the speed, but the maximum memory
requirement drops to around 2300k).
```
Defaults to 0.
**$limitOutput**
The `LimitOutput` option changes the behavior of the `$i->bzinflate` method so that the amount of memory used by the output buffer can be limited.
When `LimitOutput` is used the size of the output buffer used will either be the 16k or the amount of memory already allocated to `$output`, whichever is larger. Predicting the output size available is tricky, so don't rely on getting an exact output buffer size.
When `LimitOutout` is not specified `$i->bzinflate` will use as much memory as it takes to write all the uncompressed data it creates by uncompressing the input buffer.
If `LimitOutput` is enabled, the `ConsumeInput` option will also be enabled.
This option defaults to false.
**$verbosity**
This parameter is ignored.
Defaults to 0.
###
$status = $z->bzinflate($input, $output);
Uncompresses `$input` and writes the uncompressed data to `$output`.
Returns `BZ_OK` if the uncompression was successful, but the end of the compressed data stream has not been reached. Returns `BZ_STREAM_END` on successful uncompression and the end of the compression stream has been reached.
If `consumeInput` is enabled in the constructor for the bunzip2 object, `$input` will have all compressed data removed from it after uncompression. On `BZ_OK` return this will mean that `$input` will be an empty string; when `BZ_STREAM_END` `$input` will either be an empty string or will contain whatever data immediately followed the compressed data stream.
If `appendOutput` is enabled in the constructor for the bunzip2 object, the uncompressed data will be appended to `$output`. If not enabled, `$output` will be truncated before the uncompressed data is written to it.
Misc
----
###
my $version = Compress::Raw::Bzip2::bzlibversion();
Returns the version of the underlying bzip2 library.
Constants
---------
The following bzip2 constants are exported by this module
```
BZ_RUN
BZ_FLUSH
BZ_FINISH
BZ_OK
BZ_RUN_OK
BZ_FLUSH_OK
BZ_FINISH_OK
BZ_STREAM_END
BZ_SEQUENCE_ERROR
BZ_PARAM_ERROR
BZ_MEM_ERROR
BZ_DATA_ERROR
BZ_DATA_ERROR_MAGIC
BZ_IO_ERROR
BZ_UNEXPECTED_EOF
BZ_OUTBUFF_FULL
BZ_CONFIG_ERROR
```
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/Compress-Raw-Bzip2/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=Compress-Raw-Bzip2>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
The primary site for the bzip2 program is <https://sourceware.org/bzip2/>.
See the module <Compress::Bzip2>
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl AutoLoader AutoLoader
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Subroutine Stubs](#Subroutine-Stubs)
+ [Using AutoLoader's AUTOLOAD Subroutine](#Using-AutoLoader's-AUTOLOAD-Subroutine)
+ [Overriding AutoLoader's AUTOLOAD Subroutine](#Overriding-AutoLoader's-AUTOLOAD-Subroutine)
+ [Package Lexicals](#Package-Lexicals)
+ [Not Using AutoLoader](#Not-Using-AutoLoader)
+ [AutoLoader vs. SelfLoader](#AutoLoader-vs.-SelfLoader)
+ [Forcing AutoLoader to Load a Function](#Forcing-AutoLoader-to-Load-a-Function)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
AutoLoader - load subroutines only on demand
SYNOPSIS
--------
```
package Foo;
use AutoLoader 'AUTOLOAD'; # import the default AUTOLOAD subroutine
package Bar;
use AutoLoader; # don't import AUTOLOAD, define our own
sub AUTOLOAD {
...
$AutoLoader::AUTOLOAD = "...";
goto &AutoLoader::AUTOLOAD;
}
```
DESCRIPTION
-----------
The **AutoLoader** module works with the **AutoSplit** module and the `__END__` token to defer the loading of some subroutines until they are used rather than loading them all at once.
To use **AutoLoader**, the author of a module has to place the definitions of subroutines to be autoloaded after an `__END__` token. (See <perldata>.) The **AutoSplit** module can then be run manually to extract the definitions into individual files *auto/funcname.al*.
**AutoLoader** implements an AUTOLOAD subroutine. When an undefined subroutine in is called in a client module of **AutoLoader**, **AutoLoader**'s AUTOLOAD subroutine attempts to locate the subroutine in a file with a name related to the location of the file from which the client module was read. As an example, if *POSIX.pm* is located in */usr/local/lib/perl5/POSIX.pm*, **AutoLoader** will look for perl subroutines **POSIX** in */usr/local/lib/perl5/auto/POSIX/\*.al*, where the `.al` file has the same name as the subroutine, sans package. If such a file exists, AUTOLOAD will read and evaluate it, thus (presumably) defining the needed subroutine. AUTOLOAD will then `goto` the newly defined subroutine.
Once this process completes for a given function, it is defined, so future calls to the subroutine will bypass the AUTOLOAD mechanism.
###
Subroutine Stubs
In order for object method lookup and/or prototype checking to operate correctly even when methods have not yet been defined it is necessary to "forward declare" each subroutine (as in `sub NAME;`). See ["SYNOPSIS" in perlsub](perlsub#SYNOPSIS). Such forward declaration creates "subroutine stubs", which are place holders with no code.
The AutoSplit and **AutoLoader** modules automate the creation of forward declarations. The AutoSplit module creates an 'index' file containing forward declarations of all the AutoSplit subroutines. When the AutoLoader module is 'use'd it loads these declarations into its callers package.
Because of this mechanism it is important that **AutoLoader** is always `use`d and not `require`d.
###
Using **AutoLoader**'s AUTOLOAD Subroutine
In order to use **AutoLoader**'s AUTOLOAD subroutine you *must* explicitly import it:
```
use AutoLoader 'AUTOLOAD';
```
###
Overriding **AutoLoader**'s AUTOLOAD Subroutine
Some modules, mainly extensions, provide their own AUTOLOAD subroutines. They typically need to check for some special cases (such as constants) and then fallback to **AutoLoader**'s AUTOLOAD for the rest.
Such modules should *not* import **AutoLoader**'s AUTOLOAD subroutine. Instead, they should define their own AUTOLOAD subroutines along these lines:
```
use AutoLoader;
use Carp;
sub AUTOLOAD {
my $sub = $AUTOLOAD;
(my $constname = $sub) =~ s/.*:://;
my $val = constant($constname, @_ ? $_[0] : 0);
if ($! != 0) {
if ($! =~ /Invalid/ || $!{EINVAL}) {
$AutoLoader::AUTOLOAD = $sub;
goto &AutoLoader::AUTOLOAD;
}
else {
croak "Your vendor has not defined constant $constname";
}
}
*$sub = sub { $val }; # same as: eval "sub $sub { $val }";
goto &$sub;
}
```
If any module's own AUTOLOAD subroutine has no need to fallback to the AutoLoader's AUTOLOAD subroutine (because it doesn't have any AutoSplit subroutines), then that module should not use **AutoLoader** at all.
###
Package Lexicals
Package lexicals declared with `my` in the main block of a package using **AutoLoader** will not be visible to auto-loaded subroutines, due to the fact that the given scope ends at the `__END__` marker. A module using such variables as package globals will not work properly under the **AutoLoader**.
The `vars` pragma (see ["vars" in perlmod](perlmod#vars)) may be used in such situations as an alternative to explicitly qualifying all globals with the package namespace. Variables pre-declared with this pragma will be visible to any autoloaded routines (but will not be invisible outside the package, unfortunately).
###
Not Using AutoLoader
You can stop using AutoLoader by simply
```
no AutoLoader;
```
###
**AutoLoader** vs. **SelfLoader**
The **AutoLoader** is similar in purpose to **SelfLoader**: both delay the loading of subroutines.
**SelfLoader** uses the `__DATA__` marker rather than `__END__`. While this avoids the use of a hierarchy of disk files and the associated open/close for each routine loaded, **SelfLoader** suffers a startup speed disadvantage in the one-time parsing of the lines after `__DATA__`, after which routines are cached. **SelfLoader** can also handle multiple packages in a file.
**AutoLoader** only reads code as it is requested, and in many cases should be faster, but requires a mechanism like **AutoSplit** be used to create the individual files. <ExtUtils::MakeMaker> will invoke **AutoSplit** automatically if **AutoLoader** is used in a module source file.
###
Forcing AutoLoader to Load a Function
Sometimes, it can be necessary or useful to make sure that a certain function is fully loaded by AutoLoader. This is the case, for example, when you need to wrap a function to inject debugging code. It is also helpful to force early loading of code before forking to make use of copy-on-write as much as possible.
Starting with AutoLoader 5.73, you can call the `AutoLoader::autoload_sub` function with the fully-qualified name of the function to load from its *.al* file. The behaviour is exactly the same as if you called the function, triggering the regular `AUTOLOAD` mechanism, but it does not actually execute the autoloaded function.
CAVEATS
-------
AutoLoaders prior to Perl 5.002 had a slightly different interface. Any old modules which use **AutoLoader** should be changed to the new calling style. Typically this just means changing a require to a use, adding the explicit `'AUTOLOAD'` import if needed, and removing **AutoLoader** from `@ISA`.
On systems with restrictions on file name length, the file corresponding to a subroutine may have a shorter name that the routine itself. This can lead to conflicting file names. The *AutoSplit* package warns of these potential conflicts when used to split a module.
AutoLoader may fail to find the autosplit files (or even find the wrong ones) in cases where `@INC` contains relative paths, **and** the program does `chdir`.
SEE ALSO
---------
[SelfLoader](selfloader) - an autoloader that doesn't use external files.
AUTHOR
------
`AutoLoader` is maintained by the perl5-porters. Please direct any questions to the canonical mailing list. Anything that is applicable to the CPAN release can be sent to its maintainer, though.
Author and Maintainer: The Perl5-Porters <[email protected]>
Maintainer of the CPAN release: Steffen Mueller <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This package has been part of the perl core since the first release of perl5. It has been released separately to CPAN so older installations can benefit from bug fixes.
This package has the same copyright and license as the perl core:
```
Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
2011, 2012, 2013
by Larry Wall and others
All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of either:
a) the GNU General Public License as published by the Free
Software Foundation; either version 1, or (at your option) any
later version, or
b) the "Artistic License" which comes with this Kit.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
the GNU General Public License or the Artistic License for more details.
You should have received a copy of the Artistic License with this
Kit, in the file named "Artistic". If not, I'll be glad to provide one.
You should also have received a copy of the GNU General Public License
along with this program in the file named "Copying". If not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301, USA or visit their web page on the internet at
http://www.gnu.org/copyleft/gpl.html.
For those of you that choose to use the GNU General Public License,
my interpretation of the GNU General Public License is that no Perl
script falls under the terms of the GPL unless you explicitly put
said script under the terms of the GPL yourself. Furthermore, any
object code linked with perl does not automatically fall under the
terms of the GPL, provided such object code only adds definitions
of subroutines and variables, and does not otherwise impair the
resulting interpreter from executing any standard Perl script. I
consider linking in C subroutines in this manner to be the moral
equivalent of defining subroutines in the Perl language itself. You
may sell such an object file as proprietary provided that you provide
or offer to provide the Perl source, as specified by the GNU General
Public License. (This is merely an alternate way of specifying input
to the program.) You may also sell a binary produced by the dumping of
a running Perl script that belongs to you, provided that you provide or
offer to provide the Perl source as specified by the GPL. (The
fact that a Perl interpreter and your code are in the same binary file
is, in this case, a form of mere aggregation.) This is my interpretation
of the GPL. If you still have concerns or difficulties understanding
my intent, feel free to contact me. Of course, the Artistic License
spells all this out for your protection, so you may prefer to use that.
```
| programming_docs |
perl perlrecharclass perlrecharclass
===============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [The dot](#The-dot)
+ [Backslash sequences](#Backslash-sequences)
- [\N](#%5CN)
- [Digits](#Digits)
- [Word characters](#Word-characters)
- [Whitespace](#Whitespace)
- [Unicode Properties](#Unicode-Properties)
* [Examples](#Examples)
+ [Bracketed Character Classes](#Bracketed-Character-Classes)
- [Special Characters Inside a Bracketed Character Class](#Special-Characters-Inside-a-Bracketed-Character-Class)
- [Bracketed Character Classes and the /xx pattern modifier](#Bracketed-Character-Classes-and-the-/xx-pattern-modifier)
- [Character Ranges](#Character-Ranges)
- [Negation](#Negation)
- [Backslash Sequences](#Backslash-Sequences)
- [POSIX Character Classes](#POSIX-Character-Classes)
* [Negation of POSIX character classes](#Negation-of-POSIX-character-classes)
* [[= =] and [. .]](#%5B=-=%5D-and-%5B.-.%5D)
* [Examples](#Examples1)
- [Extended Bracketed Character Classes](#Extended-Bracketed-Character-Classes)
NAME
----
perlrecharclass - Perl Regular Expression Character Classes
DESCRIPTION
-----------
The top level documentation about Perl regular expressions is found in <perlre>.
This manual page discusses the syntax and use of character classes in Perl regular expressions.
A character class is a way of denoting a set of characters in such a way that one character of the set is matched. It's important to remember that: matching a character class consumes exactly one character in the source string. (The source string is the string the regular expression is matched against.)
There are three types of character classes in Perl regular expressions: the dot, backslash sequences, and the form enclosed in square brackets. Keep in mind, though, that often the term "character class" is used to mean just the bracketed form. Certainly, most Perl documentation does that.
###
The dot
The dot (or period), `.` is probably the most used, and certainly the most well-known character class. By default, a dot matches any character, except for the newline. That default can be changed to add matching the newline by using the *single line* modifier: for the entire regular expression with the `/s` modifier, or locally with `(?s)` (and even globally within the scope of [`use re '/s'`](re#%27%2Fflags%27-mode)). (The `["\N"](#%5CN)` backslash sequence, described below, matches any character except newline without regard to the *single line* modifier.)
Here are some examples:
```
"a" =~ /./ # Match
"." =~ /./ # Match
"" =~ /./ # No match (dot has to match a character)
"\n" =~ /./ # No match (dot does not match a newline)
"\n" =~ /./s # Match (global 'single line' modifier)
"\n" =~ /(?s:.)/ # Match (local 'single line' modifier)
"ab" =~ /^.$/ # No match (dot matches one character)
```
###
Backslash sequences
A backslash sequence is a sequence of characters, the first one of which is a backslash. Perl ascribes special meaning to many such sequences, and some of these are character classes. That is, they match a single character each, provided that the character belongs to the specific set of characters defined by the sequence.
Here's a list of the backslash sequences that are character classes. They are discussed in more detail below. (For the backslash sequences that aren't character classes, see <perlrebackslash>.)
```
\d Match a decimal digit character.
\D Match a non-decimal-digit character.
\w Match a "word" character.
\W Match a non-"word" character.
\s Match a whitespace character.
\S Match a non-whitespace character.
\h Match a horizontal whitespace character.
\H Match a character that isn't horizontal whitespace.
\v Match a vertical whitespace character.
\V Match a character that isn't vertical whitespace.
\N Match a character that isn't a newline.
\pP, \p{Prop} Match a character that has the given Unicode property.
\PP, \P{Prop} Match a character that doesn't have the Unicode property
```
####
\N
`\N`, available starting in v5.12, like the dot, matches any character that is not a newline. The difference is that `\N` is not influenced by the *single line* regular expression modifier (see ["The dot"](#The-dot) above). Note that the form `\N{...}` may mean something completely different. When the `{...}` is a [quantifier](perlre#Quantifiers), it means to match a non-newline character that many times. For example, `\N{3}` means to match 3 non-newlines; `\N{5,}` means to match 5 or more non-newlines. But if `{...}` is not a legal quantifier, it is presumed to be a named character. See <charnames> for those. For example, none of `\N{COLON}`, `\N{4F}`, and `\N{F4}` contain legal quantifiers, so Perl will try to find characters whose names are respectively `COLON`, `4F`, and `F4`.
#### Digits
`\d` matches a single character considered to be a decimal *digit*. If the `/a` regular expression modifier is in effect, it matches [0-9]. Otherwise, it matches anything that is matched by `\p{Digit}`, which includes [0-9]. (An unlikely possible exception is that under locale matching rules, the current locale might not have `[0-9]` matched by `\d`, and/or might match other characters whose code point is less than 256. The only such locale definitions that are legal would be to match `[0-9]` plus another set of 10 consecutive digit characters; anything else would be in violation of the C language standard, but Perl doesn't currently assume anything in regard to this.)
What this means is that unless the `/a` modifier is in effect `\d` not only matches the digits '0' - '9', but also Arabic, Devanagari, and digits from other languages. This may cause some confusion, and some security issues.
Some digits that `\d` matches look like some of the [0-9] ones, but have different values. For example, BENGALI DIGIT FOUR (U+09EA) looks very much like an ASCII DIGIT EIGHT (U+0038), and LEPCHA DIGIT SIX (U+1C46) looks very much like an ASCII DIGIT FIVE (U+0035). An application that is expecting only the ASCII digits might be misled, or if the match is `\d+`, the matched string might contain a mixture of digits from different writing systems that look like they signify a number different than they actually do. ["num()" in Unicode::UCD](Unicode::UCD#num%28%29) can be used to safely calculate the value, returning `undef` if the input string contains such a mixture. Otherwise, for example, a displayed price might be deliberately different than it appears.
What `\p{Digit}` means (and hence `\d` except under the `/a` modifier) is `\p{General_Category=Decimal_Number}`, or synonymously, `\p{General_Category=Digit}`. Starting with Unicode version 4.1, this is the same set of characters matched by `\p{Numeric_Type=Decimal}`. But Unicode also has a different property with a similar name, `\p{Numeric_Type=Digit}`, which matches a completely different set of characters. These characters are things such as `CIRCLED DIGIT ONE` or subscripts, or are from writing systems that lack all ten digits.
The design intent is for `\d` to exactly match the set of characters that can safely be used with "normal" big-endian positional decimal syntax, where, for example 123 means one 'hundred', plus two 'tens', plus three 'ones'. This positional notation does not necessarily apply to characters that match the other type of "digit", `\p{Numeric_Type=Digit}`, and so `\d` doesn't match them.
The Tamil digits (U+0BE6 - U+0BEF) can also legally be used in old-style Tamil numbers in which they would appear no more than one in a row, separated by characters that mean "times 10", "times 100", etc. (See <https://www.unicode.org/notes/tn21>.)
Any character not matched by `\d` is matched by `\D`.
####
Word characters
A `\w` matches a single alphanumeric character (an alphabetic character, or a decimal digit); or a connecting punctuation character, such as an underscore ("\_"); or a "mark" character (like some sort of accent) that attaches to one of those. It does not match a whole word. To match a whole word, use `\w+`. This isn't the same thing as matching an English word, but in the ASCII range it is the same as a string of Perl-identifier characters.
If the `/a` modifier is in effect ... `\w` matches the 63 characters [a-zA-Z0-9\_].
otherwise ...
For code points above 255 ... `\w` matches the same as `\p{Word}` matches in this range. That is, it matches Thai letters, Greek letters, etc. This includes connector punctuation (like the underscore) which connect two words together, or diacritics, such as a `COMBINING TILDE` and the modifier letters, which are generally used to add auxiliary markings to letters.
For code points below 256 ...
if locale rules are in effect ... `\w` matches the platform's native underscore character plus whatever the locale considers to be alphanumeric.
if, instead, Unicode rules are in effect ... `\w` matches exactly what `\p{Word}` matches.
otherwise ... `\w` matches [a-zA-Z0-9\_].
Which rules apply are determined as described in ["Which character set modifier is in effect?" in perlre](perlre#Which-character-set-modifier-is-in-effect%3F).
There are a number of security issues with the full Unicode list of word characters. See <http://unicode.org/reports/tr36>.
Also, for a somewhat finer-grained set of characters that are in programming language identifiers beyond the ASCII range, you may wish to instead use the more customized ["Unicode Properties"](#Unicode-Properties), `\p{ID_Start}`, `\p{ID_Continue}`, `\p{XID_Start}`, and `\p{XID_Continue}`. See <http://unicode.org/reports/tr31>.
Any character not matched by `\w` is matched by `\W`.
#### Whitespace
`\s` matches any single character considered whitespace.
If the `/a` modifier is in effect ... In all Perl versions, `\s` matches the 5 characters [\t\n\f\r ]; that is, the horizontal tab, the newline, the form feed, the carriage return, and the space. Starting in Perl v5.18, it also matches the vertical tab, `\cK`. See note `[1]` below for a discussion of this.
otherwise ...
For code points above 255 ... `\s` matches exactly the code points above 255 shown with an "s" column in the table below.
For code points below 256 ...
if locale rules are in effect ... `\s` matches whatever the locale considers to be whitespace.
if, instead, Unicode rules are in effect ... `\s` matches exactly the characters shown with an "s" column in the table below.
otherwise ... `\s` matches [\t\n\f\r ] and, starting in Perl v5.18, the vertical tab, `\cK`. (See note `[1]` below for a discussion of this.) Note that this list doesn't include the non-breaking space.
Which rules apply are determined as described in ["Which character set modifier is in effect?" in perlre](perlre#Which-character-set-modifier-is-in-effect%3F).
Any character not matched by `\s` is matched by `\S`.
`\h` matches any character considered horizontal whitespace; this includes the platform's space and tab characters and several others listed in the table below. `\H` matches any character not considered horizontal whitespace. They use the platform's native character set, and do not consider any locale that may otherwise be in use.
`\v` matches any character considered vertical whitespace; this includes the platform's carriage return and line feed characters (newline) plus several other characters, all listed in the table below. `\V` matches any character not considered vertical whitespace. They use the platform's native character set, and do not consider any locale that may otherwise be in use.
`\R` matches anything that can be considered a newline under Unicode rules. It can match a multi-character sequence. It cannot be used inside a bracketed character class; use `\v` instead (vertical whitespace). It uses the platform's native character set, and does not consider any locale that may otherwise be in use. Details are discussed in <perlrebackslash>.
Note that unlike `\s` (and `\d` and `\w`), `\h` and `\v` always match the same characters, without regard to other factors, such as the active locale or whether the source string is in UTF-8 format.
One might think that `\s` is equivalent to `[\h\v]`. This is indeed true starting in Perl v5.18, but prior to that, the sole difference was that the vertical tab (`"\cK"`) was not matched by `\s`.
The following table is a complete listing of characters matched by `\s`, `\h` and `\v` as of Unicode 14.0.
The first column gives the Unicode code point of the character (in hex format), the second column gives the (Unicode) name. The third column indicates by which class(es) the character is matched (assuming no locale is in effect that changes the `\s` matching).
```
0x0009 CHARACTER TABULATION h s
0x000a LINE FEED (LF) vs
0x000b LINE TABULATION vs [1]
0x000c FORM FEED (FF) vs
0x000d CARRIAGE RETURN (CR) vs
0x0020 SPACE h s
0x0085 NEXT LINE (NEL) vs [2]
0x00a0 NO-BREAK SPACE h s [2]
0x1680 OGHAM SPACE MARK h s
0x2000 EN QUAD h s
0x2001 EM QUAD h s
0x2002 EN SPACE h s
0x2003 EM SPACE h s
0x2004 THREE-PER-EM SPACE h s
0x2005 FOUR-PER-EM SPACE h s
0x2006 SIX-PER-EM SPACE h s
0x2007 FIGURE SPACE h s
0x2008 PUNCTUATION SPACE h s
0x2009 THIN SPACE h s
0x200a HAIR SPACE h s
0x2028 LINE SEPARATOR vs
0x2029 PARAGRAPH SEPARATOR vs
0x202f NARROW NO-BREAK SPACE h s
0x205f MEDIUM MATHEMATICAL SPACE h s
0x3000 IDEOGRAPHIC SPACE h s
```
[1] Prior to Perl v5.18, `\s` did not match the vertical tab. `[^\S\cK]` (obscurely) matches what `\s` traditionally did.
[2] NEXT LINE and NO-BREAK SPACE may or may not match `\s` depending on the rules in effect. See [the beginning of this section](#Whitespace).
####
Unicode Properties
`\pP` and `\p{Prop}` are character classes to match characters that fit given Unicode properties. One letter property names can be used in the `\pP` form, with the property name following the `\p`, otherwise, braces are required. When using braces, there is a single form, which is just the property name enclosed in the braces, and a compound form which looks like `\p{name=value}`, which means to match if the property "name" for the character has that particular "value". For instance, a match for a number can be written as `/\pN/` or as `/\p{Number}/`, or as `/\p{Number=True}/`. Lowercase letters are matched by the property *Lowercase\_Letter* which has the short form *Ll*. They need the braces, so are written as `/\p{Ll}/` or `/\p{Lowercase_Letter}/`, or `/\p{General_Category=Lowercase_Letter}/` (the underscores are optional). `/\pLl/` is valid, but means something different. It matches a two character string: a letter (Unicode property `\pL`), followed by a lowercase `l`.
What a Unicode property matches is never subject to locale rules, and if locale rules are not otherwise in effect, the use of a Unicode property will force the regular expression into using Unicode rules, if it isn't already.
Note that almost all properties are immune to case-insensitive matching. That is, adding a `/i` regular expression modifier does not change what they match. But there are two sets that are affected. The first set is `Uppercase_Letter`, `Lowercase_Letter`, and `Titlecase_Letter`, all of which match `Cased_Letter` under `/i` matching. The second set is `Uppercase`, `Lowercase`, and `Titlecase`, all of which match `Cased` under `/i` matching. (The difference between these sets is that some things, such as Roman numerals, come in both upper and lower case, so they are `Cased`, but aren't considered to be letters, so they aren't `Cased_Letter`s. They're actually `Letter_Number`s.) This set also includes its subsets `PosixUpper` and `PosixLower`, both of which under `/i` match `PosixAlpha`.
For more details on Unicode properties, see ["Unicode Character Properties" in perlunicode](perlunicode#Unicode-Character-Properties); for a complete list of possible properties, see ["Properties accessible through \p{} and \P{}" in perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D), which notes all forms that have `/i` differences. It is also possible to define your own properties. This is discussed in ["User-Defined Character Properties" in perlunicode](perlunicode#User-Defined-Character-Properties).
Unicode properties are defined (surprise!) only on Unicode code points. Starting in v5.20, when matching against `\p` and `\P`, Perl treats non-Unicode code points (those above the legal Unicode maximum of 0x10FFFF) as if they were typical unassigned Unicode code points.
Prior to v5.20, Perl raised a warning and made all matches fail on non-Unicode code points. This could be somewhat surprising:
```
chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails on Perls < v5.20.
chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Also fails on Perls
# < v5.20
```
Even though these two matches might be thought of as complements, until v5.20 they were so only on Unicode code points.
Starting in perl v5.30, wildcards are allowed in Unicode property values. See ["Wildcards in Property Values" in perlunicode](perlunicode#Wildcards-in-Property-Values).
##### Examples
```
"a" =~ /\w/ # Match, "a" is a 'word' character.
"7" =~ /\w/ # Match, "7" is a 'word' character as well.
"a" =~ /\d/ # No match, "a" isn't a digit.
"7" =~ /\d/ # Match, "7" is a digit.
" " =~ /\s/ # Match, a space is whitespace.
"a" =~ /\D/ # Match, "a" is a non-digit.
"7" =~ /\D/ # No match, "7" is not a non-digit.
" " =~ /\S/ # No match, a space is not non-whitespace.
" " =~ /\h/ # Match, space is horizontal whitespace.
" " =~ /\v/ # No match, space is not vertical whitespace.
"\r" =~ /\v/ # Match, a return is vertical whitespace.
"a" =~ /\pL/ # Match, "a" is a letter.
"a" =~ /\p{Lu}/ # No match, /\p{Lu}/ matches upper case letters.
"\x{0e0b}" =~ /\p{Thai}/ # Match, \x{0e0b} is the character
# 'THAI CHARACTER SO SO', and that's in
# Thai Unicode class.
"a" =~ /\P{Lao}/ # Match, as "a" is not a Laotian character.
```
It is worth emphasizing that `\d`, `\w`, etc, match single characters, not complete numbers or words. To match a number (that consists of digits), use `\d+`; to match a word, use `\w+`. But be aware of the security considerations in doing so, as mentioned above.
###
Bracketed Character Classes
The third form of character class you can use in Perl regular expressions is the bracketed character class. In its simplest form, it lists the characters that may be matched, surrounded by square brackets, like this: `[aeiou]`. This matches one of `a`, `e`, `i`, `o` or `u`. Like the other character classes, exactly one character is matched.\* To match a longer string consisting of characters mentioned in the character class, follow the character class with a [quantifier](perlre#Quantifiers). For instance, `[aeiou]+` matches one or more lowercase English vowels.
Repeating a character in a character class has no effect; it's considered to be in the set only once.
Examples:
```
"e" =~ /[aeiou]/ # Match, as "e" is listed in the class.
"p" =~ /[aeiou]/ # No match, "p" is not listed in the class.
"ae" =~ /^[aeiou]$/ # No match, a character class only matches
# a single character.
"ae" =~ /^[aeiou]+$/ # Match, due to the quantifier.
-------
```
\* There are two exceptions to a bracketed character class matching a single character only. Each requires special handling by Perl to make things work:
* When the class is to match caselessly under `/i` matching rules, and a character that is explicitly mentioned inside the class matches a multiple-character sequence caselessly under Unicode rules, the class will also match that sequence. For example, Unicode says that the letter `LATIN SMALL LETTER SHARP S` should match the sequence `ss` under `/i` rules. Thus,
```
'ss' =~ /\A\N{LATIN SMALL LETTER SHARP S}\z/i # Matches
'ss' =~ /\A[aeioust\N{LATIN SMALL LETTER SHARP S}]\z/i # Matches
```
For this to happen, the class must not be inverted (see ["Negation"](#Negation)) and the character must be explicitly specified, and not be part of a multi-character range (not even as one of its endpoints). (["Character Ranges"](#Character-Ranges) will be explained shortly.) Therefore,
```
'ss' =~ /\A[\0-\x{ff}]\z/ui # Doesn't match
'ss' =~ /\A[\0-\N{LATIN SMALL LETTER SHARP S}]\z/ui # No match
'ss' =~ /\A[\xDF-\xDF]\z/ui # Matches on ASCII platforms, since
# \xDF is LATIN SMALL LETTER SHARP S,
# and the range is just a single
# element
```
Note that it isn't a good idea to specify these types of ranges anyway.
* Some names known to `\N{...}` refer to a sequence of multiple characters, instead of the usual single character. When one of these is included in the class, the entire sequence is matched. For example,
```
"\N{TAMIL LETTER KA}\N{TAMIL VOWEL SIGN AU}"
=~ / ^ [\N{TAMIL SYLLABLE KAU}] $ /x;
```
matches, because `\N{TAMIL SYLLABLE KAU}` is a named sequence consisting of the two characters matched against. Like the other instance where a bracketed class can match multiple characters, and for similar reasons, the class must not be inverted, and the named sequence may not appear in a range, even one where it is both endpoints. If these happen, it is a fatal error if the character class is within the scope of [`use re 'strict`](re#%27strict%27-mode), or within an extended [`(?[...])`](#Extended-Bracketed-Character-Classes) class; otherwise only the first code point is used (with a `regexp`-type warning raised).
####
Special Characters Inside a Bracketed Character Class
Most characters that are meta characters in regular expressions (that is, characters that carry a special meaning like `.`, `*`, or `(`) lose their special meaning and can be used inside a character class without the need to escape them. For instance, `[()]` matches either an opening parenthesis, or a closing parenthesis, and the parens inside the character class don't group or capture. Be aware that, unless the pattern is evaluated in single-quotish context, variable interpolation will take place before the bracketed class is parsed:
```
$, = "\t| ";
$a =~ m'[$,]'; # single-quotish: matches '$' or ','
$a =~ q{[$,]}' # same
$a =~ m/[$,]/; # double-quotish: Because we made an
# assignment to $, above, this now
# matches "\t", "|", or " "
```
Characters that may carry a special meaning inside a character class are: `\`, `^`, `-`, `[` and `]`, and are discussed below. They can be escaped with a backslash, although this is sometimes not needed, in which case the backslash may be omitted.
The sequence `\b` is special inside a bracketed character class. While outside the character class, `\b` is an assertion indicating a point that does not have either two word characters or two non-word characters on either side, inside a bracketed character class, `\b` matches a backspace character.
The sequences `\a`, `\c`, `\e`, `\f`, `\n`, `\N{*NAME*}`, `\N{U+*hex char*}`, `\r`, `\t`, and `\x` are also special and have the same meanings as they do outside a bracketed character class.
Also, a backslash followed by two or three octal digits is considered an octal number.
A `[` is not special inside a character class, unless it's the start of a POSIX character class (see ["POSIX Character Classes"](#POSIX-Character-Classes) below). It normally does not need escaping.
A `]` is normally either the end of a POSIX character class (see ["POSIX Character Classes"](#POSIX-Character-Classes) below), or it signals the end of the bracketed character class. If you want to include a `]` in the set of characters, you must generally escape it.
However, if the `]` is the *first* (or the second if the first character is a caret) character of a bracketed character class, it does not denote the end of the class (as you cannot have an empty class) and is considered part of the set of characters that can be matched without escaping.
Examples:
```
"+" =~ /[+?*]/ # Match, "+" in a character class is not special.
"\cH" =~ /[\b]/ # Match, \b inside in a character class
# is equivalent to a backspace.
"]" =~ /[][]/ # Match, as the character class contains
# both [ and ].
"[]" =~ /[[]]/ # Match, the pattern contains a character class
# containing just [, and the character class is
# followed by a ].
```
####
Bracketed Character Classes and the `/xx` pattern modifier
Normally SPACE and TAB characters have no special meaning inside a bracketed character class; they are just added to the list of characters matched by the class. But if the [`/xx`](perlre#%2Fx-and-%2Fxx) pattern modifier is in effect, they are generally ignored and can be added to improve readability. They can't be added in the middle of a single construct:
```
/ [ \x{10 FFFF} ] /xx # WRONG!
```
The SPACE in the middle of the hex constant is illegal.
To specify a literal SPACE character, you can escape it with a backslash, like:
```
/[ a e i o u \ ]/xx
```
This matches the English vowels plus the SPACE character.
For clarity, you should already have been using `\t` to specify a literal tab, and `\t` is unaffected by `/xx`.
####
Character Ranges
It is not uncommon to want to match a range of characters. Luckily, instead of listing all characters in the range, one may use the hyphen (`-`). If inside a bracketed character class you have two characters separated by a hyphen, it's treated as if all characters between the two were in the class. For instance, `[0-9]` matches any ASCII digit, and `[a-m]` matches any lowercase letter from the first half of the ASCII alphabet.
Note that the two characters on either side of the hyphen are not necessarily both letters or both digits. Any character is possible, although not advisable. `['-?]` contains a range of characters, but most people will not know which characters that means. Furthermore, such ranges may lead to portability problems if the code has to run on a platform that uses a different character set, such as EBCDIC.
If a hyphen in a character class cannot syntactically be part of a range, for instance because it is the first or the last character of the character class, or if it immediately follows a range, the hyphen isn't special, and so is considered a character to be matched literally. If you want a hyphen in your set of characters to be matched and its position in the class is such that it could be considered part of a range, you must escape that hyphen with a backslash.
Examples:
```
[a-z] # Matches a character that is a lower case ASCII letter.
[a-fz] # Matches any letter between 'a' and 'f' (inclusive) or
# the letter 'z'.
[-z] # Matches either a hyphen ('-') or the letter 'z'.
[a-f-m] # Matches any letter between 'a' and 'f' (inclusive), the
# hyphen ('-'), or the letter 'm'.
['-?] # Matches any of the characters '()*+,-./0123456789:;<=>?
# (But not on an EBCDIC platform).
[\N{APOSTROPHE}-\N{QUESTION MARK}]
# Matches any of the characters '()*+,-./0123456789:;<=>?
# even on an EBCDIC platform.
[\N{U+27}-\N{U+3F}] # Same. (U+27 is "'", and U+3F is "?")
```
As the final two examples above show, you can achieve portability to non-ASCII platforms by using the `\N{...}` form for the range endpoints. These indicate that the specified range is to be interpreted using Unicode values, so `[\N{U+27}-\N{U+3F}]` means to match `\N{U+27}`, `\N{U+28}`, `\N{U+29}`, ..., `\N{U+3D}`, `\N{U+3E}`, and `\N{U+3F}`, whatever the native code point versions for those are. These are called "Unicode" ranges. If either end is of the `\N{...}` form, the range is considered Unicode. A `regexp` warning is raised under `"use re 'strict'"` if the other endpoint is specified non-portably:
```
[\N{U+00}-\x09] # Warning under re 'strict'; \x09 is non-portable
[\N{U+00}-\t] # No warning;
```
Both of the above match the characters `\N{U+00}` `\N{U+01}`, ... `\N{U+08}`, `\N{U+09}`, but the `\x09` looks like it could be a mistake so the warning is raised (under `re 'strict'`) for it.
Perl also guarantees that the ranges `A-Z`, `a-z`, `0-9`, and any subranges of these match what an English-only speaker would expect them to match on any platform. That is, `[A-Z]` matches the 26 ASCII uppercase letters; `[a-z]` matches the 26 lowercase letters; and `[0-9]` matches the 10 digits. Subranges, like `[h-k]`, match correspondingly, in this case just the four letters `"h"`, `"i"`, `"j"`, and `"k"`. This is the natural behavior on ASCII platforms where the code points (ordinal values) for `"h"` through `"k"` are consecutive integers (0x68 through 0x6B). But special handling to achieve this may be needed on platforms with a non-ASCII native character set. For example, on EBCDIC platforms, the code point for `"h"` is 0x88, `"i"` is 0x89, `"j"` is 0x91, and `"k"` is 0x92. Perl specially treats `[h-k]` to exclude the seven code points in the gap: 0x8A through 0x90. This special handling is only invoked when the range is a subrange of one of the ASCII uppercase, lowercase, and digit ranges, AND each end of the range is expressed either as a literal, like `"A"`, or as a named character (`\N{...}`, including the `\N{U+...` form).
EBCDIC Examples:
```
[i-j] # Matches either "i" or "j"
[i-\N{LATIN SMALL LETTER J}] # Same
[i-\N{U+6A}] # Same
[\N{U+69}-\N{U+6A}] # Same
[\x{89}-\x{91}] # Matches 0x89 ("i"), 0x8A .. 0x90, 0x91 ("j")
[i-\x{91}] # Same
[\x{89}-j] # Same
[i-J] # Matches, 0x89 ("i") .. 0xC1 ("J"); special
# handling doesn't apply because range is mixed
# case
```
#### Negation
It is also possible to instead list the characters you do not want to match. You can do so by using a caret (`^`) as the first character in the character class. For instance, `[^a-z]` matches any character that is not a lowercase ASCII letter, which therefore includes more than a million Unicode code points. The class is said to be "negated" or "inverted".
This syntax make the caret a special character inside a bracketed character class, but only if it is the first character of the class. So if you want the caret as one of the characters to match, either escape the caret or else don't list it first.
In inverted bracketed character classes, Perl ignores the Unicode rules that normally say that named sequence, and certain characters should match a sequence of multiple characters use under caseless `/i` matching. Following those rules could lead to highly confusing situations:
```
"ss" =~ /^[^\xDF]+$/ui; # Matches!
```
This should match any sequences of characters that aren't `\xDF` nor what `\xDF` matches under `/i`. `"s"` isn't `\xDF`, but Unicode says that `"ss"` is what `\xDF` matches under `/i`. So which one "wins"? Do you fail the match because the string has `ss` or accept it because it has an `s` followed by another `s`? Perl has chosen the latter. (See note in ["Bracketed Character Classes"](#Bracketed-Character-Classes) above.)
Examples:
```
"e" =~ /[^aeiou]/ # No match, the 'e' is listed.
"x" =~ /[^aeiou]/ # Match, as 'x' isn't a lowercase vowel.
"^" =~ /[^^]/ # No match, matches anything that isn't a caret.
"^" =~ /[x^]/ # Match, caret is not special here.
```
####
Backslash Sequences
You can put any backslash sequence character class (with the exception of `\N` and `\R`) inside a bracketed character class, and it will act just as if you had put all characters matched by the backslash sequence inside the character class. For instance, `[a-f\d]` matches any decimal digit, or any of the lowercase letters between 'a' and 'f' inclusive.
`\N` within a bracketed character class must be of the forms `\N{*name*}` or `\N{U+*hex char*}`, and NOT be the form that matches non-newlines, for the same reason that a dot `.` inside a bracketed character class loses its special meaning: it matches nearly anything, which generally isn't what you want to happen.
Examples:
```
/[\p{Thai}\d]/ # Matches a character that is either a Thai
# character, or a digit.
/[^\p{Arabic}()]/ # Matches a character that is neither an Arabic
# character, nor a parenthesis.
```
Backslash sequence character classes cannot form one of the endpoints of a range. Thus, you can't say:
```
/[\p{Thai}-\d]/ # Wrong!
```
####
POSIX Character Classes
POSIX character classes have the form `[:class:]`, where *class* is the name, and the `[:` and `:]` delimiters. POSIX character classes only appear *inside* bracketed character classes, and are a convenient and descriptive way of listing a group of characters.
Be careful about the syntax,
```
# Correct:
$string =~ /[[:alpha:]]/
# Incorrect (will warn):
$string =~ /[:alpha:]/
```
The latter pattern would be a character class consisting of a colon, and the letters `a`, `l`, `p` and `h`.
POSIX character classes can be part of a larger bracketed character class. For example,
```
[01[:alpha:]%]
```
is valid and matches '0', '1', any alphabetic character, and the percent sign.
Perl recognizes the following POSIX character classes:
```
alpha Any alphabetical character (e.g., [A-Za-z]).
alnum Any alphanumeric character (e.g., [A-Za-z0-9]).
ascii Any character in the ASCII character set.
blank A GNU extension, equal to a space or a horizontal tab ("\t").
cntrl Any control character. See Note [2] below.
digit Any decimal digit (e.g., [0-9]), equivalent to "\d".
graph Any printable character, excluding a space. See Note [3] below.
lower Any lowercase character (e.g., [a-z]).
print Any printable character, including a space. See Note [4] below.
punct Any graphical character excluding "word" characters. Note [5].
space Any whitespace character. "\s" including the vertical tab
("\cK").
upper Any uppercase character (e.g., [A-Z]).
word A Perl extension (e.g., [A-Za-z0-9_]), equivalent to "\w".
xdigit Any hexadecimal digit (e.g., [0-9a-fA-F]). Note [7].
```
Like the [Unicode properties](#Unicode-Properties), most of the POSIX properties match the same regardless of whether case-insensitive (`/i`) matching is in effect or not. The two exceptions are `[:upper:]` and `[:lower:]`. Under `/i`, they each match the union of `[:upper:]` and `[:lower:]`.
Most POSIX character classes have two Unicode-style `\p` property counterparts. (They are not official Unicode properties, but Perl extensions derived from official Unicode properties.) The table below shows the relation between POSIX character classes and these counterparts.
One counterpart, in the column labelled "ASCII-range Unicode" in the table, matches only characters in the ASCII character set.
The other counterpart, in the column labelled "Full-range Unicode", matches any appropriate characters in the full Unicode character set. For example, `\p{Alpha}` matches not just the ASCII alphabetic characters, but any character in the entire Unicode character set considered alphabetic. An entry in the column labelled "backslash sequence" is a (short) equivalent.
```
[[:...:]] ASCII-range Full-range backslash Note
Unicode Unicode sequence
-----------------------------------------------------
alpha \p{PosixAlpha} \p{XPosixAlpha}
alnum \p{PosixAlnum} \p{XPosixAlnum}
ascii \p{ASCII}
blank \p{PosixBlank} \p{XPosixBlank} \h [1]
or \p{HorizSpace} [1]
cntrl \p{PosixCntrl} \p{XPosixCntrl} [2]
digit \p{PosixDigit} \p{XPosixDigit} \d
graph \p{PosixGraph} \p{XPosixGraph} [3]
lower \p{PosixLower} \p{XPosixLower}
print \p{PosixPrint} \p{XPosixPrint} [4]
punct \p{PosixPunct} \p{XPosixPunct} [5]
\p{PerlSpace} \p{XPerlSpace} \s [6]
space \p{PosixSpace} \p{XPosixSpace} [6]
upper \p{PosixUpper} \p{XPosixUpper}
word \p{PosixWord} \p{XPosixWord} \w
xdigit \p{PosixXDigit} \p{XPosixXDigit} [7]
```
[1] `\p{Blank}` and `\p{HorizSpace}` are synonyms.
[2] Control characters don't produce output as such, but instead usually control the terminal somehow: for example, newline and backspace are control characters. On ASCII platforms, in the ASCII range, characters whose code points are between 0 and 31 inclusive, plus 127 (`DEL`) are control characters; on EBCDIC platforms, their counterparts are control characters.
[3] Any character that is *graphical*, that is, visible. This class consists of all alphanumeric characters and all punctuation characters.
[4] All printable characters, which is the set of all graphical characters plus those whitespace characters which are not also controls.
[5] `\p{PosixPunct}` and `[[:punct:]]` in the ASCII range match all non-controls, non-alphanumeric, non-space characters: `[-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~]` (although if a locale is in effect, it could alter the behavior of `[[:punct:]]`).
The similarly named property, `\p{Punct}`, matches a somewhat different set in the ASCII range, namely `[-!"#%&'()*,./:;?@[\\\]_{}]`. That is, it is missing the nine characters `[$+<=>^`|~]`. This is because Unicode splits what POSIX considers to be punctuation into two categories, Punctuation and Symbols.
`\p{XPosixPunct}` and (under Unicode rules) `[[:punct:]]`, match what `\p{PosixPunct}` matches in the ASCII range, plus what `\p{Punct}` matches. This is different than strictly matching according to `\p{Punct}`. Another way to say it is that if Unicode rules are in effect, `[[:punct:]]` matches all characters that Unicode considers punctuation, plus all ASCII-range characters that Unicode considers symbols.
[6] `\p{XPerlSpace}` and `\p{Space}` match identically starting with Perl v5.18. In earlier versions, these differ only in that in non-locale matching, `\p{XPerlSpace}` did not match the vertical tab, `\cK`. Same for the two ASCII-only range forms.
[7] Unlike `[[:digit:]]` which matches digits in many writing systems, such as Thai and Devanagari, there are currently only two sets of hexadecimal digits, and it is unlikely that more will be added. This is because you not only need the ten digits, but also the six `[A-F]` (and `[a-f]`) to correspond. That means only the Latin script is suitable for these, and Unicode has only two sets of these, the familiar ASCII set, and the fullwidth forms starting at U+FF10 (FULLWIDTH DIGIT ZERO).
There are various other synonyms that can be used besides the names listed in the table. For example, `\p{XPosixAlpha}` can be written as `\p{Alpha}`. All are listed in ["Properties accessible through \p{} and \P{}" in perluniprops](perluniprops#Properties-accessible-through-%5Cp%7B%7D-and-%5CP%7B%7D).
Both the `\p` counterparts always assume Unicode rules are in effect. On ASCII platforms, this means they assume that the code points from 128 to 255 are Latin-1, and that means that using them under locale rules is unwise unless the locale is guaranteed to be Latin-1 or UTF-8. In contrast, the POSIX character classes are useful under locale rules. They are affected by the actual rules in effect, as follows:
If the `/a` modifier, is in effect ... Each of the POSIX classes matches exactly the same as their ASCII-range counterparts.
otherwise ...
For code points above 255 ... The POSIX class matches the same as its Full-range counterpart.
For code points below 256 ...
if locale rules are in effect ... The POSIX class matches according to the locale, except:
`word` also includes the platform's native underscore character, no matter what the locale is.
`ascii` on platforms that don't have the POSIX `ascii` extension, this matches just the platform's native ASCII-range characters.
`blank` on platforms that don't have the POSIX `blank` extension, this matches just the platform's native tab and space characters.
if, instead, Unicode rules are in effect ... The POSIX class matches the same as the Full-range counterpart.
otherwise ... The POSIX class matches the same as the ASCII range counterpart.
Which rules apply are determined as described in ["Which character set modifier is in effect?" in perlre](perlre#Which-character-set-modifier-is-in-effect%3F).
#####
Negation of POSIX character classes
A Perl extension to the POSIX character class is the ability to negate it. This is done by prefixing the class name with a caret (`^`). Some examples:
```
POSIX ASCII-range Full-range backslash
Unicode Unicode sequence
-----------------------------------------------------
[[:^digit:]] \P{PosixDigit} \P{XPosixDigit} \D
[[:^space:]] \P{PosixSpace} \P{XPosixSpace}
\P{PerlSpace} \P{XPerlSpace} \S
[[:^word:]] \P{PerlWord} \P{XPosixWord} \W
```
The backslash sequence can mean either ASCII- or Full-range Unicode, depending on various factors as described in ["Which character set modifier is in effect?" in perlre](perlre#Which-character-set-modifier-is-in-effect%3F).
#####
[= =] and [. .]
Perl recognizes the POSIX character classes `[=class=]` and `[.class.]`, but does not (yet?) support them. Any attempt to use either construct raises an exception.
##### Examples
```
/[[:digit:]]/ # Matches a character that is a digit.
/[01[:lower:]]/ # Matches a character that is either a
# lowercase letter, or '0' or '1'.
/[[:digit:][:^xdigit:]]/ # Matches a character that can be anything
# except the letters 'a' to 'f' and 'A' to
# 'F'. This is because the main character
# class is composed of two POSIX character
# classes that are ORed together, one that
# matches any digit, and the other that
# matches anything that isn't a hex digit.
# The OR adds the digits, leaving only the
# letters 'a' to 'f' and 'A' to 'F' excluded.
```
####
Extended Bracketed Character Classes
This is a fancy bracketed character class that can be used for more readable and less error-prone classes, and to perform set operations, such as intersection. An example is
```
/(?[ \p{Thai} & \p{Digit} ])/
```
This will match all the digit characters that are in the Thai script.
This feature became available in Perl 5.18, as experimental; accepted in 5.36.
The rules used by [`use re 'strict`](re#%27strict%27-mode) apply to this construct.
We can extend the example above:
```
/(?[ ( \p{Thai} + \p{Lao} ) & \p{Digit} ])/
```
This matches digits that are in either the Thai or Laotian scripts.
Notice the white space in these examples. This construct always has the `/xx` modifier turned on within it.
The available binary operators are:
```
& intersection
+ union
| another name for '+', hence means union
- subtraction (the result matches the set consisting of those
code points matched by the first operand, excluding any that
are also matched by the second operand)
^ symmetric difference (the union minus the intersection). This
is like an exclusive or, in that the result is the set of code
points that are matched by either, but not both, of the
operands.
```
There is one unary operator:
```
! complement
```
All the binary operators left associate; `"&"` is higher precedence than the others, which all have equal precedence. The unary operator right associates, and has highest precedence. Thus this follows the normal Perl precedence rules for logical operators. Use parentheses to override the default precedence and associativity.
The main restriction is that everything is a metacharacter. Thus, you cannot refer to single characters by doing something like this:
```
/(?[ a + b ])/ # Syntax error!
```
The easiest way to specify an individual typable character is to enclose it in brackets:
```
/(?[ [a] + [b] ])/
```
(This is the same thing as `[ab]`.) You could also have said the equivalent:
```
/(?[[ a b ]])/
```
(You can, of course, specify single characters by using, `\x{...}`, `\N{...}`, etc.)
This last example shows the use of this construct to specify an ordinary bracketed character class without additional set operations. Note the white space within it. This is allowed because `/xx` is automatically turned on within this construct.
All the other escapes accepted by normal bracketed character classes are accepted here as well.
Because this construct compiles under [`use re 'strict`](re#%27strict%27-mode), unrecognized escapes that generate warnings in normal classes are fatal errors here, as well as all other warnings from these class elements, as well as some practices that don't currently warn outside `re 'strict'`. For example you cannot say
```
/(?[ [ \xF ] ])/ # Syntax error!
```
You have to have two hex digits after a braceless `\x` (use a leading zero to make two). These restrictions are to lower the incidence of typos causing the class to not match what you thought it would.
If a regular bracketed character class contains a `\p{}` or `\P{}` and is matched against a non-Unicode code point, a warning may be raised, as the result is not Unicode-defined. No such warning will come when using this extended form.
The final difference between regular bracketed character classes and these, is that it is not possible to get these to match a multi-character fold. Thus,
```
/(?[ [\xDF] ])/iu
```
does not match the string `ss`.
You don't have to enclose POSIX class names inside double brackets, hence both of the following work:
```
/(?[ [:word:] - [:lower:] ])/
/(?[ [[:word:]] - [[:lower:]] ])/
```
Any contained POSIX character classes, including things like `\w` and `\D` respect the `/a` (and `/aa`) modifiers.
Note that `(?[ ])` is a regex-compile-time construct. Any attempt to use something which isn't knowable at the time the containing regular expression is compiled is a fatal error. In practice, this means just three limitations:
1. When compiled within the scope of `use locale` (or the `/l` regex modifier), this construct assumes that the execution-time locale will be a UTF-8 one, and the generated pattern always uses Unicode rules. What gets matched or not thus isn't dependent on the actual runtime locale, so tainting is not enabled. But a `locale` category warning is raised if the runtime locale turns out to not be UTF-8.
2. Any [user-defined property](perlunicode#User-Defined-Character-Properties) used must be already defined by the time the regular expression is compiled (but note that this construct can be used instead of such properties).
3. A regular expression that otherwise would compile using `/d` rules, and which uses this construct will instead use `/u`. Thus this construct tells Perl that you don't want `/d` rules for the entire regular expression containing it.
Note that skipping white space applies only to the interior of this construct. There must not be any space between any of the characters that form the initial `(?[`. Nor may there be space between the closing `])` characters.
Just as in all regular expressions, the pattern can be built up by including variables that are interpolated at regex compilation time. But currently each such sub-component should be an already-compiled extended bracketed character class.
```
my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
...
qr/(?[ \p{Digit} & $thai_or_lao ])/;
```
If you interpolate something else, the pattern may still compile (or it may die), but if it compiles, it very well may not behave as you would expect:
```
my $thai_or_lao = '\p{Thai} + \p{Lao}';
qr/(?[ \p{Digit} & $thai_or_lao ])/;
```
compiles to
```
qr/(?[ \p{Digit} & \p{Thai} + \p{Lao} ])/;
```
This does not have the effect that someone reading the source code would likely expect, as the intersection applies just to `\p{Thai}`, excluding the Laotian.
Due to the way that Perl parses things, your parentheses and brackets may need to be balanced, even including comments. If you run into any examples, please submit them to <https://github.com/Perl/perl5/issues>, so that we can have a concrete example for this man page.
| programming_docs |
perl perlrebackslash perlrebackslash
===============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [The backslash](#The-backslash)
+ [All the sequences and escapes](#All-the-sequences-and-escapes)
+ [Character Escapes](#Character-Escapes)
- [Fixed characters](#Fixed-characters)
* [Example](#Example)
- [Control characters](#Control-characters)
* [Example](#Example1)
- [Named or numbered characters and character sequences](#Named-or-numbered-characters-and-character-sequences)
* [Example](#Example2)
- [Octal escapes](#Octal-escapes)
* [Examples (assuming an ASCII platform)](#Examples-(assuming-an-ASCII-platform))
* [Disambiguation rules between old-style octal escapes and backreferences](#Disambiguation-rules-between-old-style-octal-escapes-and-backreferences)
- [Hexadecimal escapes](#Hexadecimal-escapes)
* [Examples (assuming an ASCII platform)](#Examples-(assuming-an-ASCII-platform)1)
+ [Modifiers](#Modifiers)
- [Examples](#Examples2)
+ [Character classes](#Character-classes)
- [Unicode classes](#Unicode-classes)
+ [Referencing](#Referencing)
- [Absolute referencing](#Absolute-referencing)
* [Examples](#Examples3)
- [Relative referencing](#Relative-referencing)
* [Examples](#Examples4)
- [Named referencing](#Named-referencing)
* [Examples](#Examples5)
+ [Assertions](#Assertions)
- [Examples](#Examples6)
+ [Misc](#Misc)
- [Examples](#Examples7)
NAME
----
perlrebackslash - Perl Regular Expression Backslash Sequences and Escapes
DESCRIPTION
-----------
The top level documentation about Perl regular expressions is found in <perlre>.
This document describes all backslash and escape sequences. After explaining the role of the backslash, it lists all the sequences that have a special meaning in Perl regular expressions (in alphabetical order), then describes each of them.
Most sequences are described in detail in different documents; the primary purpose of this document is to have a quick reference guide describing all backslash and escape sequences.
###
The backslash
In a regular expression, the backslash can perform one of two tasks: it either takes away the special meaning of the character following it (for instance, `\|` matches a vertical bar, it's not an alternation), or it is the start of a backslash or escape sequence.
The rules determining what it is are quite simple: if the character following the backslash is an ASCII punctuation (non-word) character (that is, anything that is not a letter, digit, or underscore), then the backslash just takes away any special meaning of the character following it.
If the character following the backslash is an ASCII letter or an ASCII digit, then the sequence may be special; if so, it's listed below. A few letters have not been used yet, so escaping them with a backslash doesn't change them to be special. A future version of Perl may assign a special meaning to them, so if you have warnings turned on, Perl issues a warning if you use such a sequence. [1].
It is however guaranteed that backslash or escape sequences never have a punctuation character following the backslash, not now, and not in a future version of Perl 5. So it is safe to put a backslash in front of a non-word character.
Note that the backslash itself is special; if you want to match a backslash, you have to escape the backslash with a backslash: `/\\/` matches a single backslash.
[1] There is one exception. If you use an alphanumeric character as the delimiter of your pattern (which you probably shouldn't do for readability reasons), you have to escape the delimiter if you want to match it. Perl won't warn then. See also ["Gory details of parsing quoted constructs" in perlop](perlop#Gory-details-of-parsing-quoted-constructs).
###
All the sequences and escapes
Those not usable within a bracketed character class (like `[\da-z]`) are marked as `Not in [].`
```
\000 Octal escape sequence. See also \o{}.
\1 Absolute backreference. Not in [].
\a Alarm or bell.
\A Beginning of string. Not in [].
\b{}, \b Boundary. (\b is a backspace in []).
\B{}, \B Not a boundary. Not in [].
\cX Control-X.
\d Match any digit character.
\D Match any character that isn't a digit.
\e Escape character.
\E Turn off \Q, \L and \U processing. Not in [].
\f Form feed.
\F Foldcase till \E. Not in [].
\g{}, \g1 Named, absolute or relative backreference.
Not in [].
\G Pos assertion. Not in [].
\h Match any horizontal whitespace character.
\H Match any character that isn't horizontal whitespace.
\k{}, \k<>, \k'' Named backreference. Not in [].
\K Keep the stuff left of \K. Not in [].
\l Lowercase next character. Not in [].
\L Lowercase till \E. Not in [].
\n (Logical) newline character.
\N Match any character but newline. Not in [].
\N{} Named or numbered (Unicode) character or sequence.
\o{} Octal escape sequence.
\p{}, \pP Match any character with the given Unicode property.
\P{}, \PP Match any character without the given property.
\Q Quote (disable) pattern metacharacters till \E. Not
in [].
\r Return character.
\R Generic new line. Not in [].
\s Match any whitespace character.
\S Match any character that isn't a whitespace.
\t Tab character.
\u Titlecase next character. Not in [].
\U Uppercase till \E. Not in [].
\v Match any vertical whitespace character.
\V Match any character that isn't vertical whitespace
\w Match any word character.
\W Match any character that isn't a word character.
\x{}, \x00 Hexadecimal escape sequence.
\X Unicode "extended grapheme cluster". Not in [].
\z End of string. Not in [].
\Z End of string. Not in [].
```
###
Character Escapes
####
Fixed characters
A handful of characters have a dedicated *character escape*. The following table shows them, along with their ASCII code points (in decimal and hex), their ASCII name, the control escape on ASCII platforms and a short description. (For EBCDIC platforms, see ["OPERATOR DIFFERENCES" in perlebcdic](perlebcdic#OPERATOR-DIFFERENCES).)
```
Seq. Code Point ASCII Cntrl Description.
Dec Hex
\a 7 07 BEL \cG alarm or bell
\b 8 08 BS \cH backspace [1]
\e 27 1B ESC \c[ escape character
\f 12 0C FF \cL form feed
\n 10 0A LF \cJ line feed [2]
\r 13 0D CR \cM carriage return
\t 9 09 TAB \cI tab
```
[1] `\b` is the backspace character only inside a character class. Outside a character class, `\b` alone is a word-character/non-word-character boundary, and `\b{}` is some other type of boundary.
[2] `\n` matches a logical newline. Perl converts between `\n` and your OS's native newline character when reading from or writing to text files.
##### Example
```
$str =~ /\t/; # Matches if $str contains a (horizontal) tab.
```
####
Control characters
`\c` is used to denote a control character; the character following `\c` determines the value of the construct. For example the value of `\cA` is `chr(1)`, and the value of `\cb` is `chr(2)`, etc. The gory details are in ["Regexp Quote-Like Operators" in perlop](perlop#Regexp-Quote-Like-Operators). A complete list of what `chr(1)`, etc. means for ASCII and EBCDIC platforms is in ["OPERATOR DIFFERENCES" in perlebcdic](perlebcdic#OPERATOR-DIFFERENCES).
Note that `\c\` alone at the end of a regular expression (or doubled-quoted string) is not valid. The backslash must be followed by another character. That is, `\c\*X*` means `chr(28) . '*X*'` for all characters *X*.
To write platform-independent code, you must use `\N{*NAME*}` instead, like `\N{ESCAPE}` or `\N{U+001B}`, see <charnames>.
Mnemonic: *c*ontrol character.
##### Example
```
$str =~ /\cK/; # Matches if $str contains a vertical tab (control-K).
```
####
Named or numbered characters and character sequences
Unicode characters have a Unicode name and numeric code point (ordinal) value. Use the `\N{}` construct to specify a character by either of these values. Certain sequences of characters also have names.
To specify by name, the name of the character or character sequence goes between the curly braces.
To specify a character by Unicode code point, use the form `\N{U+*code point*}`, where *code point* is a number in hexadecimal that gives the code point that Unicode has assigned to the desired character. It is customary but not required to use leading zeros to pad the number to 4 digits. Thus `\N{U+0041}` means `LATIN CAPITAL LETTER A`, and you will rarely see it written without the two leading zeros. `\N{U+0041}` means "A" even on EBCDIC machines (where the ordinal value of "A" is not 0x41).
Blanks may freely be inserted adjacent to but within the braces enclosing the name or code point. So `\N{ U+0041 }` is perfectly legal.
It is even possible to give your own names to characters and character sequences by using the <charnames> module. These custom names are lexically scoped, and so a given code point may have different names in different scopes. The name used is what is in effect at the time the `\N{}` is expanded. For patterns in double-quotish context, that means at the time the pattern is parsed. But for patterns that are delimitted by single quotes, the expansion is deferred until pattern compilation time, which may very well have a different `charnames` translator in effect.
(There is an expanded internal form that you may see in debug output: `\N{U+*code point*.*code point*...}`. The `...` means any number of these *code point*s separated by dots. This represents the sequence formed by the characters. This is an internal form only, subject to change, and you should not try to use it yourself.)
Mnemonic: *N*amed character.
Note that a character or character sequence expressed as a named or numbered character is considered a character without special meaning by the regex engine, and will match "as is".
##### Example
```
$str =~ /\N{THAI CHARACTER SO SO}/; # Matches the Thai SO SO character
use charnames 'Cyrillic'; # Loads Cyrillic names.
$str =~ /\N{ZHE}\N{KA}/; # Match "ZHE" followed by "KA".
```
####
Octal escapes
There are two forms of octal escapes. Each is used to specify a character by its code point specified in base 8.
One form, available starting in Perl 5.14 looks like `\o{...}`, where the dots represent one or more octal digits. It can be used for any Unicode character.
It was introduced to avoid the potential problems with the other form, available in all Perls. That form consists of a backslash followed by three octal digits. One problem with this form is that it can look exactly like an old-style backreference (see ["Disambiguation rules between old-style octal escapes and backreferences"](#Disambiguation-rules-between-old-style-octal-escapes-and-backreferences) below.) You can avoid this by making the first of the three digits always a zero, but that makes \077 the largest code point specifiable.
In some contexts, a backslash followed by two or even one octal digits may be interpreted as an octal escape, sometimes with a warning, and because of some bugs, sometimes with surprising results. Also, if you are creating a regex out of smaller snippets concatenated together, and you use fewer than three digits, the beginning of one snippet may be interpreted as adding digits to the ending of the snippet before it. See ["Absolute referencing"](#Absolute-referencing) for more discussion and examples of the snippet problem.
Note that a character expressed as an octal escape is considered a character without special meaning by the regex engine, and will match "as is".
To summarize, the `\o{}` form is always safe to use, and the other form is safe to use for code points through \077 when you use exactly three digits to specify them.
Mnemonic: *0*ctal or *o*ctal.
#####
Examples (assuming an ASCII platform)
```
$str = "Perl";
$str =~ /\o{120}/; # Match, "\120" is "P".
$str =~ /\120/; # Same.
$str =~ /\o{120}+/; # Match, "\120" is "P",
# it's repeated at least once.
$str =~ /\120+/; # Same.
$str =~ /P\053/; # No match, "\053" is "+" and taken literally.
/\o{23073}/ # Black foreground, white background smiling face.
/\o{4801234567}/ # Raises a warning, and yields chr(4).
/\o{ 400}/ # LATIN CAPITAL LETTER A WITH MACRON
/\o{ 400 }/ # Same. These show blanks are allowed adjacent to
# the braces
```
#####
Disambiguation rules between old-style octal escapes and backreferences
Octal escapes of the `\000` form outside of bracketed character classes potentially clash with old-style backreferences (see ["Absolute referencing"](#Absolute-referencing) below). They both consist of a backslash followed by numbers. So Perl has to use heuristics to determine whether it is a backreference or an octal escape. Perl uses the following rules to disambiguate:
1. If the backslash is followed by a single digit, it's a backreference.
2. If the first digit following the backslash is a 0, it's an octal escape.
3. If the number following the backslash is N (in decimal), and Perl already has seen N capture groups, Perl considers this a backreference. Otherwise, it considers it an octal escape. If N has more than three digits, Perl takes only the first three for the octal escape; the rest are matched as is.
```
my $pat = "(" x 999;
$pat .= "a";
$pat .= ")" x 999;
/^($pat)\1000$/; # Matches 'aa'; there are 1000 capture groups.
/^$pat\1000$/; # Matches 'a@0'; there are 999 capture groups
# and \1000 is seen as \100 (a '@') and a '0'.
```
You can force a backreference interpretation always by using the `\g{...}` form. You can the force an octal interpretation always by using the `\o{...}` form, or for numbers up through \077 (= 63 decimal), by using three digits, beginning with a "0".
####
Hexadecimal escapes
Like octal escapes, there are two forms of hexadecimal escapes, but both start with the sequence `\x`. This is followed by either exactly two hexadecimal digits forming a number, or a hexadecimal number of arbitrary length surrounded by curly braces. The hexadecimal number is the code point of the character you want to express.
Note that a character expressed as one of these escapes is considered a character without special meaning by the regex engine, and will match "as is".
Mnemonic: he*x*adecimal.
#####
Examples (assuming an ASCII platform)
```
$str = "Perl";
$str =~ /\x50/; # Match, "\x50" is "P".
$str =~ /\x50+/; # Match, "\x50" is "P", it is repeated at least once
$str =~ /P\x2B/; # No match, "\x2B" is "+" and taken literally.
/\x{2603}\x{2602}/ # Snowman with an umbrella.
# The Unicode character 2603 is a snowman,
# the Unicode character 2602 is an umbrella.
/\x{263B}/ # Black smiling face.
/\x{263b}/ # Same, the hex digits A - F are case insensitive.
/\x{ 263b }/ # Same, showing optional blanks adjacent to the
# braces
```
### Modifiers
A number of backslash sequences have to do with changing the character, or characters following them. `\l` will lowercase the character following it, while `\u` will uppercase (or, more accurately, titlecase) the character following it. They provide functionality similar to the functions `lcfirst` and `ucfirst`.
To uppercase or lowercase several characters, one might want to use `\L` or `\U`, which will lowercase/uppercase all characters following them, until either the end of the pattern or the next occurrence of `\E`, whichever comes first. They provide functionality similar to what the functions `lc` and `uc` provide.
`\Q` is used to quote (disable) pattern metacharacters, up to the next `\E` or the end of the pattern. `\Q` adds a backslash to any character that could have special meaning to Perl. In the ASCII range, it quotes every character that isn't a letter, digit, or underscore. See ["quotemeta" in perlfunc](perlfunc#quotemeta) for details on what gets quoted for non-ASCII code points. Using this ensures that any character between `\Q` and `\E` will be matched literally, not interpreted as a metacharacter by the regex engine.
`\F` can be used to casefold all characters following, up to the next `\E` or the end of the pattern. It provides the functionality similar to the `fc` function.
Mnemonic: *L*owercase, *U*ppercase, *F*old-case, *Q*uotemeta, *E*nd.
##### Examples
```
$sid = "sid";
$greg = "GrEg";
$miranda = "(Miranda)";
$str =~ /\u$sid/; # Matches 'Sid'
$str =~ /\L$greg/; # Matches 'greg'
$str =~ /\Q$miranda\E/; # Matches '(Miranda)', as if the pattern
# had been written as /\(Miranda\)/
```
###
Character classes
Perl regular expressions have a large range of character classes. Some of the character classes are written as a backslash sequence. We will briefly discuss those here; full details of character classes can be found in <perlrecharclass>.
`\w` is a character class that matches any single *word* character (letters, digits, Unicode marks, and connector punctuation (like the underscore)). `\d` is a character class that matches any decimal digit, while the character class `\s` matches any whitespace character. New in perl 5.10.0 are the classes `\h` and `\v` which match horizontal and vertical whitespace characters.
The exact set of characters matched by `\d`, `\s`, and `\w` varies depending on various pragma and regular expression modifiers. It is possible to restrict the match to the ASCII range by using the `/a` regular expression modifier. See <perlrecharclass>.
The uppercase variants (`\W`, `\D`, `\S`, `\H`, and `\V`) are character classes that match, respectively, any character that isn't a word character, digit, whitespace, horizontal whitespace, or vertical whitespace.
Mnemonics: *w*ord, *d*igit, *s*pace, *h*orizontal, *v*ertical.
####
Unicode classes
`\pP` (where `P` is a single letter) and `\p{Property}` are used to match a character that matches the given Unicode property; properties include things like "letter", or "thai character". Capitalizing the sequence to `\PP` and `\P{Property}` make the sequence match a character that doesn't match the given Unicode property. For more details, see ["Backslash sequences" in perlrecharclass](perlrecharclass#Backslash-sequences) and ["Unicode Character Properties" in perlunicode](perlunicode#Unicode-Character-Properties).
Mnemonic: *p*roperty.
### Referencing
If capturing parenthesis are used in a regular expression, we can refer to the part of the source string that was matched, and match exactly the same thing. There are three ways of referring to such *backreference*: absolutely, relatively, and by name.
####
Absolute referencing
Either `\g*N*` (starting in Perl 5.10.0), or `\*N*` (old-style) where *N* is a positive (unsigned) decimal number of any length is an absolute reference to a capturing group.
*N* refers to the Nth set of parentheses, so `\g*N*` refers to whatever has been matched by that set of parentheses. Thus `\g1` refers to the first capture group in the regex.
The `\g*N*` form can be equivalently written as `\g{*N*}` which avoids ambiguity when building a regex by concatenating shorter strings. Otherwise if you had a regex `qr/$a$b/`, and `$a` contained `"\g1"`, and `$b` contained `"37"`, you would get `/\g137/` which is probably not what you intended.
In the `\*N*` form, *N* must not begin with a "0", and there must be at least *N* capturing groups, or else *N* is considered an octal escape (but something like `\18` is the same as `\0018`; that is, the octal escape `"\001"` followed by a literal digit `"8"`).
Mnemonic: *g*roup.
##### Examples
```
/(\w+) \g1/; # Finds a duplicated word, (e.g. "cat cat").
/(\w+) \1/; # Same thing; written old-style.
/(\w+) \g{1}/; # Same, using the safer braced notation
/(\w+) \g{ 1 }/;# Same, showing optional blanks adjacent to the braces
/(.)(.)\g2\g1/; # Match a four letter palindrome (e.g. "ABBA").
```
####
Relative referencing
`\g-*N*` (starting in Perl 5.10.0) is used for relative addressing. (It can be written as `\g{-*N*}`.) It refers to the *N*th group before the `\g{-*N*}`.
The big advantage of this form is that it makes it much easier to write patterns with references that can be interpolated in larger patterns, even if the larger pattern also contains capture groups.
##### Examples
```
/(A) # Group 1
( # Group 2
(B) # Group 3
\g{-1} # Refers to group 3 (B)
\g{-3} # Refers to group 1 (A)
\g{ -3 } # Same, showing optional blanks adjacent to the braces
)
/x; # Matches "ABBA".
my $qr = qr /(.)(.)\g{-2}\g{-1}/; # Matches 'abab', 'cdcd', etc.
/$qr$qr/ # Matches 'ababcdcd'.
```
####
Named referencing
`\g{*name*}` (starting in Perl 5.10.0) can be used to back refer to a named capture group, dispensing completely with having to think about capture buffer positions.
To be compatible with .Net regular expressions, `\g{name}` may also be written as `\k{name}`, `\k<name>` or `\k'name'`.
To prevent any ambiguity, *name* must not start with a digit nor contain a hyphen.
##### Examples
```
/(?<word>\w+) \g{word}/ # Finds duplicated word, (e.g. "cat cat")
/(?<word>\w+) \k{word}/ # Same.
/(?<word>\w+) \g{ word }/ # Same, showing optional blanks adjacent to
# the braces
/(?<word>\w+) \k{ word }/ # Same.
/(?<word>\w+) \k<word>/ # Same. There are no braces, so no blanks
# are permitted
/(?<letter1>.)(?<letter2>.)\g{letter2}\g{letter1}/
# Match a four letter palindrome (e.g.
# "ABBA")
```
### Assertions
Assertions are conditions that have to be true; they don't actually match parts of the substring. There are six assertions that are written as backslash sequences.
\A `\A` only matches at the beginning of the string. If the `/m` modifier isn't used, then `/\A/` is equivalent to `/^/`. However, if the `/m` modifier is used, then `/^/` matches internal newlines, but the meaning of `/\A/` isn't changed by the `/m` modifier. `\A` matches at the beginning of the string regardless whether the `/m` modifier is used.
\z, \Z `\z` and `\Z` match at the end of the string. If the `/m` modifier isn't used, then `/\Z/` is equivalent to `/$/`; that is, it matches at the end of the string, or one before the newline at the end of the string. If the `/m` modifier is used, then `/$/` matches at internal newlines, but the meaning of `/\Z/` isn't changed by the `/m` modifier. `\Z` matches at the end of the string (or just before a trailing newline) regardless whether the `/m` modifier is used.
`\z` is just like `\Z`, except that it does not match before a trailing newline. `\z` matches at the end of the string only, regardless of the modifiers used, and not just before a newline. It is how to anchor the match to the true end of the string under all conditions.
\G `\G` is usually used only in combination with the `/g` modifier. If the `/g` modifier is used and the match is done in scalar context, Perl remembers where in the source string the last match ended, and the next time, it will start the match from where it ended the previous time.
`\G` matches the point where the previous match on that string ended, or the beginning of that string if there was no previous match.
Mnemonic: *G*lobal.
\b{}, \b, \B{}, \B `\b{...}`, available starting in v5.22, matches a boundary (between two characters, or before the first character of the string, or after the final character of the string) based on the Unicode rules for the boundary type specified inside the braces. The boundary types are given a few paragraphs below. `\B{...}` matches at any place between characters where `\b{...}` of the same type doesn't match.
`\b` when not immediately followed by a `"{"` is available in all Perls. It matches at any place between a word (something matched by `\w`) and a non-word character (`\W`); `\B` when not immediately followed by a `"{"` matches at any place between characters where `\b` doesn't match. To get better word matching of natural language text, see ["\b{wb}"](#%5Cb%7Bwb%7D) below.
`\b` and `\B` assume there's a non-word character before the beginning and after the end of the source string; so `\b` will match at the beginning (or end) of the source string if the source string begins (or ends) with a word character. Otherwise, `\B` will match.
Do not use something like `\b=head\d\b` and expect it to match the beginning of a line. It can't, because for there to be a boundary before the non-word "=", there must be a word character immediately previous. All plain `\b` and `\B` boundary determinations look for word characters alone, not for non-word characters nor for string ends. It may help to understand how `\b` and `\B` work by equating them as follows:
```
\b really means (?:(?<=\w)(?!\w)|(?<!\w)(?=\w))
\B really means (?:(?<=\w)(?=\w)|(?<!\w)(?!\w))
```
In contrast, `\b{...}` and `\B{...}` may or may not match at the beginning and end of the line, depending on the boundary type. These implement the Unicode default boundaries, specified in <https://www.unicode.org/reports/tr14/> and <https://www.unicode.org/reports/tr29/>. The boundary types are:
`\b{gcb}` or `\b{g}`
This matches a Unicode "Grapheme Cluster Boundary". (Actually Perl always uses the improved "extended" grapheme cluster"). These are explained below under `["\X"](#%5CX)`. In fact, `\X` is another way to get the same functionality. It is equivalent to `/.+?\b{gcb}/`. Use whichever is most convenient for your situation.
`\b{lb}`
This matches according to the default Unicode Line Breaking Algorithm (<https://www.unicode.org/reports/tr14/>), as customized in that document ([Example 7 of revision 35](https://www.unicode.org/reports/tr14/tr14-35.html#Example7)) for better handling of numeric expressions.
This is suitable for many purposes, but the <Unicode::LineBreak> module is available on CPAN that provides many more features, including customization.
`\b{sb}`
This matches a Unicode "Sentence Boundary". This is an aid to parsing natural language sentences. It gives good, but imperfect results. For example, it thinks that "Mr. Smith" is two sentences. More details are at <https://www.unicode.org/reports/tr29/>. Note also that it thinks that anything matching ["\R"](#%5CR) (except form feed and vertical tab) is a sentence boundary. `\b{sb}` works with text designed for word-processors which wrap lines automatically for display, but hard-coded line boundaries are considered to be essentially the ends of text blocks (paragraphs really), and hence the ends of sentences. `\b{sb}` doesn't do well with text containing embedded newlines, like the source text of the document you are reading. Such text needs to be preprocessed to get rid of the line separators before looking for sentence boundaries. Some people view this as a bug in the Unicode standard, and this behavior is quite subject to change in future Perl versions.
`\b{wb}`
This matches a Unicode "Word Boundary", but tailored to Perl expectations. This gives better (though not perfect) results for natural language processing than plain `\b` (without braces) does. For example, it understands that apostrophes can be in the middle of words and that parentheses aren't (see the examples below). More details are at <https://www.unicode.org/reports/tr29/>.
The current Unicode definition of a Word Boundary matches between every white space character. Perl tailors this, starting in version 5.24, to generally not break up spans of white space, just as plain `\b` has always functioned. This allows `\b{wb}` to be a drop-in replacement for `\b`, but with generally better results for natural language processing. (The exception to this tailoring is when a span of white space is immediately followed by something like U+0303, COMBINING TILDE. If the final space character in the span is a horizontal white space, it is broken out so that it attaches instead to the combining character. To be precise, if a span of white space that ends in a horizontal space has the character immediately following it have any of the Word Boundary property values "Extend", "Format" or "ZWJ", the boundary between the final horizontal space character and the rest of the span matches `\b{wb}`. In all other cases the boundary between two white space characters matches `\B{wb}`.)
It is important to realize when you use these Unicode boundaries, that you are taking a risk that a future version of Perl which contains a later version of the Unicode Standard will not work precisely the same way as it did when your code was written. These rules are not considered stable and have been somewhat more subject to change than the rest of the Standard. Unicode reserves the right to change them at will, and Perl reserves the right to update its implementation to Unicode's new rules. In the past, some changes have been because new characters have been added to the Standard which have different characteristics than all previous characters, so new rules are formulated for handling them. These should not cause any backward compatibility issues. But some changes have changed the treatment of existing characters because the Unicode Technical Committee has decided that the change is warranted for whatever reason. This could be to fix a bug, or because they think better results are obtained with the new rule.
It is also important to realize that these are default boundary definitions, and that implementations may wish to tailor the results for particular purposes and locales. For example, some languages, such as Japanese and Thai, require dictionary lookup to accurately determine word boundaries.
Mnemonic: *b*oundary.
##### Examples
```
"cat" =~ /\Acat/; # Match.
"cat" =~ /cat\Z/; # Match.
"cat\n" =~ /cat\Z/; # Match.
"cat\n" =~ /cat\z/; # No match.
"cat" =~ /\bcat\b/; # Matches.
"cats" =~ /\bcat\b/; # No match.
"cat" =~ /\bcat\B/; # No match.
"cats" =~ /\bcat\B/; # Match.
while ("cat dog" =~ /(\w+)/g) {
print $1; # Prints 'catdog'
}
while ("cat dog" =~ /\G(\w+)/g) {
print $1; # Prints 'cat'
}
my $s = "He said, \"Is pi 3.14? (I'm not sure).\"";
print join("|", $s =~ m/ ( .+? \b ) /xg), "\n";
print join("|", $s =~ m/ ( .+? \b{wb} ) /xg), "\n";
prints
He| |said|, "|Is| |pi| |3|.|14|? (|I|'|m| |not| |sure
He| |said|,| |"|Is| |pi| |3.14|?| |(|I'm| |not| |sure|)|.|"
```
### Misc
Here we document the backslash sequences that don't fall in one of the categories above. These are:
\K This appeared in perl 5.10.0. Anything matched left of `\K` is not included in `$&`, and will not be replaced if the pattern is used in a substitution. This lets you write `s/PAT1 \K PAT2/REPL/x` instead of `s/(PAT1) PAT2/${1}REPL/x` or `s/(?<=PAT1) PAT2/REPL/x`.
Mnemonic: *K*eep.
\N This feature, available starting in v5.12, matches any character that is **not** a newline. It is a short-hand for writing `[^\n]`, and is identical to the `.` metasymbol, except under the `/s` flag, which changes the meaning of `.`, but not `\N`.
Note that `\N{...}` can mean a [named or numbered character](#Named-or-numbered-characters-and-character-sequences) .
Mnemonic: Complement of *\n*.
\R `\R` matches a *generic newline*; that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by `\v` (vertical whitespace), and the multi character sequence `"\x0D\x0A"` (carriage return followed by a line feed, sometimes called the network newline; it's the end of line sequence used in Microsoft text files opened in binary mode). `\R` is equivalent to `(?>\x0D\x0A|\v)`. (The reason it doesn't backtrack is that the sequence is considered inseparable. That means that
```
"\x0D\x0A" =~ /^\R\x0A$/ # No match
```
fails, because the `\R` matches the entire string, and won't backtrack to match just the `"\x0D"`.) Since `\R` can match a sequence of more than one character, it cannot be put inside a bracketed character class; `/[\R]/` is an error; use `\v` instead. `\R` was introduced in perl 5.10.0.
Note that this does not respect any locale that might be in effect; it matches according to the platform's native character set.
Mnemonic: none really. `\R` was picked because PCRE already uses `\R`, and more importantly because Unicode recommends such a regular expression metacharacter, and suggests `\R` as its notation.
\X This matches a Unicode *extended grapheme cluster*.
`\X` matches quite well what normal (non-Unicode-programmer) usage would consider a single character. As an example, consider a G with some sort of diacritic mark, such as an arrow. There is no such single character in Unicode, but one can be composed by using a G followed by a Unicode "COMBINING UPWARDS ARROW BELOW", and would be displayed by Unicode-aware software as if it were a single character.
The match is greedy and non-backtracking, so that the cluster is never broken up into smaller components.
See also [`\b{gcb}`](#%5Cb%7B%7D%2C-%5Cb%2C-%5CB%7B%7D%2C-%5CB).
Mnemonic: e*X*tended Unicode character.
##### Examples
```
$str =~ s/foo\Kbar/baz/g; # Change any 'bar' following a 'foo' to 'baz'
$str =~ s/(.)\K\g1//g; # Delete duplicated characters.
"\n" =~ /^\R$/; # Match, \n is a generic newline.
"\r" =~ /^\R$/; # Match, \r is a generic newline.
"\r\n" =~ /^\R$/; # Match, \r\n is a generic newline.
"P\x{307}" =~ /^\X$/ # \X matches a P with a dot above.
```
| programming_docs |
perl perlvos perlvos
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [BUILDING PERL FOR OPENVOS](#BUILDING-PERL-FOR-OPENVOS)
* [INSTALLING PERL IN OPENVOS](#INSTALLING-PERL-IN-OPENVOS)
* [USING PERL IN OPENVOS](#USING-PERL-IN-OPENVOS)
+ [Restrictions of Perl on OpenVOS](#Restrictions-of-Perl-on-OpenVOS)
* [TEST STATUS](#TEST-STATUS)
* [SUPPORT STATUS](#SUPPORT-STATUS)
* [AUTHOR](#AUTHOR)
* [LAST UPDATE](#LAST-UPDATE)
NAME
----
perlvos - Perl for Stratus OpenVOS
SYNOPSIS
--------
This file contains notes for building perl on the Stratus OpenVOS operating system. Perl is a scripting or macro language that is popular on many systems. See [perlbook](https://perldoc.perl.org/5.36.0/perlbook) for a number of good books on Perl.
These are instructions for building Perl from source. This version of Perl requires the dynamic linking support that is found in OpenVOS Release 17.1 and thus is not supported on OpenVOS Release 17.0 or earlier releases.
If you are running VOS Release 14.4.1 or later, you can obtain a pre-compiled, supported copy of perl by purchasing the GNU Tools product from Stratus Technologies.
BUILDING PERL FOR OPENVOS
--------------------------
To build perl from its source code on the Stratus V Series platform you must have OpenVOS Release 17.1.0 or later, GNU Tools Release 3.5 or later, and the C/POSIX Runtime Libraries.
Follow the normal instructions for building perl; e.g, enter bash, run the Configure script, then use "gmake" to build perl.
INSTALLING PERL IN OPENVOS
---------------------------
1. After you have built perl using the Configure script, ensure that you have modify and default write permission to `>system>ported` and all subdirectories. Then type
```
gmake install
```
2. While there are currently no architecture-specific extensions or modules distributed with perl, the following directories can be used to hold such files (replace the string VERSION by the appropriate version number):
```
>system>ported>lib>perl5>VERSION>i786
```
3. Site-specific perl extensions and modules can be installed in one of two places. Put architecture-independent files into:
```
>system>ported>lib>perl5>site_perl>VERSION
```
Put site-specific architecture-dependent files into one of the following directories:
```
>system>ported>lib>perl5>site_perl>VERSION>i786
```
4. You can examine the @INC variable from within a perl program to see the order in which Perl searches these directories.
USING PERL IN OPENVOS
----------------------
###
Restrictions of Perl on OpenVOS
This port of Perl version 5 prefers Unix-style, slash-separated pathnames over OpenVOS-style greater-than-separated pathnames. OpenVOS-style pathnames should work in most contexts, but if you have trouble, replace all greater-than characters by slash characters. Because the slash character is used as a pathname delimiter, Perl cannot process OpenVOS pathnames containing a slash character in a directory or file name; these must be renamed.
This port of Perl also uses Unix-epoch date values internally. As long as you are dealing with ASCII character string representations of dates, this should not be an issue. The supported epoch is January 1, 1980 to January 17, 2038.
See the file pod/perlport.pod for more information about the OpenVOS port of Perl.
TEST STATUS
------------
A number of the perl self-tests fails for various reasons; generally these are minor and due to subtle differences between common POSIX-based environments and the OpenVOS POSIX environment. Ensure that you conduct sufficient testing of your code to guarantee that it works properly in the OpenVOS environment.
SUPPORT STATUS
---------------
I'm offering this port "as is". You can ask me questions, but I can't guarantee I'll be able to answer them. There are some excellent books available on the Perl language; consult a book seller.
If you want a supported version of perl for OpenVOS, purchase the OpenVOS GNU Tools product from Stratus Technologies, along with a support contract (or from anyone else who will sell you support).
AUTHOR
------
Paul Green ([email protected])
LAST UPDATE
------------
February 28, 2013
perl autodie autodie
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXCEPTIONS](#EXCEPTIONS)
* [CATEGORIES](#CATEGORIES)
* [FUNCTION SPECIFIC NOTES](#FUNCTION-SPECIFIC-NOTES)
+ [print](#print)
+ [flock](#flock)
+ [system/exec](#system/exec)
* [GOTCHAS](#GOTCHAS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [Tips and Tricks](#Tips-and-Tricks)
+ [Importing autodie into another namespace than "caller"](#Importing-autodie-into-another-namespace-than-%22caller%22)
* [BUGS](#BUGS)
+ [autodie and string eval](#autodie-and-string-eval)
+ [REPORTING BUGS](#REPORTING-BUGS)
* [FEEDBACK](#FEEDBACK)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
NAME
----
autodie - Replace functions with ones that succeed or die with lexical scope
SYNOPSIS
--------
```
use autodie; # Recommended: implies 'use autodie qw(:default)'
use autodie qw(:all); # Recommended more: defaults and system/exec.
use autodie qw(open close); # open/close succeed or die
open(my $fh, "<", $filename); # No need to check!
{
no autodie qw(open); # open failures won't die
open(my $fh, "<", $filename); # Could fail silently!
no autodie; # disable all autodies
}
print "Hello World" or die $!; # autodie DOESN'T check print!
```
DESCRIPTION
-----------
```
bIlujDI' yIchegh()Qo'; yIHegh()!
It is better to die() than to return() in failure.
-- Klingon programming proverb.
```
The `autodie` pragma provides a convenient way to replace functions that normally return false on failure with equivalents that throw an exception on failure.
The `autodie` pragma has *lexical scope*, meaning that functions and subroutines altered with `autodie` will only change their behaviour until the end of the enclosing block, file, or `eval`.
If `system` is specified as an argument to `autodie`, then it uses <IPC::System::Simple> to do the heavy lifting. See the description of that module for more information.
EXCEPTIONS
----------
Exceptions produced by the `autodie` pragma are members of the <autodie::exception> class. The preferred way to work with these exceptions under Perl 5.10 is as follows:
```
eval {
use autodie;
open(my $fh, '<', $some_file);
my @records = <$fh>;
# Do things with @records...
close($fh);
};
if ($@ and $@->isa('autodie::exception')) {
if ($@->matches('open')) { print "Error from open\n"; }
if ($@->matches(':io' )) { print "Non-open, IO error."; }
} elsif ($@) {
# A non-autodie exception.
}
```
See <autodie::exception> for further information on interrogating exceptions.
CATEGORIES
----------
Autodie uses a simple set of categories to group together similar built-ins. Requesting a category type (starting with a colon) will enable autodie for all built-ins beneath that category. For example, requesting `:file` will enable autodie for `close`, `fcntl`, `open` and `sysopen`.
The categories are currently:
```
:all
:default
:io
read
seek
sysread
sysseek
syswrite
:dbm
dbmclose
dbmopen
:file
binmode
close
chmod
chown
fcntl
flock
ioctl
open
sysopen
truncate
:filesys
chdir
closedir
opendir
link
mkdir
readlink
rename
rmdir
symlink
unlink
:ipc
kill
pipe
:msg
msgctl
msgget
msgrcv
msgsnd
:semaphore
semctl
semget
semop
:shm
shmctl
shmget
shmread
:socket
accept
bind
connect
getsockopt
listen
recv
send
setsockopt
shutdown
socketpair
:threads
fork
:system
system
exec
```
Note that while the above category system is presently a strict hierarchy, this should not be assumed.
A plain `use autodie` implies `use autodie qw(:default)`. Note that `system` and `exec` are not enabled by default. `system` requires the optional <IPC::System::Simple> module to be installed, and enabling `system` or `exec` will invalidate their exotic forms. See ["BUGS"](#BUGS) below for more details.
The syntax:
```
use autodie qw(:1.994);
```
allows the `:default` list from a particular version to be used. This provides the convenience of using the default methods, but the surety that no behavioral changes will occur if the `autodie` module is upgraded.
`autodie` can be enabled for all of Perl's built-ins, including `system` and `exec` with:
```
use autodie qw(:all);
```
FUNCTION SPECIFIC NOTES
------------------------
### print
The autodie pragma **does not check calls to `print`**.
### flock
It is not considered an error for `flock` to return false if it fails due to an `EWOULDBLOCK` (or equivalent) condition. This means one can still use the common convention of testing the return value of `flock` when called with the `LOCK_NB` option:
```
use autodie;
if ( flock($fh, LOCK_EX | LOCK_NB) ) {
# We have a lock
}
```
Autodying `flock` will generate an exception if `flock` returns false with any other error.
###
system/exec
The `system` built-in is considered to have failed in the following circumstances:
* The command does not start.
* The command is killed by a signal.
* The command returns a non-zero exit value (but see below).
On success, the autodying form of `system` returns the *exit value* rather than the contents of `$?`.
Additional allowable exit values can be supplied as an optional first argument to autodying `system`:
```
system( [ 0, 1, 2 ], $cmd, @args); # 0,1,2 are good exit values
```
`autodie` uses the <IPC::System::Simple> module to change `system`. See its documentation for further information.
Applying `autodie` to `system` or `exec` causes the exotic forms `system { $cmd } @args` or `exec { $cmd } @args` to be considered a syntax error until the end of the lexical scope. If you really need to use the exotic form, you can call `CORE::system` or `CORE::exec` instead, or use `no autodie qw(system exec)` before calling the exotic form.
GOTCHAS
-------
Functions called in list context are assumed to have failed if they return an empty list, or a list consisting only of a single undef element.
Some builtins (e.g. `chdir` or `truncate`) has a call signature that cannot completely be represented with a Perl prototype. This means that some valid Perl code will be invalid under autodie. As an example:
```
chdir(BAREWORD);
```
Without autodie (and assuming BAREWORD is an open filehandle/dirhandle) this is a valid call to chdir. But under autodie, `chdir` will behave like it had the prototype ";$" and thus BAREWORD will be a syntax error (under "use strict". Without strict, it will interpreted as a filename).
DIAGNOSTICS
-----------
:void cannot be used with lexical scope The `:void` option is supported in [Fatal](fatal), but not `autodie`. To workaround this, `autodie` may be explicitly disabled until the end of the current block with `no autodie`. To disable autodie for only a single function (eg, open) use `no autodie qw(open)`.
`autodie` performs no checking of called context to determine whether to throw an exception; the explicitness of error handling with `autodie` is a deliberate feature.
No user hints defined for %s You've insisted on hints for user-subroutines, either by pre-pending a `!` to the subroutine name itself, or earlier in the list of arguments to `autodie`. However the subroutine in question does not have any hints available.
See also ["DIAGNOSTICS" in Fatal](fatal#DIAGNOSTICS).
Tips and Tricks
----------------
###
Importing autodie into another namespace than "caller"
It is possible to import autodie into a different namespace by using <Import::Into>. However, you have to pass a "caller depth" (rather than a package name) for this to work correctly.
BUGS
----
"Used only once" warnings can be generated when `autodie` or `Fatal` is used with package filehandles (eg, `FILE`). Scalar filehandles are strongly recommended instead.
When using `autodie` or `Fatal` with user subroutines, the declaration of those subroutines must appear before the first use of `Fatal` or `autodie`, or have been exported from a module. Attempting to use `Fatal` or `autodie` on other user subroutines will result in a compile-time error.
Due to a bug in Perl, `autodie` may "lose" any format which has the same name as an autodying built-in or function.
`autodie` may not work correctly if used inside a file with a name that looks like a string eval, such as *eval (3)*.
###
autodie and string eval
Due to the current implementation of `autodie`, unexpected results may be seen when used near or with the string version of eval. *None of these bugs exist when using block eval*.
Under Perl 5.8 only, `autodie` *does not* propagate into string `eval` statements, although it can be explicitly enabled inside a string `eval`.
Under Perl 5.10 only, using a string eval when `autodie` is in effect can cause the autodie behaviour to leak into the surrounding scope. This can be worked around by using a `no autodie` at the end of the scope to explicitly remove autodie's effects, or by avoiding the use of string eval.
*None of these bugs exist when using block eval*. The use of `autodie` with block eval is considered good practice.
###
REPORTING BUGS
Please report bugs via the GitHub Issue Tracker at <https://github.com/pjf/autodie/issues>.
FEEDBACK
--------
If you find this module useful, please consider rating it on the CPAN Ratings service at <http://cpanratings.perl.org/rate?distribution=autodie> .
The module author loves to hear how `autodie` has made your life better (or worse). Feedback can be sent to <[email protected]>.
AUTHOR
------
Copyright 2008-2009, Paul Fenwick <[email protected]>
LICENSE
-------
This module is free software. You may distribute it under the same terms as Perl itself.
SEE ALSO
---------
[Fatal](fatal), <autodie::exception>, <autodie::hints>, <IPC::System::Simple>
*Perl tips, autodie* at <http://perltraining.com.au/tips/2008-08-20.html>
ACKNOWLEDGEMENTS
----------------
Mark Reed and Roland Giersig -- Klingon translators.
See the *AUTHORS* file for full credits. The latest version of this file can be found at <https://github.com/pjf/autodie/tree/master/AUTHORS> .
perl IO::Handle IO::Handle
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
* [METHODS](#METHODS)
* [NOTE](#NOTE)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
* [HISTORY](#HISTORY)
NAME
----
IO::Handle - supply object methods for I/O handles
SYNOPSIS
--------
```
use IO::Handle;
$io = IO::Handle->new();
if ($io->fdopen(fileno(STDIN),"r")) {
print $io->getline;
$io->close;
}
$io = IO::Handle->new();
if ($io->fdopen(fileno(STDOUT),"w")) {
$io->print("Some text\n");
}
# setvbuf is not available by default on Perls 5.8.0 and later.
use IO::Handle '_IOLBF';
$io->setvbuf($buffer_var, _IOLBF, 1024);
undef $io; # automatically closes the file if it's open
autoflush STDOUT 1;
```
DESCRIPTION
-----------
`IO::Handle` is the base class for all other IO handle classes. It is not intended that objects of `IO::Handle` would be created directly, but instead `IO::Handle` is inherited from by several other classes in the IO hierarchy.
If you are reading this documentation, looking for a replacement for the `FileHandle` package, then I suggest you read the documentation for `IO::File` too.
CONSTRUCTOR
-----------
new () Creates a new `IO::Handle` object.
new\_from\_fd ( FD, MODE ) Creates an `IO::Handle` like `new` does. It requires two parameters, which are passed to the method `fdopen`; if the fdopen fails, the object is destroyed. Otherwise, it is returned to the caller.
METHODS
-------
See <perlfunc> for complete descriptions of each of the following supported `IO::Handle` methods, which are just front ends for the corresponding built-in functions:
```
$io->close
$io->eof
$io->fcntl( FUNCTION, SCALAR )
$io->fileno
$io->format_write( [FORMAT_NAME] )
$io->getc
$io->ioctl( FUNCTION, SCALAR )
$io->read ( BUF, LEN, [OFFSET] )
$io->print ( ARGS )
$io->printf ( FMT, [ARGS] )
$io->say ( ARGS )
$io->stat
$io->sysread ( BUF, LEN, [OFFSET] )
$io->syswrite ( BUF, [LEN, [OFFSET]] )
$io->truncate ( LEN )
```
See <perlvar> for complete descriptions of each of the following supported `IO::Handle` methods. All of them return the previous value of the attribute and takes an optional single argument that when given will set the value. If no argument is given the previous value is unchanged (except for $io->autoflush will actually turn ON autoflush by default).
```
$io->autoflush ( [BOOL] ) $|
$io->format_page_number( [NUM] ) $%
$io->format_lines_per_page( [NUM] ) $=
$io->format_lines_left( [NUM] ) $-
$io->format_name( [STR] ) $~
$io->format_top_name( [STR] ) $^
$io->input_line_number( [NUM]) $.
```
The following methods are not supported on a per-filehandle basis.
```
IO::Handle->format_line_break_characters( [STR] ) $:
IO::Handle->format_formfeed( [STR]) $^L
IO::Handle->output_field_separator( [STR] ) $,
IO::Handle->output_record_separator( [STR] ) $\
IO::Handle->input_record_separator( [STR] ) $/
```
Furthermore, for doing normal I/O you might need these:
$io->fdopen ( FD, MODE ) `fdopen` is like an ordinary `open` except that its first parameter is not a filename but rather a file handle name, an IO::Handle object, or a file descriptor number. (For the documentation of the `open` method, see <IO::File>.)
$io->opened Returns true if the object is currently a valid file descriptor, false otherwise.
$io->getline This works like <$io> described in ["I/O Operators" in perlop](perlop#I%2FO-Operators) except that it's more readable and can be safely called in a list context but still returns just one line. If used as the conditional within a `while` or C-style `for` loop, however, you will need to emulate the functionality of <$io> with `defined($_ = $io->getline)`.
$io->getlines This works like <$io> when called in a list context to read all the remaining lines in a file, except that it's more readable. It will also croak() if accidentally called in a scalar context.
$io->ungetc ( ORD ) Pushes a character with the given ordinal value back onto the given handle's input stream. Only one character of pushback per handle is guaranteed.
$io->write ( BUF, LEN [, OFFSET ] ) This `write` is somewhat like `write` found in C, in that it is the opposite of read. The wrapper for the perl `write` function is called `format_write`. However, whilst the C `write` function returns the number of bytes written, this `write` function simply returns true if successful (like `print`). A more C-like `write` is `syswrite` (see above).
$io->error Returns a true value if the given handle has experienced any errors since it was opened or since the last call to `clearerr`, or if the handle is invalid. It only returns false for a valid handle with no outstanding errors.
$io->clearerr Clear the given handle's error indicator. Returns -1 if the handle is invalid, 0 otherwise.
$io->sync `sync` synchronizes a file's in-memory state with that on the physical medium. `sync` does not operate at the perlio api level, but operates on the file descriptor (similar to sysread, sysseek and systell). This means that any data held at the perlio api level will not be synchronized. To synchronize data that is buffered at the perlio api level you must use the flush method. `sync` is not implemented on all platforms. Returns "0 but true" on success, `undef` on error, `undef` for an invalid handle. See fsync(3c).
$io->flush `flush` causes perl to flush any buffered data at the perlio api level. Any unread data in the buffer will be discarded, and any unwritten data will be written to the underlying file descriptor. Returns "0 but true" on success, `undef` on error.
$io->printflush ( ARGS ) Turns on autoflush, print ARGS and then restores the autoflush status of the `IO::Handle` object. Returns the return value from print.
$io->blocking ( [ BOOL ] ) If called with an argument `blocking` will turn on non-blocking IO if `BOOL` is false, and turn it off if `BOOL` is true.
`blocking` will return the value of the previous setting, or the current setting if `BOOL` is not given.
If an error occurs `blocking` will return undef and `$!` will be set.
If the C functions setbuf() and/or setvbuf() are available, then `IO::Handle::setbuf` and `IO::Handle::setvbuf` set the buffering policy for an IO::Handle. The calling sequences for the Perl functions are the same as their C counterparts--including the constants `_IOFBF`, `_IOLBF`, and `_IONBF` for setvbuf()--except that the buffer parameter specifies a scalar variable to use as a buffer. You should only change the buffer before any I/O, or immediately after calling flush.
WARNING: The IO::Handle::setvbuf() is not available by default on Perls 5.8.0 and later because setvbuf() is rather specific to using the stdio library, while Perl prefers the new perlio subsystem instead.
WARNING: A variable used as a buffer by `setbuf` or `setvbuf` **must not be modified** in any way until the IO::Handle is closed or `setbuf` or `setvbuf` is called again, or memory corruption may result! Remember that the order of global destruction is undefined, so even if your buffer variable remains in scope until program termination, it may be undefined before the file IO::Handle is closed. Note that you need to import the constants `_IOFBF`, `_IOLBF`, and `_IONBF` explicitly. Like C, setbuf returns nothing. setvbuf returns "0 but true", on success, `undef` on failure.
Lastly, there is a special method for working under **-T** and setuid/gid scripts:
$io->untaint Marks the object as taint-clean, and as such data read from it will also be considered taint-clean. Note that this is a very trusting action to take, and appropriate consideration for the data source and potential vulnerability should be kept in mind. Returns 0 on success, -1 if setting the taint-clean flag failed. (eg invalid handle)
NOTE
----
An `IO::Handle` object is a reference to a symbol/GLOB reference (see the `Symbol` package). Some modules that inherit from `IO::Handle` may want to keep object related variables in the hash table part of the GLOB. In an attempt to prevent modules trampling on each other I propose the that any such module should prefix its variables with its own name separated by \_'s. For example the IO::Socket module keeps a `timeout` variable in 'io\_socket\_timeout'.
SEE ALSO
---------
<perlfunc>, ["I/O Operators" in perlop](perlop#I%2FO-Operators), <IO::File>
BUGS
----
Due to backwards compatibility, all filehandles resemble objects of class `IO::Handle`, or actually classes derived from that class. They actually aren't. Which means you can't derive your own class from `IO::Handle` and inherit those methods.
HISTORY
-------
Derived from FileHandle.pm by Graham Barr <*[email protected]*>
| programming_docs |
perl ExtUtils::Miniperl ExtUtils::Miniperl
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::Miniperl - write the C code for miniperlmain.c and perlmain.c
SYNOPSIS
--------
```
use ExtUtils::Miniperl;
writemain(@directories);
# or
writemain($fh, @directories);
# or
writemain(\$filename, @directories);
```
DESCRIPTION
-----------
`writemain()` takes an argument list of zero or more directories containing archive libraries that relate to perl modules and should be linked into a new perl binary. It writes a corresponding *miniperlmain.c* or *perlmain.c* file that is a plain C file containing all the bootstrap code to make the modules associated with the libraries available from within perl. If the first argument to `writemain()` is a reference to a scalar it is used as the filename to open for output. Any other reference is used as the filehandle to write to. Otherwise output defaults to `STDOUT`.
The typical usage is from within perl's own Makefile (to build *perlmain.c*) or from *regen/miniperlmain.pl* (to build miniperlmain.c). So under normal circumstances you won't have to deal with this module directly.
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl IPC::Msg IPC::Msg
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IPC::Msg - SysV Msg IPC object class
SYNOPSIS
--------
```
use IPC::SysV qw(IPC_PRIVATE S_IRUSR S_IWUSR);
use IPC::Msg;
$msg = IPC::Msg->new(IPC_PRIVATE, S_IRUSR | S_IWUSR);
$msg->snd($msgtype, $msgdata);
$msg->rcv($buf, 256);
$ds = $msg->stat;
$msg->remove;
```
DESCRIPTION
-----------
A class providing an object based interface to SysV IPC message queues.
METHODS
-------
new ( KEY , FLAGS ) Creates a new message queue associated with `KEY`. A new queue is created if
* `KEY` is equal to `IPC_PRIVATE`
* `KEY` does not already have a message queue associated with it, and `*FLAGS* & IPC_CREAT` is true.
On creation of a new message queue `FLAGS` is used to set the permissions. Be careful not to set any flags that the Sys V IPC implementation does not allow: in some systems setting execute bits makes the operations fail.
id Returns the system message queue identifier.
rcv ( BUF, LEN [, TYPE [, FLAGS ]] ) Read a message from the queue. Returns the type of the message read. See [msgrcv(2)](http://man.he.net/man2/msgrcv). The BUF becomes tainted.
remove Remove and destroy the message queue from the system.
set ( STAT )
set ( NAME => VALUE [, NAME => VALUE ...] ) `set` will set the following values of the `stat` structure associated with the message queue.
```
uid
gid
mode (oly the permission bits)
qbytes
```
`set` accepts either a stat object, as returned by the `stat` method, or a list of *name*-*value* pairs.
snd ( TYPE, MSG [, FLAGS ] ) Place a message on the queue with the data from `MSG` and with type `TYPE`. See [msgsnd(2)](http://man.he.net/man2/msgsnd).
stat Returns an object of type `IPC::Msg::stat` which is a sub-class of `Class::Struct`. It provides the following fields. For a description of these fields see you system documentation.
```
uid
gid
cuid
cgid
mode
qnum
qbytes
lspid
lrpid
stime
rtime
ctime
```
SEE ALSO
---------
<IPC::SysV>, <Class::Struct>
AUTHORS
-------
Graham Barr <[email protected]>, Marcus Holland-Moritz <[email protected]>
COPYRIGHT
---------
Version 2.x, Copyright (C) 2007-2013, Marcus Holland-Moritz.
Version 1.x, Copyright (c) 1997, Graham Barr.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl TAP::Parser::Iterator::Process TAP::Parser::Iterator::Process
==============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [next](#next)
- [next\_raw](#next_raw)
- [wait](#wait)
- [exit](#exit)
- [handle\_unicode](#handle_unicode)
- [get\_select\_handles](#get_select_handles)
* [ATTRIBUTION](#ATTRIBUTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Iterator::Process - Iterator for process-based TAP sources
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Iterator::Process;
my %args = (
command => ['python', 'setup.py', 'test'],
merge => 1,
setup => sub { ... },
teardown => sub { ... },
);
my $it = TAP::Parser::Iterator::Process->new(\%args);
my $line = $it->next;
```
DESCRIPTION
-----------
This is a simple iterator wrapper for executing external processes, used by <TAP::Parser>. Unless you're writing a plugin or subclassing, you probably won't need to use this module directly.
METHODS
-------
###
Class Methods
#### `new`
Create an iterator. Expects one argument containing a hashref of the form:
```
command => \@command_to_execute
merge => $attempt_merge_stderr_and_stdout?
setup => $callback_to_setup_command
teardown => $callback_to_teardown_command
```
Tries to uses <IPC::Open3> & <IO::Select> to communicate with the spawned process if they are available. Falls back onto `open()`.
###
Instance Methods
#### `next`
Iterate through the process output, of course.
#### `next_raw`
Iterate raw input without applying any fixes for quirky input syntax.
#### `wait`
Get the wait status for this iterator's process.
#### `exit`
Get the exit status for this iterator's process.
#### `handle_unicode`
Upgrade the input stream to handle UTF8.
#### `get_select_handles`
Return a list of filehandles that may be used upstream in a select() call to signal that this Iterator is ready. Iterators that are not handle based should return an empty list.
ATTRIBUTION
-----------
Originally ripped off from <Test::Harness>.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::Iterator>,
perl File::Path File::Path
==========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [ERROR HANDLING](#ERROR-HANDLING)
+ [NOTES](#NOTES)
- [API CHANGES](#API-CHANGES)
- [SECURITY CONSIDERATIONS](#SECURITY-CONSIDERATIONS)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [SEE ALSO](#SEE-ALSO)
* [BUGS AND LIMITATIONS](#BUGS-AND-LIMITATIONS)
+ [MULTITHREADED APPLICATIONS](#MULTITHREADED-APPLICATIONS)
+ [NFS Mount Points](#NFS-Mount-Points)
+ [REPORTING BUGS](#REPORTING-BUGS)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHORS](#AUTHORS)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT](#COPYRIGHT)
* [LICENSE](#LICENSE)
NAME
----
File::Path - Create or remove directory trees
VERSION
-------
2.18 - released November 4 2020.
SYNOPSIS
--------
```
use File::Path qw(make_path remove_tree);
@created = make_path('foo/bar/baz', '/zug/zwang');
@created = make_path('foo/bar/baz', '/zug/zwang', {
verbose => 1,
mode => 0711,
});
make_path('foo/bar/baz', '/zug/zwang', {
chmod => 0777,
});
$removed_count = remove_tree('foo/bar/baz', '/zug/zwang', {
verbose => 1,
error => \my $err_list,
safe => 1,
});
# legacy (interface promoted before v2.00)
@created = mkpath('/foo/bar/baz');
@created = mkpath('/foo/bar/baz', 1, 0711);
@created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
$removed_count = rmtree('foo/bar/baz', 1, 1);
$removed_count = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
# legacy (interface promoted before v2.06)
@created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
$removed_count = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });
```
DESCRIPTION
-----------
This module provides a convenient way to create directories of arbitrary depth and to delete an entire directory subtree from the filesystem.
The following functions are provided:
make\_path( $dir1, $dir2, .... )
make\_path( $dir1, $dir2, ...., \%opts ) The `make_path` function creates the given directories if they don't exist before, much like the Unix command `mkdir -p`.
The function accepts a list of directories to be created. Its behaviour may be tuned by an optional hashref appearing as the last parameter on the call.
The function returns the list of directories actually created during the call; in scalar context the number of directories created.
The following keys are recognised in the option hash:
mode => $num The numeric permissions mode to apply to each created directory (defaults to `0777`), to be modified by the current `umask`. If the directory already exists (and thus does not need to be created), the permissions will not be modified.
`mask` is recognised as an alias for this parameter.
chmod => $num Takes a numeric mode to apply to each created directory (not modified by the current `umask`). If the directory already exists (and thus does not need to be created), the permissions will not be modified.
verbose => $bool If present, will cause `make_path` to print the name of each directory as it is created. By default nothing is printed.
error => \$err If present, it should be a reference to a scalar. This scalar will be made to reference an array, which will be used to store any errors that are encountered. See the ["ERROR HANDLING"](#ERROR-HANDLING) section for more information.
If this parameter is not used, certain error conditions may raise a fatal error that will cause the program to halt, unless trapped in an `eval` block.
owner => $owner
user => $owner
uid => $owner If present, will cause any created directory to be owned by `$owner`. If the value is numeric, it will be interpreted as a uid; otherwise a username is assumed. An error will be issued if the username cannot be mapped to a uid, the uid does not exist or the process lacks the privileges to change ownership.
Ownership of directories that already exist will not be changed.
`user` and `uid` are aliases of `owner`.
group => $group If present, will cause any created directory to be owned by the group `$group`. If the value is numeric, it will be interpreted as a gid; otherwise a group name is assumed. An error will be issued if the group name cannot be mapped to a gid, the gid does not exist or the process lacks the privileges to change group ownership.
Group ownership of directories that already exist will not be changed.
```
make_path '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};
```
mkpath( $dir )
mkpath( $dir, $verbose, $mode )
mkpath( [$dir1, $dir2,...], $verbose, $mode )
mkpath( $dir1, $dir2,..., \%opt ) The `mkpath()` function provide the legacy interface of `make_path()` with a different interpretation of the arguments passed. The behaviour and return value of the function is otherwise identical to `make_path()`.
remove\_tree( $dir1, $dir2, .... )
remove\_tree( $dir1, $dir2, ...., \%opts ) The `remove_tree` function deletes the given directories and any files and subdirectories they might contain, much like the Unix command `rm -rf` or the Windows commands `rmdir /s` and `rd /s`.
The function accepts a list of directories to be removed. (In point of fact, it will also accept filesystem entries which are not directories, such as regular files and symlinks. But, as its name suggests, its intent is to remove trees rather than individual files.)
`remove_tree()`'s behaviour may be tuned by an optional hashref appearing as the last parameter on the call. If an empty string is passed to `remove_tree`, an error will occur.
**NOTE:** For security reasons, we strongly advise use of the hashref-as-final-argument syntax -- specifically, with a setting of the `safe` element to a true value.
```
remove_tree( $dir1, $dir2, ....,
{
safe => 1,
... # other key-value pairs
},
);
```
The function returns the number of files successfully deleted.
The following keys are recognised in the option hash:
verbose => $bool If present, will cause `remove_tree` to print the name of each file as it is unlinked. By default nothing is printed.
safe => $bool When set to a true value, will cause `remove_tree` to skip the files for which the process lacks the required privileges needed to delete files, such as delete privileges on VMS. In other words, the code will make no attempt to alter file permissions. Thus, if the process is interrupted, no filesystem object will be left in a more permissive mode.
keep\_root => $bool When set to a true value, will cause all files and subdirectories to be removed, except the initially specified directories. This comes in handy when cleaning out an application's scratch directory.
```
remove_tree( '/tmp', {keep_root => 1} );
```
result => \$res If present, it should be a reference to a scalar. This scalar will be made to reference an array, which will be used to store all files and directories unlinked during the call. If nothing is unlinked, the array will be empty.
```
remove_tree( '/tmp', {result => \my $list} );
print "unlinked $_\n" for @$list;
```
This is a useful alternative to the `verbose` key.
error => \$err If present, it should be a reference to a scalar. This scalar will be made to reference an array, which will be used to store any errors that are encountered. See the ["ERROR HANDLING"](#ERROR-HANDLING) section for more information.
Removing things is a much more dangerous proposition than creating things. As such, there are certain conditions that `remove_tree` may encounter that are so dangerous that the only sane action left is to kill the program.
Use `error` to trap all that is reasonable (problems with permissions and the like), and let it die if things get out of hand. This is the safest course of action.
rmtree( $dir )
rmtree( $dir, $verbose, $safe )
rmtree( [$dir1, $dir2,...], $verbose, $safe )
rmtree( $dir1, $dir2,..., \%opt ) The `rmtree()` function provide the legacy interface of `remove_tree()` with a different interpretation of the arguments passed. The behaviour and return value of the function is otherwise identical to `remove_tree()`.
**NOTE:** For security reasons, we strongly advise use of the hashref-as-final-argument syntax, specifically with a setting of the `safe` element to a true value.
```
rmtree( $dir1, $dir2, ....,
{
safe => 1,
... # other key-value pairs
},
);
```
###
ERROR HANDLING
**NOTE:**
The following error handling mechanism is consistent throughout all code paths EXCEPT in cases where the ROOT node is nonexistent. In version 2.11 the maintainers attempted to rectify this inconsistency but too many downstream modules encountered problems. In such case, if you require root node evaluation or error checking prior to calling `make_path` or `remove_tree`, you should take additional precautions.
If `make_path` or `remove_tree` encounters an error, a diagnostic message will be printed to `STDERR` via `carp` (for non-fatal errors) or via `croak` (for fatal errors).
If this behaviour is not desirable, the `error` attribute may be used to hold a reference to a variable, which will be used to store the diagnostics. The variable is made a reference to an array of hash references. Each hash contain a single key/value pair where the key is the name of the file, and the value is the error message (including the contents of `$!` when appropriate). If a general error is encountered the diagnostic key will be empty.
An example usage looks like:
```
remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
if ($err && @$err) {
for my $diag (@$err) {
my ($file, $message) = %$diag;
if ($file eq '') {
print "general error: $message\n";
}
else {
print "problem unlinking $file: $message\n";
}
}
}
else {
print "No error encountered\n";
}
```
Note that if no errors are encountered, `$err` will reference an empty array. This means that `$err` will always end up TRUE; so you need to test `@$err` to determine if errors occurred.
### NOTES
`File::Path` blindly exports `mkpath` and `rmtree` into the current namespace. These days, this is considered bad style, but to change it now would break too much code. Nonetheless, you are invited to specify what it is you are expecting to use:
```
use File::Path 'rmtree';
```
The routines `make_path` and `remove_tree` are **not** exported by default. You must specify which ones you want to use.
```
use File::Path 'remove_tree';
```
Note that a side-effect of the above is that `mkpath` and `rmtree` are no longer exported at all. This is due to the way the `Exporter` module works. If you are migrating a codebase to use the new interface, you will have to list everything explicitly. But that's just good practice anyway.
```
use File::Path qw(remove_tree rmtree);
```
####
API CHANGES
The API was changed in the 2.0 branch. For a time, `mkpath` and `rmtree` tried, unsuccessfully, to deal with the two different calling mechanisms. This approach was considered a failure.
The new semantics are now only available with `make_path` and `remove_tree`. The old semantics are only available through `mkpath` and `rmtree`. Users are strongly encouraged to upgrade to at least 2.08 in order to avoid surprises.
####
SECURITY CONSIDERATIONS
There were race conditions in the 1.x implementations of File::Path's `rmtree` function (although sometimes patched depending on the OS distribution or platform). The 2.0 version contains code to avoid the problem mentioned in CVE-2002-0435.
See the following pages for more information:
```
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
http://www.debian.org/security/2005/dsa-696
```
Additionally, unless the `safe` parameter is set (or the third parameter in the traditional interface is TRUE), should a `remove_tree` be interrupted, files that were originally in read-only mode may now have their permissions set to a read-write (or "delete OK") mode.
The following CVE reports were previously filed against File-Path and are believed to have been addressed:
* <http://cve.circl.lu/cve/CVE-2004-0452>
* <http://cve.circl.lu/cve/CVE-2005-0448>
In February 2017 the cPanel Security Team reported an additional vulnerability in File-Path. The `chmod()` logic to make directories traversable can be abused to set the mode on an attacker-chosen file to an attacker-chosen value. This is due to the time-of-check-to-time-of-use (TOCTTOU) race condition (<https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>) between the `stat()` that decides the inode is a directory and the `chmod()` that tries to make it user-rwx. CPAN versions 2.13 and later incorporate a patch provided by John Lightsey to address this problem. This vulnerability has been reported as CVE-2017-6512.
DIAGNOSTICS
-----------
FATAL errors will cause the program to halt (`croak`), since the problem is so severe that it would be dangerous to continue. (This can always be trapped with `eval`, but it's not a good idea. Under the circumstances, dying is the best thing to do).
SEVERE errors may be trapped using the modern interface. If the they are not trapped, or if the old interface is used, such an error will cause the program will halt.
All other errors may be trapped using the modern interface, otherwise they will be `carp`ed about. Program execution will not be halted.
mkdir [path]: [errmsg] (SEVERE) `make_path` was unable to create the path. Probably some sort of permissions error at the point of departure or insufficient resources (such as free inodes on Unix).
No root path(s) specified `make_path` was not given any paths to create. This message is only emitted if the routine is called with the traditional interface. The modern interface will remain silent if given nothing to do.
No such file or directory On Windows, if `make_path` gives you this warning, it may mean that you have exceeded your filesystem's maximum path length.
cannot fetch initial working directory: [errmsg] `remove_tree` attempted to determine the initial directory by calling `Cwd::getcwd`, but the call failed for some reason. No attempt will be made to delete anything.
cannot stat initial working directory: [errmsg] `remove_tree` attempted to stat the initial directory (after having successfully obtained its name via `getcwd`), however, the call failed for some reason. No attempt will be made to delete anything.
cannot chdir to [dir]: [errmsg] `remove_tree` attempted to set the working directory in order to begin deleting the objects therein, but was unsuccessful. This is usually a permissions issue. The routine will continue to delete other things, but this directory will be left intact.
directory [dir] changed before chdir, expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL) `remove_tree` recorded the device and inode of a directory, and then moved into it. It then performed a `stat` on the current directory and detected that the device and inode were no longer the same. As this is at the heart of the race condition problem, the program will die at this point.
cannot make directory [dir] read+writeable: [errmsg] `remove_tree` attempted to change the permissions on the current directory to ensure that subsequent unlinkings would not run into problems, but was unable to do so. The permissions remain as they were, and the program will carry on, doing the best it can.
cannot read [dir]: [errmsg] `remove_tree` tried to read the contents of the directory in order to acquire the names of the directory entries to be unlinked, but was unsuccessful. This is usually a permissions issue. The program will continue, but the files in this directory will remain after the call.
cannot reset chmod [dir]: [errmsg] `remove_tree`, after having deleted everything in a directory, attempted to restore its permissions to the original state but failed. The directory may wind up being left behind.
cannot remove [dir] when cwd is [dir] The current working directory of the program is */some/path/to/here* and you are attempting to remove an ancestor, such as */some/path*. The directory tree is left untouched.
The solution is to `chdir` out of the child directory to a place outside the directory tree to be removed.
cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL) `remove_tree`, after having deleted everything and restored the permissions of a directory, was unable to chdir back to the parent. The program halts to avoid a race condition from occurring.
cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL) `remove_tree` was unable to stat the parent directory after having returned from the child. Since there is no way of knowing if we returned to where we think we should be (by comparing device and inode) the only way out is to `croak`.
previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL) When `remove_tree` returned from deleting files in a child directory, a check revealed that the parent directory it returned to wasn't the one it started out from. This is considered a sign of malicious activity.
cannot make directory [dir] writeable: [errmsg] Just before removing a directory (after having successfully removed everything it contained), `remove_tree` attempted to set the permissions on the directory to ensure it could be removed and failed. Program execution continues, but the directory may possibly not be deleted.
cannot remove directory [dir]: [errmsg] `remove_tree` attempted to remove a directory, but failed. This may be because some objects that were unable to be removed remain in the directory, or it could be a permissions issue. The directory will be left behind.
cannot restore permissions of [dir] to [0nnn]: [errmsg] After having failed to remove a directory, `remove_tree` was unable to restore its permissions from a permissive state back to a possibly more restrictive setting. (Permissions given in octal).
cannot make file [file] writeable: [errmsg] `remove_tree` attempted to force the permissions of a file to ensure it could be deleted, but failed to do so. It will, however, still attempt to unlink the file.
cannot unlink file [file]: [errmsg] `remove_tree` failed to remove a file. Probably a permissions issue.
cannot restore permissions of [file] to [0nnn]: [errmsg] After having failed to remove a file, `remove_tree` was also unable to restore the permissions on the file to a possibly less permissive setting. (Permissions given in octal).
unable to map [owner] to a uid, ownership not changed"); `make_path` was instructed to give the ownership of created directories to the symbolic name [owner], but `getpwnam` did not return the corresponding numeric uid. The directory will be created, but ownership will not be changed.
unable to map [group] to a gid, group ownership not changed `make_path` was instructed to give the group ownership of created directories to the symbolic name [group], but `getgrnam` did not return the corresponding numeric gid. The directory will be created, but group ownership will not be changed.
SEE ALSO
---------
* <File::Remove>
Allows files and directories to be moved to the Trashcan/Recycle Bin (where they may later be restored if necessary) if the operating system supports such functionality. This feature may one day be made available directly in `File::Path`.
* <File::Find::Rule>
When removing directory trees, if you want to examine each file to decide whether to delete it (and possibly leaving large swathes alone), *File::Find::Rule* offers a convenient and flexible approach to examining directory trees.
BUGS AND LIMITATIONS
---------------------
The following describes *File::Path* limitations and how to report bugs.
###
MULTITHREADED APPLICATIONS
*File::Path* `rmtree` and `remove_tree` will not work with multithreaded applications due to its use of `chdir`. At this time, no warning or error is generated in this situation. You will certainly encounter unexpected results.
The implementation that surfaces this limitation will not be changed. See the *File::Path::Tiny* module for functionality similar to *File::Path* but which does not `chdir`.
###
NFS Mount Points
*File::Path* is not responsible for triggering the automounts, mirror mounts, and the contents of network mounted filesystems. If your NFS implementation requires an action to be performed on the filesystem in order for *File::Path* to perform operations, it is strongly suggested you assure filesystem availability by reading the root of the mounted filesystem.
###
REPORTING BUGS
Please report all bugs on the RT queue, either via the web interface:
<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
or by email:
```
[email protected]
```
In either case, please **attach** patches to the bug report rather than including them inline in the web post or the body of the email.
You can also send pull requests to the Github repository:
<https://github.com/rpcme/File-Path>
ACKNOWLEDGEMENTS
----------------
Paul Szabo identified the race condition originally, and Brendan O'Dea wrote an implementation for Debian that addressed the problem. That code was used as a basis for the current code. Their efforts are greatly appreciated.
Gisle Aas made a number of improvements to the documentation for 2.07 and his advice and assistance is also greatly appreciated.
AUTHORS
-------
Prior authors and maintainers: Tim Bunce, Charles Bailey, and David Landgren <*[email protected]*>.
Current maintainers are Richard Elberger <*[email protected]*> and James (Jim) Keenan <*[email protected]*>.
CONTRIBUTORS
------------
Contributors to File::Path, in alphabetical order by first name.
<*[email protected]*>
Charlie Gonzalez <*[email protected]*>
Craig A. Berry <*[email protected]*>
James E Keenan <*[email protected]*>
John Lightsey <*[email protected]*>
Nigel Horne <*[email protected]*>
Richard Elberger <*[email protected]*>
Ryan Yee <*[email protected]*>
Skye Shaw <*[email protected]*>
Tom Lutz <*[email protected]*>
Will Sheppard <*willsheppard@github*> COPYRIGHT
---------
This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren, James Keenan and Richard Elberger 1995-2020. All rights reserved.
LICENSE
-------
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl piconv piconv
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
piconv -- iconv(1), reinvented in perl
SYNOPSIS
--------
```
piconv [-f from_encoding] [-t to_encoding]
[-p|--perlqq|--htmlcref|--xmlcref] [-C N|-c] [-D] [-S scheme]
[-s string|file...]
piconv -l
piconv -r encoding_alias
piconv -h
```
DESCRIPTION
-----------
**piconv** is perl version of **iconv**, a character encoding converter widely available for various Unixen today. This script was primarily a technology demonstrator for Perl 5.8.0, but you can use piconv in the place of iconv for virtually any case.
piconv converts the character encoding of either STDIN or files specified in the argument and prints out to STDOUT.
Here is the list of options. Some options can be in short format (-f) or long (--from) one.
-f,--from *from\_encoding*
Specifies the encoding you are converting from. Unlike **iconv**, this option can be omitted. In such cases, the current locale is used.
-t,--to *to\_encoding*
Specifies the encoding you are converting to. Unlike **iconv**, this option can be omitted. In such cases, the current locale is used.
Therefore, when both -f and -t are omitted, **piconv** just acts like **cat**.
-s,--string *string*
uses *string* instead of file for the source of text.
-l,--list Lists all available encodings, one per line, in case-insensitive order. Note that only the canonical names are listed; many aliases exist. For example, the names are case-insensitive, and many standard and common aliases work, such as "latin1" for "ISO-8859-1", or "ibm850" instead of "cp850", or "winlatin1" for "cp1252". See <Encode::Supported> for a full discussion.
-r,--resolve *encoding\_alias*
Resolve *encoding\_alias* to Encode canonical encoding name.
-C,--check *N*
Check the validity of the stream if *N* = 1. When *N* = -1, something interesting happens when it encounters an invalid character.
-c Same as `-C 1`.
-p,--perlqq Transliterate characters missing in encoding to \x{HHHH} where HHHH is the hexadecimal Unicode code point.
--htmlcref Transliterate characters missing in encoding to &#NNN; where NNN is the decimal Unicode code point.
--xmlcref Transliterate characters missing in encoding to &#xHHHH; where HHHH is the hexadecimal Unicode code point.
-h,--help Show usage.
-D,--debug Invokes debugging mode. Primarily for Encode hackers.
-S,--scheme *scheme*
Selects which scheme is to be used for conversion. Available schemes are as follows:
from\_to Uses Encode::from\_to for conversion. This is the default.
decode\_encode Input strings are decode()d then encode()d. A straight two-step implementation.
perlio The new perlIO layer is used. NI-S' favorite.
You should use this option if you are using UTF-16 and others which linefeed is not $/.
Like the *-D* option, this is also for Encode hackers.
SEE ALSO
---------
[iconv(1)](http://man.he.net/man1/iconv) [locale(3)](http://man.he.net/man3/locale) [Encode](encode) <Encode::Supported> <Encode::Alias> [PerlIO](perlio)
perl Pod::Perldoc::ToTk Pod::Perldoc::ToTk
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToTk - let Perldoc use Tk::Pod to render Pod
SYNOPSIS
--------
```
perldoc -o tk Some::Modulename &
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Tk::Pod as a formatter class.
You have to have installed Tk::Pod first, or this class won't load.
SEE ALSO
---------
<Tk::Pod>, <Pod::Perldoc>
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`; Sean M. Burke `<[email protected]>`; significant portions copied from *tkpod* in the Tk::Pod dist, by Nick Ing-Simmons, Slaven Rezic, et al.
perl perlintern perlintern
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [AV Handling](#AV-Handling)
* [Callback Functions](#Callback-Functions)
* [Casting](#Casting)
* [Character case changing](#Character-case-changing)
* [Character classification](#Character-classification)
* [Compiler and Preprocessor information](#Compiler-and-Preprocessor-information)
* [Compiler directives](#Compiler-directives)
* [Compile-time scope hooks](#Compile-time-scope-hooks)
* [Concurrency](#Concurrency)
* [COPs and Hint Hashes](#COPs-and-Hint-Hashes)
* [Custom Operators](#Custom-Operators)
* [CV Handling](#CV-Handling)
* [Debugging](#Debugging)
* [Display functions](#Display-functions)
* [Embedding, Threads, and Interpreter Cloning](#Embedding,-Threads,-and-Interpreter-Cloning)
* [Errno](#Errno)
* [Exception Handling (simple) Macros](#Exception-Handling-(simple)-Macros)
* [Filesystem configuration values](#Filesystem-configuration-values)
* [Floating point](#Floating-point)
* [General Configuration](#General-Configuration)
* [Global Variables](#Global-Variables)
* [GV Handling and Stashes](#GV-Handling-and-Stashes)
* [Hook manipulation](#Hook-manipulation)
* [HV Handling](#HV-Handling)
* [Input/Output](#Input/Output)
* [Integer](#Integer)
* [I/O Formats](#I/O-Formats)
* [Lexer interface](#Lexer-interface)
* [Locales](#Locales)
* [Magic](#Magic)
* [Memory Management](#Memory-Management)
* [MRO](#MRO)
* [Multicall Functions](#Multicall-Functions)
* [Numeric Functions](#Numeric-Functions)
* [Optrees](#Optrees)
* [Pack and Unpack](#Pack-and-Unpack)
* [Pad Data Structures](#Pad-Data-Structures)
* [Password and Group access](#Password-and-Group-access)
* [Paths to system commands](#Paths-to-system-commands)
* [Prototype information](#Prototype-information)
* [REGEXP Functions](#REGEXP-Functions)
* [Reports and Formats](#Reports-and-Formats)
* [Signals](#Signals)
* [Site configuration](#Site-configuration)
* [Sockets configuration values](#Sockets-configuration-values)
* [Source Filters](#Source-Filters)
* [Stack Manipulation Macros](#Stack-Manipulation-Macros)
* [String Handling](#String-Handling)
* [SV Flags](#SV-Flags)
* [SV Handling](#SV-Handling)
* [Tainting](#Tainting)
* [Time](#Time)
* [Typedef names](#Typedef-names)
* [Unicode Support](#Unicode-Support)
* [Utility Functions](#Utility-Functions)
* [Versioning](#Versioning)
* [Warning and Dieing](#Warning-and-Dieing)
* [XS](#XS)
* [Undocumented elements](#Undocumented-elements)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlintern - autogenerated documentation of purely **internal** Perl functions
DESCRIPTION
-----------
This file is the autogenerated documentation of functions in the Perl interpreter that are documented using Perl's internal documentation format but are not marked as part of the Perl API. In other words, **they are not for use in extensions**!
It has the same sections as <perlapi>, though some may be empty.
AV Handling
------------
`av_fetch_simple` This is a cut-down version of av\_fetch that assumes that the array is very straightforward - no magic, not readonly, and AvREAL - and that `key` is not negative. This function MUST NOT be used in situations where any of those assumptions may not hold.
Returns the SV at the specified index in the array. The `key` is the index. If lval is true, you are guaranteed to get a real SV back (in case it wasn't real before), which you can then modify. Check that the return value is non-null before dereferencing it to a `SV*`.
The rough perl equivalent is `$myarray[$key]`.
```
SV** av_fetch_simple(AV *av, SSize_t key, I32 lval)
```
`AvFILLp` If the array `av` is empty, this returns -1; otherwise it returns the maximum value of the indices of all the array elements which are currently defined in `av`. It does not handle magic, hence the `p` private indication in its name.
```
SSize_t AvFILLp(AV* av)
```
`av_new_alloc` This implements ["`newAV_alloc_x`" in perlapi](perlapi#newAV_alloc_x) and ["`newAV_alloc_xz`" in perlapi](perlapi#newAV_alloc_xz), which are the public API for this functionality.
Creates a new AV and allocates its SV\* array.
This is similar to, but more efficient than doing:
```
AV *av = newAV();
av_extend(av, key);
```
The size parameter is used to pre-allocate a SV\* array large enough to hold at least elements `0..(size-1)`. `size` must be at least 1.
The `zeroflag` parameter controls whether or not the array is NULL initialized.
```
AV* av_new_alloc(SSize_t size, bool zeroflag)
```
`av_store_simple` This is a cut-down version of av\_store that assumes that the array is very straightforward - no magic, not readonly, and AvREAL - and that `key` is not negative. This function MUST NOT be used in situations where any of those assumptions may not hold.
Stores an SV in an array. The array index is specified as `key`. It can be dereferenced to get the `SV*` that was stored there (= `val`)).
Note that the caller is responsible for suitably incrementing the reference count of `val` before the call.
Approximate Perl equivalent: `splice(@myarray, $key, 1, $val)`.
```
SV** av_store_simple(AV *av, SSize_t key, SV *val)
```
Callback Functions
-------------------
`dowantarray` Implements the deprecated ["`GIMME`" in perlapi](perlapi#GIMME).
```
U8 dowantarray()
```
`leave_scope` Implements `LEAVE_SCOPE` which you should use instead.
```
void leave_scope(I32 base)
```
`pop_scope` Implements ["`LEAVE`" in perlapi](perlapi#LEAVE)
```
void pop_scope()
```
`push_scope` Implements ["`ENTER`" in perlapi](perlapi#ENTER)
```
void push_scope()
```
`save_adelete` Implements `SAVEADELETE`.
```
void save_adelete(AV *av, SSize_t key)
```
`save_generic_pvref` Implements `SAVEGENERICPV`.
Like save\_pptr(), but also Safefree()s the new value if it is different from the old one. Can be used to restore a global char\* to its prior contents, freeing new value.
```
void save_generic_pvref(char** str)
```
`save_generic_svref` Implements `SAVEGENERICSV`.
Like save\_sptr(), but also SvREFCNT\_dec()s the new value. Can be used to restore a global SV to its prior contents, freeing new value.
```
void save_generic_svref(SV** sptr)
```
`save_hdelete` Implements `SAVEHDELETE`.
```
void save_hdelete(HV *hv, SV *keysv)
```
`save_hints` Implements `SAVEHINTS`.
```
void save_hints()
```
`save_op` Implements `SAVEOP`.
```
void save_op()
```
`save_padsv_and_mortalize` Implements `SAVEPADSVANDMORTALIZE`.
```
void save_padsv_and_mortalize(PADOFFSET off)
```
`save_set_svflags` Implements `SAVESETSVFLAGS`.
Set the SvFLAGS specified by mask to the values in val
```
void save_set_svflags(SV *sv, U32 mask, U32 val)
```
`save_shared_pvref` Implements `SAVESHAREDPV`.
Like save\_generic\_pvref(), but uses PerlMemShared\_free() rather than Safefree(). Can be used to restore a shared global char\* to its prior contents, freeing new value.
```
void save_shared_pvref(char** str)
```
`save_vptr` Implements `SAVEVPTR`.
```
void save_vptr(void *ptr)
```
Casting
-------
There are only public API items currently in Casting
Character case changing
------------------------
There are only public API items currently in Character case changing
Character classification
-------------------------
There are only public API items currently in Character classification
Compiler and Preprocessor information
--------------------------------------
There are only public API items currently in Compiler and Preprocessor information
Compiler directives
--------------------
There are only public API items currently in Compiler directives
Compile-time scope hooks
-------------------------
`BhkENTRY` NOTE: `BhkENTRY` is **experimental** and may change or be removed without notice.
Return an entry from the BHK structure. `which` is a preprocessor token indicating which entry to return. If the appropriate flag is not set this will return `NULL`. The type of the return value depends on which entry you ask for.
```
void * BhkENTRY(BHK *hk, which)
```
`BhkFLAGS` NOTE: `BhkFLAGS` is **experimental** and may change or be removed without notice.
Return the BHK's flags.
```
U32 BhkFLAGS(BHK *hk)
```
`CALL_BLOCK_HOOKS` NOTE: `CALL_BLOCK_HOOKS` is **experimental** and may change or be removed without notice.
Call all the registered block hooks for type `which`. `which` is a preprocessing token; the type of `arg` depends on `which`.
```
void CALL_BLOCK_HOOKS(which, arg)
```
Concurrency
-----------
`CVf_SLABBED` `CvROOT` `CvSTART` Described in <perlguts>.
`CX_CUR` Described in <perlguts>.
```
CX_CUR()
```
`CXINC` Described in <perlguts>.
`CX_LEAVE_SCOPE` Described in <perlguts>.
```
void CX_LEAVE_SCOPE(PERL_CONTEXT* cx)
```
`CX_POP` Described in <perlguts>.
```
void CX_POP(PERL_CONTEXT* cx)
```
`cxstack` Described in <perlguts>.
`cxstack_ix` Described in <perlguts>.
`CXt_BLOCK` `CXt_EVAL` `CXt_FORMAT` `CXt_GIVEN` `CXt_LOOP_ARY` `CXt_LOOP_LAZYIV` `CXt_LOOP_LAZYSV` `CXt_LOOP_LIST` `CXt_LOOP_PLAIN` `CXt_NULL` `CXt_SUB` `CXt_SUBST` `CXt_WHEN` Described in <perlguts>.
`cx_type` Described in <perlguts>.
`dounwind` Described in <perlguts>.
```
void dounwind(I32 cxix)
```
`my_fork` This is for the use of `PerlProc_fork` as a wrapper for the C library [fork(2)](http://man.he.net/man2/fork) on some platforms to hide some platform quirks. It should not be used except through `PerlProc_fork`.
```
Pid_t my_fork()
```
`PERL_CONTEXT` Described in <perlguts>.
COPs and Hint Hashes
---------------------
There are only public API items currently in COPs and Hint Hashes
Custom Operators
-----------------
`core_prototype` This function assigns the prototype of the named core function to `sv`, or to a new mortal SV if `sv` is `NULL`. It returns the modified `sv`, or `NULL` if the core function has no prototype. `code` is a code as returned by `keyword()`. It must not be equal to 0.
```
SV * core_prototype(SV *sv, const char *name, const int code,
int * const opnum)
```
CV Handling
------------
`CvWEAKOUTSIDE` Each CV has a pointer, `CvOUTSIDE()`, to its lexically enclosing CV (if any). Because pointers to anonymous sub prototypes are stored in `&` pad slots, it is a possible to get a circular reference, with the parent pointing to the child and vice-versa. To avoid the ensuing memory leak, we do not increment the reference count of the CV pointed to by `CvOUTSIDE` in the *one specific instance* that the parent has a `&` pad slot pointing back to us. In this case, we set the `CvWEAKOUTSIDE` flag in the child. This allows us to determine under what circumstances we should decrement the refcount of the parent when freeing the child.
There is a further complication with non-closure anonymous subs (i.e. those that do not refer to any lexicals outside that sub). In this case, the anonymous prototype is shared rather than being cloned. This has the consequence that the parent may be freed while there are still active children, *e.g.*,
```
BEGIN { $a = sub { eval '$x' } }
```
In this case, the BEGIN is freed immediately after execution since there are no active references to it: the anon sub prototype has `CvWEAKOUTSIDE` set since it's not a closure, and $a points to the same CV, so it doesn't contribute to BEGIN's refcount either. When $a is executed, the `eval '$x'` causes the chain of `CvOUTSIDE`s to be followed, and the freed BEGIN is accessed.
To avoid this, whenever a CV and its associated pad is freed, any `&` entries in the pad are explicitly removed from the pad, and if the refcount of the pointed-to anon sub is still positive, then that child's `CvOUTSIDE` is set to point to its grandparent. This will only occur in the single specific case of a non-closure anon prototype having one or more active references (such as `$a` above).
One other thing to consider is that a CV may be merely undefined rather than freed, eg `undef &foo`. In this case, its refcount may not have reached zero, but we still delete its pad and its `CvROOT` etc. Since various children may still have their `CvOUTSIDE` pointing at this undefined CV, we keep its own `CvOUTSIDE` for the time being, so that the chain of lexical scopes is unbroken. For example, the following should print 123:
```
my $x = 123;
sub tmp { sub { eval '$x' } }
my $a = tmp();
undef &tmp;
print $a->();
```
```
bool CvWEAKOUTSIDE(CV *cv)
```
`docatch` Check for the cases 0 or 3 of cur\_env.je\_ret, only used inside an eval context.
0 is used as continue inside eval,
3 is used for a die caught by an inner eval - continue inner loop
See *cop.h*: je\_mustcatch, when set at any runlevel to TRUE, means eval ops must establish a local jmpenv to handle exception traps.
```
OP* docatch(Perl_ppaddr_t firstpp)
```
Debugging
---------
`_aDEPTH` Some functions when compiled under DEBUGGING take an extra final argument named `depth`, indicating the C stack depth. This argument is omitted otherwise. This macro expands to either `, depth` under DEBUGGING, or to nothing at all when not under DEBUGGING, reducing the number of `#ifdef`'s in the code.
The program is responsible for maintaining the correct value for `depth`.
```
_aDEPTH
```
`debop` Implements **-Dt** perl command line option on OP `o`.
```
I32 debop(const OP* o)
```
`debprof` Called to indicate that `o` was executed, for profiling purposes under the `-DP` command line option.
```
void debprof(const OP *o)
```
`debprofdump` Dumps the contents of the data collected by the `-DP` perl command line option.
```
void debprofdump()
```
`free_c_backtrace` Deallocates a backtrace received from get\_c\_backtrace.
```
void free_c_backtrace(Perl_c_backtrace* bt)
```
`get_c_backtrace` Collects the backtrace (aka "stacktrace") into a single linear malloced buffer, which the caller **must** `Perl_free_c_backtrace()`.
Scans the frames back by `depth + skip`, then drops the `skip` innermost, returning at most `depth` frames.
```
Perl_c_backtrace* get_c_backtrace(int max_depth, int skip)
```
`_pDEPTH` This is used in the prototype declarations for functions that take a ["`_aDEPTH`"](#_aDEPTH) final parameter, much like [`pTHX_`](perlguts#Background-and-MULTIPLICITY) is used in functions that take a thread context initial parameter.
`PL_DBsingle` When Perl is run in debugging mode, with the **-d** switch, this SV is a boolean which indicates whether subs are being single-stepped. Single-stepping is automatically turned on after every step. This is the C variable which corresponds to Perl's $DB::single variable. See `["PL\_DBsub"](#PL_DBsub)`.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
SV * PL_DBsingle
```
`PL_DBsub` When Perl is run in debugging mode, with the **-d** switch, this GV contains the SV which holds the name of the sub being debugged. This is the C variable which corresponds to Perl's $DB::sub variable. See `["PL\_DBsingle"](#PL_DBsingle)`.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
GV * PL_DBsub
```
`PL_DBtrace` Trace variable used when Perl is run in debugging mode, with the **-d** switch. This is the C variable which corresponds to Perl's $DB::trace variable. See `["PL\_DBsingle"](#PL_DBsingle)`.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
SV * PL_DBtrace
```
`runops_debug` Described in <perlguts>.
```
int runops_debug()
```
`runops_standard` Described in <perlguts>.
```
int runops_standard()
```
Display functions
------------------
`sv_peek` Implements `SvPEEK`
```
char* sv_peek(SV* sv)
```
Embedding, Threads, and Interpreter Cloning
--------------------------------------------
`cv_dump` dump the contents of a CV
```
void cv_dump(const CV *cv, const char *title)
```
`cv_forget_slab` When a CV has a reference count on its slab (`CvSLABBED`), it is responsible for making sure it is freed. (Hence, no two CVs should ever have a reference count on the same slab.) The CV only needs to reference the slab during compilation. Once it is compiled and `CvROOT` attached, it has finished its job, so it can forget the slab.
```
void cv_forget_slab(CV *cv)
```
`do_dump_pad` Dump the contents of a padlist
```
void do_dump_pad(I32 level, PerlIO *file, PADLIST *padlist,
int full)
```
`get_context` Implements ["`PERL_GET_CONTEXT`" in perlapi](perlapi#PERL_GET_CONTEXT), which you should use instead.
```
void* get_context()
```
`pad_alloc_name` Allocates a place in the currently-compiling pad (via ["pad\_alloc" in perlapi](perlapi#pad_alloc)) and then stores a name for that entry. `name` is adopted and becomes the name entry; it must already contain the name string. `typestash` and `ourstash` and the `padadd_STATE` flag get added to `name`. None of the other processing of ["pad\_add\_name\_pvn" in perlapi](perlapi#pad_add_name_pvn) is done. Returns the offset of the allocated pad slot.
```
PADOFFSET pad_alloc_name(PADNAME *name, U32 flags, HV *typestash,
HV *ourstash)
```
`pad_block_start` Update the pad compilation state variables on entry to a new block.
```
void pad_block_start(int full)
```
`pad_check_dup` Check for duplicate declarations: report any of:
```
* a 'my' in the current scope with the same name;
* an 'our' (anywhere in the pad) with the same name and the
same stash as 'ourstash'
```
`is_our` indicates that the name to check is an `"our"` declaration.
```
void pad_check_dup(PADNAME *name, U32 flags, const HV *ourstash)
```
`pad_findlex` Find a named lexical anywhere in a chain of nested pads. Add fake entries in the inner pads if it's found in an outer one.
Returns the offset in the bottom pad of the lex or the fake lex. `cv` is the CV in which to start the search, and seq is the current `cop_seq` to match against. If `warn` is true, print appropriate warnings. The `out_`\* vars return values, and so are pointers to where the returned values should be stored. `out_capture`, if non-null, requests that the innermost instance of the lexical is captured; `out_name` is set to the innermost matched pad name or fake pad name; `out_flags` returns the flags normally associated with the `PARENT_FAKELEX_FLAGS` field of a fake pad name.
Note that `pad_findlex()` is recursive; it recurses up the chain of CVs, then comes back down, adding fake entries as it goes. It has to be this way because fake names in anon prototypes have to store in `xpadn_low` the index into the parent pad.
```
PADOFFSET pad_findlex(const char *namepv, STRLEN namelen,
U32 flags, const CV* cv, U32 seq, int warn,
SV** out_capture, PADNAME** out_name,
int *out_flags)
```
`pad_fixup_inner_anons` For any anon CVs in the pad, change `CvOUTSIDE` of that CV from `old_cv` to `new_cv` if necessary. Needed when a newly-compiled CV has to be moved to a pre-existing CV struct.
```
void pad_fixup_inner_anons(PADLIST *padlist, CV *old_cv,
CV *new_cv)
```
`pad_free` Free the SV at offset po in the current pad.
```
void pad_free(PADOFFSET po)
```
`pad_leavemy` Cleanup at end of scope during compilation: set the max seq number for lexicals in this scope and warn of any lexicals that never got introduced.
```
OP * pad_leavemy()
```
`padlist_dup` Duplicates a pad.
```
PADLIST * padlist_dup(PADLIST *srcpad, CLONE_PARAMS *param)
```
`padname_dup` Duplicates a pad name.
```
PADNAME * padname_dup(PADNAME *src, CLONE_PARAMS *param)
```
`padnamelist_dup` Duplicates a pad name list.
```
PADNAMELIST * padnamelist_dup(PADNAMELIST *srcpad,
CLONE_PARAMS *param)
```
`pad_push` Push a new pad frame onto the padlist, unless there's already a pad at this depth, in which case don't bother creating a new one. Then give the new pad an `@_` in slot zero.
```
void pad_push(PADLIST *padlist, int depth)
```
`pad_reset` Mark all the current temporaries for reuse
```
void pad_reset()
```
`pad_setsv` Set the value at offset `po` in the current (compiling or executing) pad. Use the macro `PAD_SETSV()` rather than calling this function directly.
```
void pad_setsv(PADOFFSET po, SV* sv)
```
`pad_sv` Get the value at offset `po` in the current (compiling or executing) pad. Use macro `PAD_SV` instead of calling this function directly.
```
SV* pad_sv(PADOFFSET po)
```
`pad_swipe` Abandon the tmp in the current pad at offset `po` and replace with a new one.
```
void pad_swipe(PADOFFSET po, bool refadjust)
```
`set_context` Implements ["`PERL_SET_CONTEXT`" in perlapi](perlapi#PERL_SET_CONTEXT), which you should use instead.
```
void set_context(void *t)
```
Errno
-----
`dSAVEDERRNO` Declare variables needed to save `errno` and any operating system specific error number.
```
void dSAVEDERRNO
```
`dSAVE_ERRNO` Declare variables needed to save `errno` and any operating system specific error number, and save them for optional later restoration by `RESTORE_ERRNO`.
```
void dSAVE_ERRNO
```
`RESTORE_ERRNO` Restore `errno` and any operating system specific error number that was saved by `dSAVE_ERRNO` or `RESTORE_ERRNO`.
```
void RESTORE_ERRNO
```
`SAVE_ERRNO` Save `errno` and any operating system specific error number for optional later restoration by `RESTORE_ERRNO`. Requires `dSAVEDERRNO` or `dSAVE_ERRNO` in scope.
```
void SAVE_ERRNO
```
`SETERRNO` Set `errno`, and on VMS set `vaxc$errno`.
```
void SETERRNO(int errcode, int vmserrcode)
```
Exception Handling (simple) Macros
-----------------------------------
There are only public API items currently in Exception Handling (simple) Macros
Filesystem configuration values
--------------------------------
There are only public API items currently in Filesystem configuration values
Floating point
---------------
There are only public API items currently in Floating point
General Configuration
----------------------
There are only public API items currently in General Configuration
Global Variables
-----------------
There are only public API items currently in Global Variables
GV Handling and Stashes
------------------------
`gp_dup` Duplicate a typeglob, returning a pointer to the cloned object.
```
GP* gp_dup(GP *const gp, CLONE_PARAMS *const param)
```
`gv_handler` Implements `StashHANDLER`, which you should use instead
```
CV* gv_handler(HV* stash, I32 id)
```
`gv_stashsvpvn_cached` Returns a pointer to the stash for a specified package, possibly cached. Implements both ["`gv_stashpvn`" in perlapi](perlapi#gv_stashpvn) and ["`gv_stashsv`" in perlapi](perlapi#gv_stashsv).
Requires one of either `namesv` or `namepv` to be non-null.
If the flag `GV_CACHE_ONLY` is set, return the stash only if found in the cache; see ["`gv_stashpvn`" in perlapi](perlapi#gv_stashpvn) for details on the other `flags`.
Note it is strongly preferred for `namesv` to be non-null, for performance reasons.
```
HV* gv_stashsvpvn_cached(SV *namesv, const char* name,
U32 namelen, I32 flags)
```
`gv_try_downgrade` NOTE: `gv_try_downgrade` is **experimental** and may change or be removed without notice.
If the typeglob `gv` can be expressed more succinctly, by having something other than a real GV in its place in the stash, replace it with the optimised form. Basic requirements for this are that `gv` is a real typeglob, is sufficiently ordinary, and is only referenced from its package. This function is meant to be used when a GV has been looked up in part to see what was there, causing upgrading, but based on what was found it turns out that the real GV isn't required after all.
If `gv` is a completely empty typeglob, it is deleted from the stash.
If `gv` is a typeglob containing only a sufficiently-ordinary constant sub, the typeglob is replaced with a scalar-reference placeholder that more compactly represents the same thing.
```
void gv_try_downgrade(GV* gv)
```
Hook manipulation
------------------
There are only public API items currently in Hook manipulation
HV Handling
------------
`hv_eiter_p` Implements `HvEITER` which you should use instead.
NOTE: `hv_eiter_p` must be explicitly called as `Perl_hv_eiter_p` with an `aTHX_` parameter.
```
HE** Perl_hv_eiter_p(pTHX_ HV *hv)
```
`hv_eiter_set` Implements `HvEITER_set` which you should use instead.
NOTE: `hv_eiter_set` must be explicitly called as `Perl_hv_eiter_set` with an `aTHX_` parameter.
```
void Perl_hv_eiter_set(pTHX_ HV *hv, HE *eiter)
```
`hv_ename_add` Adds a name to a stash's internal list of effective names. See `["hv\_ename\_delete"](#hv_ename_delete)`.
This is called when a stash is assigned to a new location in the symbol table.
```
void hv_ename_add(HV *hv, const char *name, U32 len, U32 flags)
```
`hv_ename_delete` Removes a name from a stash's internal list of effective names. If this is the name returned by `HvENAME`, then another name in the list will take its place (`HvENAME` will use it).
This is called when a stash is deleted from the symbol table.
```
void hv_ename_delete(HV *hv, const char *name, U32 len,
U32 flags)
```
`hv_fill` Returns the number of hash buckets that happen to be in use.
This function implements the [`HvFILL` macro](perlapi#HvFILL) which you should use instead.
As of perl 5.25 this function is used only for debugging purposes, and the number of used hash buckets is not in any way cached, thus this function can be costly to execute as it must iterate over all the buckets in the hash.
NOTE: `hv_fill` must be explicitly called as `Perl_hv_fill` with an `aTHX_` parameter.
```
STRLEN Perl_hv_fill(pTHX_ HV *const hv)
```
`hv_placeholders_get` Implements `HvPLACEHOLDERS_get`, which you should use instead.
NOTE: `hv_placeholders_get` must be explicitly called as `Perl_hv_placeholders_get` with an `aTHX_` parameter.
```
I32 Perl_hv_placeholders_get(pTHX_ const HV *hv)
```
`hv_placeholders_set` Implements `HvPLACEHOLDERS_set`, which you should use instead.
NOTE: `hv_placeholders_set` must be explicitly called as `Perl_hv_placeholders_set` with an `aTHX_` parameter.
```
void Perl_hv_placeholders_set(pTHX_ HV *hv, I32 ph)
```
`hv_riter_p` Implements `HvRITER` which you should use instead.
NOTE: `hv_riter_p` must be explicitly called as `Perl_hv_riter_p` with an `aTHX_` parameter.
```
I32* Perl_hv_riter_p(pTHX_ HV *hv)
```
`hv_riter_set` Implements `HvRITER_set` which you should use instead.
NOTE: `hv_riter_set` must be explicitly called as `Perl_hv_riter_set` with an `aTHX_` parameter.
```
void Perl_hv_riter_set(pTHX_ HV *hv, I32 riter)
```
`refcounted_he_chain_2hv` Generates and returns a `HV *` representing the content of a `refcounted_he` chain. `flags` is currently unused and must be zero.
```
HV * refcounted_he_chain_2hv(const struct refcounted_he *c,
U32 flags)
```
`refcounted_he_fetch_pv` Like ["refcounted\_he\_fetch\_pvn"](#refcounted_he_fetch_pvn), but takes a nul-terminated string instead of a string/length pair.
```
SV * refcounted_he_fetch_pv(const struct refcounted_he *chain,
const char *key, U32 hash, U32 flags)
```
`refcounted_he_fetch_pvn` Search along a `refcounted_he` chain for an entry with the key specified by `keypv` and `keylen`. If `flags` has the `REFCOUNTED_HE_KEY_UTF8` bit set, the key octets are interpreted as UTF-8, otherwise they are interpreted as Latin-1. `hash` is a precomputed hash of the key string, or zero if it has not been precomputed. Returns a mortal scalar representing the value associated with the key, or `&PL_sv_placeholder` if there is no value associated with the key.
```
SV * refcounted_he_fetch_pvn(const struct refcounted_he *chain,
const char *keypv, STRLEN keylen,
U32 hash, U32 flags)
```
`refcounted_he_fetch_pvs` Like ["refcounted\_he\_fetch\_pvn"](#refcounted_he_fetch_pvn), but takes a literal string instead of a string/length pair, and no precomputed hash.
```
SV * refcounted_he_fetch_pvs(const struct refcounted_he *chain,
"key", U32 flags)
```
`refcounted_he_fetch_sv` Like ["refcounted\_he\_fetch\_pvn"](#refcounted_he_fetch_pvn), but takes a Perl scalar instead of a string/length pair.
```
SV * refcounted_he_fetch_sv(const struct refcounted_he *chain,
SV *key, U32 hash, U32 flags)
```
`refcounted_he_free` Decrements the reference count of a `refcounted_he` by one. If the reference count reaches zero the structure's memory is freed, which (recursively) causes a reduction of its parent `refcounted_he`'s reference count. It is safe to pass a null pointer to this function: no action occurs in this case.
```
void refcounted_he_free(struct refcounted_he *he)
```
`refcounted_he_inc` Increment the reference count of a `refcounted_he`. The pointer to the `refcounted_he` is also returned. It is safe to pass a null pointer to this function: no action occurs and a null pointer is returned.
```
struct refcounted_he * refcounted_he_inc(
struct refcounted_he *he)
```
`refcounted_he_new_pv` Like ["refcounted\_he\_new\_pvn"](#refcounted_he_new_pvn), but takes a nul-terminated string instead of a string/length pair.
```
struct refcounted_he * refcounted_he_new_pv(
struct refcounted_he *parent,
const char *key, U32 hash,
SV *value, U32 flags)
```
`refcounted_he_new_pvn` Creates a new `refcounted_he`. This consists of a single key/value pair and a reference to an existing `refcounted_he` chain (which may be empty), and thus forms a longer chain. When using the longer chain, the new key/value pair takes precedence over any entry for the same key further along the chain.
The new key is specified by `keypv` and `keylen`. If `flags` has the `REFCOUNTED_HE_KEY_UTF8` bit set, the key octets are interpreted as UTF-8, otherwise they are interpreted as Latin-1. `hash` is a precomputed hash of the key string, or zero if it has not been precomputed.
`value` is the scalar value to store for this key. `value` is copied by this function, which thus does not take ownership of any reference to it, and later changes to the scalar will not be reflected in the value visible in the `refcounted_he`. Complex types of scalar will not be stored with referential integrity, but will be coerced to strings. `value` may be either null or `&PL_sv_placeholder` to indicate that no value is to be associated with the key; this, as with any non-null value, takes precedence over the existence of a value for the key further along the chain.
`parent` points to the rest of the `refcounted_he` chain to be attached to the new `refcounted_he`. This function takes ownership of one reference to `parent`, and returns one reference to the new `refcounted_he`.
```
struct refcounted_he * refcounted_he_new_pvn(
struct refcounted_he *parent,
const char *keypv,
STRLEN keylen, U32 hash,
SV *value, U32 flags)
```
`refcounted_he_new_pvs` Like ["refcounted\_he\_new\_pvn"](#refcounted_he_new_pvn), but takes a literal string instead of a string/length pair, and no precomputed hash.
```
struct refcounted_he * refcounted_he_new_pvs(
struct refcounted_he *parent,
"key", SV *value, U32 flags)
```
`refcounted_he_new_sv` Like ["refcounted\_he\_new\_pvn"](#refcounted_he_new_pvn), but takes a Perl scalar instead of a string/length pair.
```
struct refcounted_he * refcounted_he_new_sv(
struct refcounted_he *parent,
SV *key, U32 hash, SV *value,
U32 flags)
```
`unsharepvn` If no one has access to shared string `str` with length `len`, free it.
`len` and `hash` must both be valid for `str`.
```
void unsharepvn(const char* sv, I32 len, U32 hash)
```
Input/Output
-------------
`dirp_dup` Duplicate a directory handle, returning a pointer to the cloned object.
```
DIR* dirp_dup(DIR *const dp, CLONE_PARAMS *const param)
```
`fp_dup` Duplicate a file handle, returning a pointer to the cloned object.
```
PerlIO* fp_dup(PerlIO *const fp, const char type,
CLONE_PARAMS *const param)
```
`my_fflush_all` Implements `PERL_FLUSHALL_FOR_CHILD` on some platforms.
```
I32 my_fflush_all()
```
`my_mkostemp` The C library `[mkostemp(3)](http://man.he.net/man3/mkostemp)` if available, or a Perl implementation of it.
NOTE: `my_mkostemp` must be explicitly called as `Perl_my_mkostemp` .
```
int Perl_my_mkostemp(char *templte, int flags)
```
`my_mkstemp` The C library `[mkstemp(3)](http://man.he.net/man3/mkstemp)` if available, or a Perl implementation of it.
NOTE: `my_mkstemp` must be explicitly called as `Perl_my_mkstemp` .
```
int Perl_my_mkstemp(char *templte)
```
`PL_last_in_gv` The GV which was last used for a filehandle input operation. (`<FH>`)
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
GV* PL_last_in_gv
```
`PL_ofsgv` The glob containing the output field separator - `*,` in Perl space.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
GV* PL_ofsgv
```
`PL_rs` The input record separator - `$/` in Perl space.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
SV* PL_rs
```
`start_glob` NOTE: `start_glob` is **experimental** and may change or be removed without notice.
Function called by `do_readline` to spawn a glob (or do the glob inside perl on VMS). This code used to be inline, but now perl uses `File::Glob` this glob starter is only used by miniperl during the build process, or when PERL\_EXTERNAL\_GLOB is defined. Moving it away shrinks *pp\_hot.c*; shrinking *pp\_hot.c* helps speed perl up.
NOTE: `start_glob` must be explicitly called as `Perl_start_glob` with an `aTHX_` parameter.
```
PerlIO* Perl_start_glob(pTHX_ SV *tmpglob, IO *io)
```
Integer
-------
There are only public API items currently in Integer
I/O Formats
------------
There are only public API items currently in I/O Formats
Lexer interface
----------------
`validate_proto` NOTE: `validate_proto` is **experimental** and may change or be removed without notice.
This function performs syntax checking on a prototype, `proto`. If `warn` is true, any illegal characters or mismatched brackets will trigger illegalproto warnings, declaring that they were detected in the prototype for `name`.
The return value is `true` if this is a valid prototype, and `false` if it is not, regardless of whether `warn` was `true` or `false`.
Note that `NULL` is a valid `proto` and will always return `true`.
```
bool validate_proto(SV *name, SV *proto, bool warn,
bool curstash)
```
Locales
-------
There are only public API items currently in Locales
Magic
-----
`magic_clearhint` Triggered by a delete from `%^H`, records the key to `PL_compiling.cop_hints_hash`.
```
int magic_clearhint(SV* sv, MAGIC* mg)
```
`magic_clearhints` Triggered by clearing `%^H`, resets `PL_compiling.cop_hints_hash`.
```
int magic_clearhints(SV* sv, MAGIC* mg)
```
`magic_methcall` Invoke a magic method (like FETCH).
`sv` and `mg` are the tied thingy and the tie magic.
`meth` is the name of the method to call.
`argc` is the number of args (in addition to $self) to pass to the method.
The `flags` can be:
```
G_DISCARD invoke method with G_DISCARD flag and don't
return a value
G_UNDEF_FILL fill the stack with argc pointers to
PL_sv_undef
```
The arguments themselves are any values following the `flags` argument.
Returns the SV (if any) returned by the method, or `NULL` on failure.
NOTE: `magic_methcall` must be explicitly called as `Perl_magic_methcall` with an `aTHX_` parameter.
```
SV* Perl_magic_methcall(pTHX_ SV *sv, const MAGIC *mg, SV *meth,
U32 flags, U32 argc, ...)
```
`magic_sethint` Triggered by a store to `%^H`, records the key/value pair to `PL_compiling.cop_hints_hash`. It is assumed that hints aren't storing anything that would need a deep copy. Maybe we should warn if we find a reference.
```
int magic_sethint(SV* sv, MAGIC* mg)
```
`mg_dup` Duplicate a chain of magic, returning a pointer to the cloned object.
```
MAGIC* mg_dup(MAGIC *mg, CLONE_PARAMS *const param)
```
`mg_localize` Copy some of the magic from an existing SV to new localized version of that SV. Container magic (*e.g.*, `%ENV`, `$1`, `tie`) gets copied, value magic doesn't (*e.g.*, `taint`, `pos`).
If `setmagic` is false then no set magic will be called on the new (empty) SV. This typically means that assignment will soon follow (e.g. `'local $x = $y'`), and that will handle the magic.
```
void mg_localize(SV* sv, SV* nsv, bool setmagic)
```
`si_dup` Duplicate a stack info structure, returning a pointer to the cloned object.
```
PERL_SI* si_dup(PERL_SI* si, CLONE_PARAMS* param)
```
`ss_dup` Duplicate the save stack, returning a pointer to the cloned object.
```
ANY* ss_dup(PerlInterpreter* proto_perl, CLONE_PARAMS* param)
```
Memory Management
------------------
`calloc` Implements ["`Newxz`" in perlapi](perlapi#Newxz) which you should use instead.
NOTE: `calloc` must be explicitly called as `Perl_calloc` .
```
Malloc_t Perl_calloc(MEM_SIZE elements, MEM_SIZE size)
```
`malloc` Implements ["`Newx`" in perlapi](perlapi#Newx) which you should use instead.
NOTE: `malloc` must be explicitly called as `Perl_malloc` .
```
Malloc_t Perl_malloc(MEM_SIZE nbytes)
```
`mfree` Implements ["`Safefree`" in perlapi](perlapi#Safefree) which you should use instead.
NOTE: `mfree` must be explicitly called as `Perl_mfree` .
```
Free_t Perl_mfree(Malloc_t where)
```
`realloc` Implements ["`Renew`" in perlapi](perlapi#Renew) which you should use instead.
NOTE: `realloc` must be explicitly called as `Perl_realloc` .
```
Malloc_t Perl_realloc(Malloc_t where, MEM_SIZE nbytes)
```
MRO
---
`mro_get_linear_isa_dfs` Returns the Depth-First Search linearization of `@ISA` the given stash. The return value is a read-only AV\*. `level` should be 0 (it is used internally in this function's recursion).
You are responsible for `SvREFCNT_inc()` on the return value if you plan to store it anywhere semi-permanently (otherwise it might be deleted out from under you the next time the cache is invalidated).
```
AV* mro_get_linear_isa_dfs(HV* stash, U32 level)
```
`mro_isa_changed_in` Takes the necessary steps (cache invalidations, mostly) when the `@ISA` of the given package has changed. Invoked by the `setisa` magic, should not need to invoke directly.
```
void mro_isa_changed_in(HV* stash)
```
`mro_package_moved` Call this function to signal to a stash that it has been assigned to another spot in the stash hierarchy. `stash` is the stash that has been assigned. `oldstash` is the stash it replaces, if any. `gv` is the glob that is actually being assigned to.
This can also be called with a null first argument to indicate that `oldstash` has been deleted.
This function invalidates isa caches on the old stash, on all subpackages nested inside it, and on the subclasses of all those, including non-existent packages that have corresponding entries in `stash`.
It also sets the effective names (`HvENAME`) on all the stashes as appropriate.
If the `gv` is present and is not in the symbol table, then this function simply returns. This checked will be skipped if `flags & 1`.
```
void mro_package_moved(HV * const stash, HV * const oldstash,
const GV * const gv, U32 flags)
```
Multicall Functions
--------------------
There are only public API items currently in Multicall Functions
Numeric Functions
------------------
`isinfnansv` Checks whether the argument would be either an infinity or `NaN` when used as a number, but is careful not to trigger non-numeric or uninitialized warnings. it assumes the caller has done `SvGETMAGIC(sv)` already.
Note that this always accepts trailing garbage (similar to `grok_number_flags` with `PERL_SCAN_TRAILING`), so `"inferior"` and `"NAND gates"` will return true.
```
bool isinfnansv(SV *sv)
```
Optrees
-------
`finalize_optree` This function finalizes the optree. Should be called directly after the complete optree is built. It does some additional checking which can't be done in the normal `ck_`xxx functions and makes the tree thread-safe.
```
void finalize_optree(OP* o)
```
`newATTRSUB_x` Construct a Perl subroutine, also performing some surrounding jobs.
This function is expected to be called in a Perl compilation context, and some aspects of the subroutine are taken from global variables associated with compilation. In particular, `PL_compcv` represents the subroutine that is currently being compiled. It must be non-null when this function is called, and some aspects of the subroutine being constructed are taken from it. The constructed subroutine may actually be a reuse of the `PL_compcv` object, but will not necessarily be so.
If `block` is null then the subroutine will have no body, and for the time being it will be an error to call it. This represents a forward subroutine declaration such as `sub foo ($$);`. If `block` is non-null then it provides the Perl code of the subroutine body, which will be executed when the subroutine is called. This body includes any argument unwrapping code resulting from a subroutine signature or similar. The pad use of the code must correspond to the pad attached to `PL_compcv`. The code is not expected to include a `leavesub` or `leavesublv` op; this function will add such an op. `block` is consumed by this function and will become part of the constructed subroutine.
`proto` specifies the subroutine's prototype, unless one is supplied as an attribute (see below). If `proto` is null, then the subroutine will not have a prototype. If `proto` is non-null, it must point to a `const` op whose value is a string, and the subroutine will have that string as its prototype. If a prototype is supplied as an attribute, the attribute takes precedence over `proto`, but in that case `proto` should preferably be null. In any case, `proto` is consumed by this function.
`attrs` supplies attributes to be applied the subroutine. A handful of attributes take effect by built-in means, being applied to `PL_compcv` immediately when seen. Other attributes are collected up and attached to the subroutine by this route. `attrs` may be null to supply no attributes, or point to a `const` op for a single attribute, or point to a `list` op whose children apart from the `pushmark` are `const` ops for one or more attributes. Each `const` op must be a string, giving the attribute name optionally followed by parenthesised arguments, in the manner in which attributes appear in Perl source. The attributes will be applied to the sub by this function. `attrs` is consumed by this function.
If `o_is_gv` is false and `o` is null, then the subroutine will be anonymous. If `o_is_gv` is false and `o` is non-null, then `o` must point to a `const` OP, which will be consumed by this function, and its string value supplies a name for the subroutine. The name may be qualified or unqualified, and if it is unqualified then a default stash will be selected in some manner. If `o_is_gv` is true, then `o` doesn't point to an `OP` at all, but is instead a cast pointer to a `GV` by which the subroutine will be named.
If there is already a subroutine of the specified name, then the new sub will either replace the existing one in the glob or be merged with the existing one. A warning may be generated about redefinition.
If the subroutine has one of a few special names, such as `BEGIN` or `END`, then it will be claimed by the appropriate queue for automatic running of phase-related subroutines. In this case the relevant glob will be left not containing any subroutine, even if it did contain one before. In the case of `BEGIN`, the subroutine will be executed and the reference to it disposed of before this function returns.
The function returns a pointer to the constructed subroutine. If the sub is anonymous then ownership of one counted reference to the subroutine is transferred to the caller. If the sub is named then the caller does not get ownership of a reference. In most such cases, where the sub has a non-phase name, the sub will be alive at the point it is returned by virtue of being contained in the glob that names it. A phase-named subroutine will usually be alive by virtue of the reference owned by the phase's automatic run queue. But a `BEGIN` subroutine, having already been executed, will quite likely have been destroyed already by the time this function returns, making it erroneous for the caller to make any use of the returned pointer. It is the caller's responsibility to ensure that it knows which of these situations applies.
```
CV* newATTRSUB_x(I32 floor, OP *o, OP *proto, OP *attrs,
OP *block, bool o_is_gv)
```
`newXS_len_flags` Construct an XS subroutine, also performing some surrounding jobs.
The subroutine will have the entry point `subaddr`. It will have the prototype specified by the nul-terminated string `proto`, or no prototype if `proto` is null. The prototype string is copied; the caller can mutate the supplied string afterwards. If `filename` is non-null, it must be a nul-terminated filename, and the subroutine will have its `CvFILE` set accordingly. By default `CvFILE` is set to point directly to the supplied string, which must be static. If `flags` has the `XS_DYNAMIC_FILENAME` bit set, then a copy of the string will be taken instead.
Other aspects of the subroutine will be left in their default state. If anything else needs to be done to the subroutine for it to function correctly, it is the caller's responsibility to do that after this function has constructed it. However, beware of the subroutine potentially being destroyed before this function returns, as described below.
If `name` is null then the subroutine will be anonymous, with its `CvGV` referring to an `__ANON__` glob. If `name` is non-null then the subroutine will be named accordingly, referenced by the appropriate glob. `name` is a string of length `len` bytes giving a sigilless symbol name, in UTF-8 if `flags` has the `SVf_UTF8` bit set and in Latin-1 otherwise. The name may be either qualified or unqualified, with the stash defaulting in the same manner as for `gv_fetchpvn_flags`. `flags` may contain flag bits understood by `gv_fetchpvn_flags` with the same meaning as they have there, such as `GV_ADDWARN`. The symbol is always added to the stash if necessary, with `GV_ADDMULTI` semantics.
If there is already a subroutine of the specified name, then the new sub will replace the existing one in the glob. A warning may be generated about the redefinition. If the old subroutine was `CvCONST` then the decision about whether to warn is influenced by an expectation about whether the new subroutine will become a constant of similar value. That expectation is determined by `const_svp`. (Note that the call to this function doesn't make the new subroutine `CvCONST` in any case; that is left to the caller.) If `const_svp` is null then it indicates that the new subroutine will not become a constant. If `const_svp` is non-null then it indicates that the new subroutine will become a constant, and it points to an `SV*` that provides the constant value that the subroutine will have.
If the subroutine has one of a few special names, such as `BEGIN` or `END`, then it will be claimed by the appropriate queue for automatic running of phase-related subroutines. In this case the relevant glob will be left not containing any subroutine, even if it did contain one before. In the case of `BEGIN`, the subroutine will be executed and the reference to it disposed of before this function returns, and also before its prototype is set. If a `BEGIN` subroutine would not be sufficiently constructed by this function to be ready for execution then the caller must prevent this happening by giving the subroutine a different name.
The function returns a pointer to the constructed subroutine. If the sub is anonymous then ownership of one counted reference to the subroutine is transferred to the caller. If the sub is named then the caller does not get ownership of a reference. In most such cases, where the sub has a non-phase name, the sub will be alive at the point it is returned by virtue of being contained in the glob that names it. A phase-named subroutine will usually be alive by virtue of the reference owned by the phase's automatic run queue. But a `BEGIN` subroutine, having already been executed, will quite likely have been destroyed already by the time this function returns, making it erroneous for the caller to make any use of the returned pointer. It is the caller's responsibility to ensure that it knows which of these situations applies.
```
CV * newXS_len_flags(const char *name, STRLEN len,
XSUBADDR_t subaddr,
const char *const filename,
const char *const proto, SV **const_svp,
U32 flags)
```
`op_refcnt_lock` Implements the `OP_REFCNT_LOCK` macro which you should use instead.
```
void op_refcnt_lock()
```
`op_refcnt_unlock` Implements the `OP_REFCNT_UNLOCK` macro which you should use instead.
```
void op_refcnt_unlock()
```
`optimize_optree` This function applies some optimisations to the optree in top-down order. It is called before the peephole optimizer, which processes ops in execution order. Note that finalize\_optree() also does a top-down scan, but is called \*after\* the peephole optimizer.
```
void optimize_optree(OP* o)
```
`traverse_op_tree` Return the next op in a depth-first traversal of the op tree, returning NULL when the traversal is complete.
The initial call must supply the root of the tree as both top and o.
For now it's static, but it may be exposed to the API in the future.
```
OP* traverse_op_tree(OP* top, OP* o)
```
Pack and Unpack
----------------
There are only public API items currently in Pack and Unpack
Pad Data Structures
--------------------
`CX_CURPAD_SAVE` Save the current pad in the given context block structure.
```
void CX_CURPAD_SAVE(struct context)
```
`CX_CURPAD_SV` Access the SV at offset `po` in the saved current pad in the given context block structure (can be used as an lvalue).
```
SV * CX_CURPAD_SV(struct context, PADOFFSET po)
```
`PAD_BASE_SV` Get the value from slot `po` in the base (DEPTH=1) pad of a padlist
```
SV * PAD_BASE_SV(PADLIST padlist, PADOFFSET po)
```
`PAD_CLONE_VARS` Clone the state variables associated with running and compiling pads.
```
void PAD_CLONE_VARS(PerlInterpreter *proto_perl,
CLONE_PARAMS* param)
```
`PAD_COMPNAME_FLAGS` Return the flags for the current compiling pad name at offset `po`. Assumes a valid slot entry.
```
U32 PAD_COMPNAME_FLAGS(PADOFFSET po)
```
`PAD_COMPNAME_GEN` The generation number of the name at offset `po` in the current compiling pad (lvalue).
```
STRLEN PAD_COMPNAME_GEN(PADOFFSET po)
```
`PAD_COMPNAME_GEN_set` Sets the generation number of the name at offset `po` in the current ling pad (lvalue) to `gen`.
```
STRLEN PAD_COMPNAME_GEN_set(PADOFFSET po, int gen)
```
`PAD_COMPNAME_OURSTASH` Return the stash associated with an `our` variable. Assumes the slot entry is a valid `our` lexical.
```
HV * PAD_COMPNAME_OURSTASH(PADOFFSET po)
```
`PAD_COMPNAME_PV` Return the name of the current compiling pad name at offset `po`. Assumes a valid slot entry.
```
char * PAD_COMPNAME_PV(PADOFFSET po)
```
`PAD_COMPNAME_TYPE` Return the type (stash) of the current compiling pad name at offset `po`. Must be a valid name. Returns null if not typed.
```
HV * PAD_COMPNAME_TYPE(PADOFFSET po)
```
`PadnameIsOUR` Whether this is an "our" variable.
```
bool PadnameIsOUR(PADNAME * pn)
```
`PadnameIsSTATE` Whether this is a "state" variable.
```
bool PadnameIsSTATE(PADNAME * pn)
```
`PadnameOURSTASH` The stash in which this "our" variable was declared.
```
HV * PadnameOURSTASH(PADNAME * pn)
```
`PadnameOUTER` Whether this entry belongs to an outer pad. Entries for which this is true are often referred to as 'fake'.
```
bool PadnameOUTER(PADNAME * pn)
```
`PadnameTYPE` The stash associated with a typed lexical. This returns the `%Foo::` hash for `my Foo $bar`.
```
HV * PadnameTYPE(PADNAME * pn)
```
`PAD_RESTORE_LOCAL` Restore the old pad saved into the local variable `opad` by `PAD_SAVE_LOCAL()`
```
void PAD_RESTORE_LOCAL(PAD *opad)
```
`PAD_SAVE_LOCAL` Save the current pad to the local variable `opad`, then make the current pad equal to `npad`
```
void PAD_SAVE_LOCAL(PAD *opad, PAD *npad)
```
`PAD_SAVE_SETNULLPAD` Save the current pad then set it to null.
```
void PAD_SAVE_SETNULLPAD()
```
`PAD_SETSV` Set the slot at offset `po` in the current pad to `sv`
```
SV * PAD_SETSV(PADOFFSET po, SV* sv)
```
`PAD_SET_CUR` Set the current pad to be pad `n` in the padlist, saving the previous current pad. NB currently this macro expands to a string too long for some compilers, so it's best to replace it with
```
SAVECOMPPAD();
PAD_SET_CUR_NOSAVE(padlist,n);
```
```
void PAD_SET_CUR(PADLIST padlist, I32 n)
```
`PAD_SET_CUR_NOSAVE` like PAD\_SET\_CUR, but without the save
```
void PAD_SET_CUR_NOSAVE(PADLIST padlist, I32 n)
```
`PAD_SV` Get the value at offset `po` in the current pad
```
SV * PAD_SV(PADOFFSET po)
```
`PAD_SVl` Lightweight and lvalue version of `PAD_SV`. Get or set the value at offset `po` in the current pad. Unlike `PAD_SV`, does not print diagnostics with -DX. For internal use only.
```
SV * PAD_SVl(PADOFFSET po)
```
`SAVECLEARSV` Clear the pointed to pad value on scope exit. (i.e. the runtime action of `my`)
```
void SAVECLEARSV(SV **svp)
```
`SAVECOMPPAD` save `PL_comppad` and `PL_curpad`
```
void SAVECOMPPAD()
```
`SAVEPADSV` Save a pad slot (used to restore after an iteration)
```
void SAVEPADSV(PADOFFSET po)
```
Password and Group access
--------------------------
There are only public API items currently in Password and Group access
Paths to system commands
-------------------------
There are only public API items currently in Paths to system commands
Prototype information
----------------------
There are only public API items currently in Prototype information
REGEXP Functions
-----------------
`regnode` Described in <perlreguts>.
Reports and Formats
--------------------
There are only public API items currently in Reports and Formats
Signals
-------
There are only public API items currently in Signals
Site configuration
-------------------
There are only public API items currently in Site configuration
Sockets configuration values
-----------------------------
There are only public API items currently in Sockets configuration values
Source Filters
---------------
There are only public API items currently in Source Filters
Stack Manipulation Macros
--------------------------
`djSP` Declare Just `SP`. This is actually identical to `dSP`, and declares a local copy of perl's stack pointer, available via the `SP` macro. See `["SP" in perlapi](perlapi#SP)`. (Available for backward source code compatibility with the old (Perl 5.005) thread model.)
```
djSP();
```
`LVRET` True if this op will be the return value of an lvalue subroutine
`save_alloc` Implements ["`SSNEW`" in perlapi](perlapi#SSNEW) and kin, which should be used instead of this function.
```
I32 save_alloc(I32 size, I32 pad)
```
String Handling
----------------
`delimcpy_no_escape` Copy a source buffer to a destination buffer, stopping at (but not including) the first occurrence in the source of the delimiter byte, `delim`. The source is the bytes between `from` and `from_end` - 1. Similarly, the dest is `to` up to `to_end`.
The number of bytes copied is written to `*retlen`.
Returns the position of `delim` in the `from` buffer, but if there is no such occurrence before `from_end`, then `from_end` is returned, and the entire buffer `from` .. `from_end` - 1 is copied.
If there is room in the destination available after the copy, an extra terminating safety `NUL` byte is appended (not included in the returned length).
The error case is if the destination buffer is not large enough to accommodate everything that should be copied. In this situation, a value larger than `to_end` - `to` is written to `*retlen`, and as much of the source as fits will be written to the destination. Not having room for the safety `NUL` is not considered an error.
```
char* delimcpy_no_escape(char* to, const char* to_end,
const char* from, const char* from_end,
const int delim, I32* retlen)
```
`my_cxt_init` Implements the ["`MY_CXT_INIT`" in perlxs](perlxs#MY_CXT_INIT) macro, which you should use instead.
The first time a module is loaded, the global `PL_my_cxt_index` is incremented, and that value is assigned to that module's static `my_cxt_index` (whose address is passed as an arg). Then, for each interpreter this function is called for, it makes sure a `void*` slot is available to hang the static data off, by allocating or extending the interpreter's `PL_my_cxt_list` array
NOTE: `my_cxt_init` must be explicitly called as `Perl_my_cxt_init` with an `aTHX_` parameter.
```
void* Perl_my_cxt_init(pTHX_ int *indexp, size_t size)
```
`quadmath_format_needed` `quadmath_format_needed()` returns true if the `format` string seems to contain at least one non-Q-prefixed `%[efgaEFGA]` format specifier, or returns false otherwise.
The format specifier detection is not complete printf-syntax detection, but it should catch most common cases.
If true is returned, those arguments **should** in theory be processed with `quadmath_snprintf()`, but in case there is more than one such format specifier (see ["quadmath\_format\_valid"](#quadmath_format_valid)), and if there is anything else beyond that one (even just a single byte), they **cannot** be processed because `quadmath_snprintf()` is very strict, accepting only one format spec, and nothing else. In this case, the code should probably fail.
```
bool quadmath_format_needed(const char* format)
```
`quadmath_format_valid` `quadmath_snprintf()` is very strict about its `format` string and will fail, returning -1, if the format is invalid. It accepts exactly one format spec.
`quadmath_format_valid()` checks that the intended single spec looks sane: begins with `%`, has only one `%`, ends with `[efgaEFGA]`, and has `Q` before it. This is not a full "printf syntax check", just the basics.
Returns true if it is valid, false if not.
See also ["quadmath\_format\_needed"](#quadmath_format_needed).
```
bool quadmath_format_valid(const char* format)
```
SV Flags
---------
`SVt_INVLIST` Type flag for scalars. See ["svtype" in perlapi](perlapi#svtype).
SV Handling
------------
`PL_Sv` A scratch pad SV for whatever temporary use you need. Chiefly used as a fallback by macros on platforms where ["PERL\_USE\_GCC\_BRACE\_GROUPS" in perlapi](perlapi#PERL_USE_GCC_BRACE_GROUPS)> is unavailable, and which would otherwise evaluate their SV parameter more than once.
```
PL_Sv
```
`sv_2bool` This macro is only used by `sv_true()` or its macro equivalent, and only if the latter's argument is neither `SvPOK`, `SvIOK` nor `SvNOK`. It calls `sv_2bool_flags` with the `SV_GMAGIC` flag.
```
bool sv_2bool(SV *const sv)
```
`sv_2bool_flags` This function is only used by `sv_true()` and friends, and only if the latter's argument is neither `SvPOK`, `SvIOK` nor `SvNOK`. If the flags contain `SV_GMAGIC`, then it does an `mg_get()` first.
```
bool sv_2bool_flags(SV *sv, I32 flags)
```
`sv_2num` NOTE: `sv_2num` is **experimental** and may change or be removed without notice.
Return an SV with the numeric value of the source SV, doing any necessary reference or overload conversion. The caller is expected to have handled get-magic already.
```
SV* sv_2num(SV *const sv)
```
`sv_2pvbyte_nolen` Return a pointer to the byte-encoded representation of the SV. May cause the SV to be downgraded from UTF-8 as a side-effect.
Usually accessed via the `SvPVbyte_nolen` macro.
```
char* sv_2pvbyte_nolen(SV* sv)
```
`sv_2pvutf8_nolen` Return a pointer to the UTF-8-encoded representation of the SV. May cause the SV to be upgraded to UTF-8 as a side-effect.
Usually accessed via the `SvPVutf8_nolen` macro.
```
char* sv_2pvutf8_nolen(SV* sv)
```
`sv_2pv_nolen` Like `sv_2pv()`, but doesn't return the length too. You should usually use the macro wrapper `SvPV_nolen(sv)` instead.
```
char* sv_2pv_nolen(SV* sv)
```
`sv_add_arena` Given a chunk of memory, link it to the head of the list of arenas, and split it into a list of free SVs.
```
void sv_add_arena(char *const ptr, const U32 size,
const U32 flags)
```
`sv_clean_all` Decrement the refcnt of each remaining SV, possibly triggering a cleanup. This function may have to be called multiple times to free SVs which are in complex self-referential hierarchies.
```
I32 sv_clean_all()
```
`sv_clean_objs` Attempt to destroy all objects not yet freed.
```
void sv_clean_objs()
```
`sv_free_arenas` Deallocate the memory used by all arenas. Note that all the individual SV heads and bodies within the arenas must already have been freed.
```
void sv_free_arenas()
```
`sv_grow` Expands the character buffer in the SV. If necessary, uses `sv_unref` and upgrades the SV to `SVt_PV`. Returns a pointer to the character buffer. Use the `SvGROW` wrapper instead.
```
char* sv_grow(SV *const sv, STRLEN newlen)
```
`sv_grow_fresh` A cut-down version of sv\_grow intended only for when sv is a freshly-minted SVt\_PV, SVt\_PVIV, SVt\_PVNV, or SVt\_PVMG. i.e. sv has the default flags, has never been any other type, and does not have an existing string. Basically, just assigns a char buffer and returns a pointer to it.
```
char* sv_grow_fresh(SV *const sv, STRLEN newlen)
```
`sv_iv` `**DEPRECATED!**` It is planned to remove `sv_iv` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvIVx` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
IV sv_iv(SV* sv)
```
`sv_newref` Increment an SV's reference count. Use the `SvREFCNT_inc()` wrapper instead.
```
SV* sv_newref(SV *const sv)
```
`sv_nv` `**DEPRECATED!**` It is planned to remove `sv_nv` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvNVx` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
NV sv_nv(SV* sv)
```
`sv_pv` Use the `SvPV_nolen` macro instead
```
char* sv_pv(SV *sv)
```
`sv_pvbyte` Use `SvPVbyte_nolen` instead.
```
char* sv_pvbyte(SV *sv)
```
`sv_pvbyten` `**DEPRECATED!**` It is planned to remove `sv_pvbyten` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvPVbyte` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
char* sv_pvbyten(SV *sv, STRLEN *lp)
```
`sv_pvbyten_force` The backend for the `SvPVbytex_force` macro. Always use the macro instead. If the SV cannot be downgraded from UTF-8, this croaks.
```
char* sv_pvbyten_force(SV *const sv, STRLEN *const lp)
```
`sv_pvn` `**DEPRECATED!**` It is planned to remove `sv_pvn` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvPV` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
char* sv_pvn(SV *sv, STRLEN *lp)
```
`sv_pvn_force` Get a sensible string out of the SV somehow. A private implementation of the `SvPV_force` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
char* sv_pvn_force(SV* sv, STRLEN* lp)
```
`sv_pvutf8` Use the `SvPVutf8_nolen` macro instead
```
char* sv_pvutf8(SV *sv)
```
`sv_pvutf8n` `**DEPRECATED!**` It is planned to remove `sv_pvutf8n` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvPVutf8` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
char* sv_pvutf8n(SV *sv, STRLEN *lp)
```
`sv_pvutf8n_force` The backend for the `SvPVutf8x_force` macro. Always use the macro instead.
```
char* sv_pvutf8n_force(SV *const sv, STRLEN *const lp)
```
`sv_tainted` Test an SV for taintedness. Use `SvTAINTED` instead.
```
bool sv_tainted(SV *const sv)
```
`SvTHINKFIRST` A quick flag check to see whether an `sv` should be passed to `sv_force_normal` to be "downgraded" before `SvIVX` or `SvPVX` can be modified directly.
For example, if your scalar is a reference and you want to modify the `SvIVX` slot, you can't just do `SvROK_off`, as that will leak the referent.
This is used internally by various sv-modifying functions, such as `sv_setsv`, `sv_setiv` and `sv_pvn_force`.
One case that this does not handle is a gv without SvFAKE set. After
```
if (SvTHINKFIRST(gv)) sv_force_normal(gv);
```
it will still be a gv.
`SvTHINKFIRST` sometimes produces false positives. In those cases `sv_force_normal` does nothing.
```
U32 SvTHINKFIRST(SV *sv)
```
`sv_true` Returns true if the SV has a true value by Perl's rules. Use the `SvTRUE` macro instead, which may call `sv_true()` or may instead use an in-line version.
```
I32 sv_true(SV *const sv)
```
`sv_untaint` Untaint an SV. Use `SvTAINTED_off` instead.
```
void sv_untaint(SV *const sv)
```
`sv_uv` `**DEPRECATED!**` It is planned to remove `sv_uv` from a future release of Perl. Do not use it for new code; remove it from existing code.
A private implementation of the `SvUVx` macro for compilers which can't cope with complex macro expressions. Always use the macro instead.
```
UV sv_uv(SV* sv)
```
Tainting
--------
`sv_taint` Taint an SV. Use `SvTAINTED_on` instead.
```
void sv_taint(SV* sv)
```
`TAINT` If we aren't in taint checking mode, do nothing; otherwise indicate to ["`TAINT_set`"](#TAINT_set) and ["`TAINT_PROPER`"](#TAINT_PROPER) that some unspecified element is tainted.
```
void TAINT()
```
`TAINT_ENV` Looks at several components of [`%ENV`](perlvar#%25ENV) for taintedness, and calls ["`taint_proper`"](#taint_proper) if any are tainted. The components it searches are things like `$PATH`.
```
void TAINT_ENV
```
`taint_env` Implements the ["TAINT\_ENV"](#TAINT_ENV) macro, which you should generally use instead.
```
void taint_env()
```
`TAINT_get` Returns a boolean as to whether some element is tainted or not.
```
bool TAINT_get()
```
`TAINT_IF` If `c` evaluates to true, call ["`TAINT`"](#TAINT) to indicate that something is tainted; otherwise do nothing.
```
void TAINT_IF(bool c)
```
`TAINTING_get` Returns a boolean as to whether taint checking is enabled or not.
```
bool TAINTING_get()
```
`TAINTING_set` Turn taint checking mode off/on
```
void TAINTING_set(bool s)
```
`TAINT_NOT` Remove any taintedness previously set by, *e.g.*, `TAINT`.
```
void TAINT_NOT()
```
`TAINT_PROPER` If no element is tainted, do nothing; otherwise output a message (containing `s`) that indicates there is a tainting violation. If such violations are fatal, it croaks.
```
void TAINT_PROPER(const char * s)
```
`taint_proper` Implements the ["TAINT\_PROPER"](#TAINT_PROPER) macro, which you should generally use instead.
```
void taint_proper(const char* f, const char *const s)
```
`TAINT_set` If `s` is true, ["`TAINT_get`"](#TAINT_get) returns true; If `s` is false, ["`TAINT_get`"](#TAINT_get) returns false;
```
void TAINT_set(bool s)
```
`TAINT_WARN_get` Returns false if tainting violations are fatal; Returns true if they're just warnings
```
bool TAINT_WARN_get()
```
`TAINT_WARN_set` `s` being true indicates ["`TAINT_WARN_get`"](#TAINT_WARN_get) should return that tainting violations are just warnings
`s` being false indicates ["`TAINT_WARN_get`"](#TAINT_WARN_get) should return that tainting violations are fatal.
```
void TAINT_WARN_set(bool s)
```
Time
----
There are only public API items currently in Time
Typedef names
--------------
There are only public API items currently in Typedef names
Unicode Support
----------------
`bytes_from_utf8_loc` NOTE: `bytes_from_utf8_loc` is **experimental** and may change or be removed without notice.
Like `["bytes\_from\_utf8" in perlapi](perlapi#bytes_from_utf8)()`, but takes an extra parameter, a pointer to where to store the location of the first character in `"s"` that cannot be converted to non-UTF8.
If that parameter is `NULL`, this function behaves identically to `bytes_from_utf8`.
Otherwise if `*is_utf8p` is 0 on input, the function behaves identically to `bytes_from_utf8`, except it also sets `*first_non_downgradable` to `NULL`.
Otherwise, the function returns a newly created `NUL`-terminated string containing the non-UTF8 equivalent of the convertible first portion of `"s"`. `*lenp` is set to its length, not including the terminating `NUL`. If the entire input string was converted, `*is_utf8p` is set to a FALSE value, and `*first_non_downgradable` is set to `NULL`.
Otherwise, `*first_non_downgradable` is set to point to the first byte of the first character in the original string that wasn't converted. `*is_utf8p` is unchanged. Note that the new string may have length 0.
Another way to look at it is, if `*first_non_downgradable` is non-`NULL` and `*is_utf8p` is TRUE, this function starts at the beginning of `"s"` and converts as many characters in it as possible stopping at the first one it finds that can't be converted to non-UTF-8. `*first_non_downgradable` is set to point to that. The function returns the portion that could be converted in a newly created `NUL`-terminated string, and `*lenp` is set to its length, not including the terminating `NUL`. If the very first character in the original could not be converted, `*lenp` will be 0, and the new string will contain just a single `NUL`. If the entire input string was converted, `*is_utf8p` is set to FALSE and `*first_non_downgradable` is set to `NULL`.
Upon successful return, the number of variants in the converted portion of the string can be computed by having saved the value of `*lenp` before the call, and subtracting the after-call value of `*lenp` from it.
```
U8* bytes_from_utf8_loc(const U8 *s, STRLEN *lenp,
bool *is_utf8p,
const U8 ** first_unconverted)
```
`find_uninit_var` NOTE: `find_uninit_var` is **experimental** and may change or be removed without notice.
Find the name of the undefined variable (if any) that caused the operator to issue a "Use of uninitialized value" warning. If match is true, only return a name if its value matches `uninit_sv`. So roughly speaking, if a unary operator (such as `OP_COS`) generates a warning, then following the direct child of the op may yield an `OP_PADSV` or `OP_GV` that gives the name of the undefined variable. On the other hand, with `OP_ADD` there are two branches to follow, so we only print the variable name if we get an exact match. `desc_p` points to a string pointer holding the description of the op. This may be updated if needed.
The name is returned as a mortal SV.
Assumes that `PL_op` is the OP that originally triggered the error, and that `PL_comppad`/`PL_curpad` points to the currently executing pad.
```
SV* find_uninit_var(const OP *const obase,
const SV *const uninit_sv, bool match,
const char **desc_p)
```
`isSCRIPT_RUN` Returns a bool as to whether or not the sequence of bytes from `s` up to but not including `send` form a "script run". `utf8_target` is TRUE iff the sequence starting at `s` is to be treated as UTF-8. To be precise, except for two degenerate cases given below, this function returns TRUE iff all code points in it come from any combination of three "scripts" given by the Unicode "Script Extensions" property: Common, Inherited, and possibly one other. Additionally all decimal digits must come from the same consecutive sequence of 10.
For example, if all the characters in the sequence are Greek, or Common, or Inherited, this function will return TRUE, provided any decimal digits in it are from the same block of digits in Common. (These are the ASCII digits "0".."9" and additionally a block for full width forms of these, and several others used in mathematical notation.) For scripts (unlike Greek) that have their own digits defined this will accept either digits from that set or from one of the Common digit sets, but not a combination of the two. Some scripts, such as Arabic, have more than one set of digits. All digits must come from the same set for this function to return TRUE.
`*ret_script`, if `ret_script` is not NULL, will on return of TRUE contain the script found, using the `SCX_enum` typedef. Its value will be `SCX_INVALID` if the function returns FALSE.
If the sequence is empty, TRUE is returned, but `*ret_script` (if asked for) will be `SCX_INVALID`.
If the sequence contains a single code point which is unassigned to a character in the version of Unicode being used, the function will return TRUE, and the script will be `SCX_Unknown`. Any other combination of unassigned code points in the input sequence will result in the function treating the input as not being a script run.
The returned script will be `SCX_Inherited` iff all the code points in it are from the Inherited script.
Otherwise, the returned script will be `SCX_Common` iff all the code points in it are from the Inherited or Common scripts.
```
bool isSCRIPT_RUN(const U8 *s, const U8 *send,
const bool utf8_target)
```
`is_utf8_non_invariant_string` Returns TRUE if ["is\_utf8\_invariant\_string" in perlapi](perlapi#is_utf8_invariant_string) returns FALSE for the first `len` bytes of the string `s`, but they are, nonetheless, legal Perl-extended UTF-8; otherwise returns FALSE.
A TRUE return means that at least one code point represented by the sequence either is a wide character not representable as a single byte, or the representation differs depending on whether the sequence is encoded in UTF-8 or not.
See also `["is\_utf8\_invariant\_string" in perlapi](perlapi#is_utf8_invariant_string)`, `["is\_utf8\_string" in perlapi](perlapi#is_utf8_string)`
```
bool is_utf8_non_invariant_string(const U8* const s, STRLEN len)
```
`report_uninit` Print appropriate "Use of uninitialized variable" warning.
```
void report_uninit(const SV *uninit_sv)
```
`utf8n_to_uvuni` `**DEPRECATED!**` It is planned to remove `utf8n_to_uvuni` from a future release of Perl. Do not use it for new code; remove it from existing code.
Instead use ["utf8\_to\_uvchr\_buf" in perlapi](perlapi#utf8_to_uvchr_buf), or rarely, ["utf8n\_to\_uvchr" in perlapi](perlapi#utf8n_to_uvchr).
This function was useful for code that wanted to handle both EBCDIC and ASCII platforms with Unicode properties, but starting in Perl v5.20, the distinctions between the platforms have mostly been made invisible to most code, so this function is quite unlikely to be what you want. If you do need this precise functionality, use instead `[NATIVE\_TO\_UNI(utf8\_to\_uvchr\_buf(...))](perlapi#utf8_to_uvchr_buf)` or `[NATIVE\_TO\_UNI(utf8n\_to\_uvchr(...))](perlapi#utf8n_to_uvchr)`.
```
UV utf8n_to_uvuni(const U8 *s, STRLEN curlen, STRLEN *retlen,
U32 flags)
```
`utf8_to_uvuni` `**DEPRECATED!**` It is planned to remove `utf8_to_uvuni` from a future release of Perl. Do not use it for new code; remove it from existing code.
Returns the Unicode code point of the first character in the string `s` which is assumed to be in UTF-8 encoding; `retlen` will be set to the length, in bytes, of that character.
Some, but not all, UTF-8 malformations are detected, and in fact, some malformed input could cause reading beyond the end of the input buffer, which is one reason why this function is deprecated. The other is that only in extremely limited circumstances should the Unicode versus native code point be of any interest to you. See ["utf8\_to\_uvuni\_buf"](#utf8_to_uvuni_buf) for alternatives.
If `s` points to one of the detected malformations, and UTF8 warnings are enabled, zero is returned and `*retlen` is set (if `retlen` doesn't point to NULL) to -1. If those warnings are off, the computed value if well-defined (or the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and `*retlen` is set (if `retlen` isn't NULL) so that (`s` + `*retlen`) is the next possible position in `s` that could begin a non-malformed character. See ["utf8n\_to\_uvchr" in perlapi](perlapi#utf8n_to_uvchr) for details on when the REPLACEMENT CHARACTER is returned.
```
UV utf8_to_uvuni(const U8 *s, STRLEN *retlen)
```
`utf8_to_uvuni_buf` `**DEPRECATED!**` It is planned to remove `utf8_to_uvuni_buf` from a future release of Perl. Do not use it for new code; remove it from existing code.
Only in very rare circumstances should code need to be dealing in Unicode (as opposed to native) code points. In those few cases, use `[NATIVE\_TO\_UNI(utf8\_to\_uvchr\_buf(...))](perlapi#utf8_to_uvchr_buf)` instead. If you are not absolutely sure this is one of those cases, then assume it isn't and use plain `utf8_to_uvchr_buf` instead.
Returns the Unicode (not-native) code point of the first character in the string `s` which is assumed to be in UTF-8 encoding; `send` points to 1 beyond the end of `s`. `retlen` will be set to the length, in bytes, of that character.
If `s` does not point to a well-formed UTF-8 character and UTF8 warnings are enabled, zero is returned and `*retlen` is set (if `retlen` isn't NULL) to -1. If those warnings are off, the computed value if well-defined (or the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and `*retlen` is set (if `retlen` isn't NULL) so that (`s` + `*retlen`) is the next possible position in `s` that could begin a non-malformed character. See ["utf8n\_to\_uvchr" in perlapi](perlapi#utf8n_to_uvchr) for details on when the REPLACEMENT CHARACTER is returned.
```
UV utf8_to_uvuni_buf(const U8 *s, const U8 *send, STRLEN *retlen)
```
`uvoffuni_to_utf8_flags` THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES. Instead, **Almost all code should use ["uvchr\_to\_utf8" in perlapi](perlapi#uvchr_to_utf8) or ["uvchr\_to\_utf8\_flags" in perlapi](perlapi#uvchr_to_utf8_flags)**.
This function is like them, but the input is a strict Unicode (as opposed to native) code point. Only in very rare circumstances should code not be using the native code point.
For details, see the description for ["uvchr\_to\_utf8\_flags" in perlapi](perlapi#uvchr_to_utf8_flags).
```
U8* uvoffuni_to_utf8_flags(U8 *d, UV uv, UV flags)
```
`uvuni_to_utf8_flags` `**DEPRECATED!**` It is planned to remove `uvuni_to_utf8_flags` from a future release of Perl. Do not use it for new code; remove it from existing code.
Instead you almost certainly want to use ["uvchr\_to\_utf8" in perlapi](perlapi#uvchr_to_utf8) or ["uvchr\_to\_utf8\_flags" in perlapi](perlapi#uvchr_to_utf8_flags).
This function is a deprecated synonym for ["uvoffuni\_to\_utf8\_flags"](#uvoffuni_to_utf8_flags), which itself, while not deprecated, should be used only in isolated circumstances. These functions were useful for code that wanted to handle both EBCDIC and ASCII platforms with Unicode properties, but starting in Perl v5.20, the distinctions between the platforms have mostly been made invisible to most code, so this function is quite unlikely to be what you want.
```
U8* uvuni_to_utf8_flags(U8 *d, UV uv, UV flags)
```
`valid_utf8_to_uvchr` Like `["utf8\_to\_uvchr\_buf" in perlapi](perlapi#utf8_to_uvchr_buf)`, but should only be called when it is known that the next character in the input UTF-8 string `s` is well-formed (*e.g.*, it passes `["isUTF8\_CHAR" in perlapi](perlapi#isUTF8_CHAR)`. Surrogates, non-character code points, and non-Unicode code points are allowed.
```
UV valid_utf8_to_uvchr(const U8 *s, STRLEN *retlen)
```
`variant_under_utf8_count` This function looks at the sequence of bytes between `s` and `e`, which are assumed to be encoded in ASCII/Latin1, and returns how many of them would change should the string be translated into UTF-8. Due to the nature of UTF-8, each of these would occupy two bytes instead of the single one in the input string. Thus, this function returns the precise number of bytes the string would expand by when translated to UTF-8.
Unlike most of the other functions that have `utf8` in their name, the input to this function is NOT a UTF-8-encoded string. The function name is slightly *odd* to emphasize this.
This function is internal to Perl because khw thinks that any XS code that would want this is probably operating too close to the internals. Presenting a valid use case could change that.
See also `["is\_utf8\_invariant\_string" in perlapi](perlapi#is_utf8_invariant_string)` and `["is\_utf8\_invariant\_string\_loc" in perlapi](perlapi#is_utf8_invariant_string_loc)`,
```
Size_t variant_under_utf8_count(const U8* const s,
const U8* const e)
```
Utility Functions
------------------
`my_popen_list` Implementing function on some systems for PerlProc\_popen\_list()
```
PerlIO* my_popen_list(const char* mode, int n, SV ** args)
```
`my_socketpair` Emulates [socketpair(2)](http://man.he.net/man2/socketpair) on systems that don't have it, but which do have enough functionality for the emulation.
```
int my_socketpair(int family, int type, int protocol, int fd[2])
```
Versioning
----------
There are only public API items currently in Versioning
Warning and Dieing
-------------------
`PL_dowarn` The C variable that roughly corresponds to Perl's `$^W` warning variable. However, `$^W` is treated as a boolean, whereas `PL_dowarn` is a collection of flag bits.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
U8 PL_dowarn
```
XS
--
There are only public API items currently in XS
Undocumented elements
----------------------
The following functions are currently undocumented. If you use one of them, you may wish to consider creating and submitting documentation for it.
```
abort_execution
add_cp_to_invlist
_add_range_to_invlist
alloc_LOGOP
allocmy
amagic_cmp
amagic_cmp_desc
amagic_cmp_locale
amagic_cmp_locale_desc
amagic_is_enabled
amagic_i_ncmp
amagic_i_ncmp_desc
amagic_ncmp
amagic_ncmp_desc
any_dup
append_utf8_from_native_byte
apply
ASCII_TO_NEED
atfork_lock
atfork_unlock
av_arylen_p
av_extend_guts
av_iter_p
av_nonelem
av_reify
bind_match
block_gimme
boot_core_builtin
boot_core_mro
boot_core_PerlIO
boot_core_UNIVERSAL
_byte_dump_string
call_list
cando
cast_i32
cast_iv
cast_ulong
cast_uv
check_utf8_print
ck_anoncode
ck_backtick
ck_bitop
ck_cmp
ck_concat
ck_defined
ck_delete
ck_each
ck_entersub_args_core
ck_eof
ck_eval
ck_exec
ck_exists
ck_ftst
ck_fun
ck_glob
ck_grep
ck_index
ck_isa
ck_join
ck_length
ck_lfun
ck_listiob
ck_match
ck_method
ck_null
ck_open
ck_prototype
ck_readline
ck_refassign
ck_repeat
ck_require
ck_return
ck_rfun
ck_rvconst
ck_sassign
ck_select
ck_shift
ck_smartmatch
ck_sort
ck_spair
ck_split
ck_stringify
ck_subr
ck_substr
ck_svconst
ck_tell
ck_trunc
ck_trycatch
ckwarn
ckwarn_d
clear_defarray
closest_cop
cmpchain_extend
cmpchain_finish
cmpchain_start
cmp_desc
cmp_locale_desc
cntrl_to_mnemonic
cop_file_avn
coresub_op
create_eval_scope
croak_caller
croak_memory_wrap
croak_no_mem
croak_popstack
csighandler
csighandler1
csighandler3
current_re_engine
custom_op_get_field
cv_ckproto_len_flags
cv_clone_into
cv_const_sv_or_av
cvgv_from_hek
cvgv_set
cvstash_set
cv_undef_flags
cx_dump
cx_dup
cxinc
cx_popblock
cx_popeval
cx_popformat
cx_popgiven
cx_poploop
cx_popsub
cx_popsub_args
cx_popsub_common
cx_popwhen
cx_pushblock
cx_pusheval
cx_pushformat
cx_pushgiven
cx_pushloop_for
cx_pushloop_plain
cx_pushsub
cx_pushtry
cx_pushwhen
cx_topblock
debstackptrs
deb_stack_all
debug_hash_seed
defelem_target
delete_eval_scope
despatch_signals
die_unwind
do_aexec
do_aexec5
do_aspawn
do_eof
does_utf8_overflow
do_exec
do_exec3
dofile
do_gvgv_dump
do_gv_dump
do_hv_dump
doing_taint
do_ipcctl
do_ipcget
do_magic_dump
do_msgrcv
do_msgsnd
do_ncmp
do_open6
do_open_raw
do_op_dump
do_pmop_dump
do_print
do_readline
doref
do_seek
do_semop
do_shmio
do_spawn
do_spawn_nowait
do_sv_dump
do_sysseek
do_tell
do_trans
do_uniprop_match
do_vecget
do_vecset
do_vop
drand48_init_r
drand48_r
dtrace_probe_call
dtrace_probe_load
dtrace_probe_op
dtrace_probe_phase
dump_all_perl
dump_indent
dump_packsubs_perl
dump_sub_perl
dump_sv_child
dump_vindent
dup_warnings
emulate_cop_io
find_first_differing_byte_pos
find_lexical_cv
find_runcv_where
find_script
foldEQ_latin1
foldEQ_latin1_s2_folded
foldEQ_utf8_flags
_force_out_malformed_utf8_message
form_alien_digit_msg
form_cp_too_large_msg
free_tied_hv_pool
free_tmps
get_and_check_backslash_N_name
get_db_sub
get_debug_opts
get_deprecated_property_msg
getenv_len
get_hash_seed
get_invlist_iter_addr
get_invlist_offset_addr
get_invlist_previous_index_addr
get_mstats
get_no_modify
get_opargs
get_ppaddr
get_prop_definition
get_prop_values
get_regclass_nonbitmap_data
get_regex_charset_name
get_re_arg
get_re_gclass_nonbitmap_data
get_vtbl
gimme_V
gp_free
gp_ref
grok_bin_oct_hex
grok_bslash_c
grok_bslash_o
grok_bslash_x
gv_check
gv_fetchmeth_internal
gv_override
gv_setref
gv_stashpvn_internal
he_dup
hek_dup
hfree_next_entry
hv_auxalloc
hv_backreferences_p
hv_common
hv_common_key_len
hv_delayfree_ent
hv_kill_backrefs
hv_placeholders_p
hv_pushkv
hv_rand_set
hv_undef_flags
init_argv_symbols
init_constants
init_dbargs
init_debugger
init_i18nl10n
init_i18nl14n
init_named_cv
init_stacks
init_tm
init_uniprops
_inverse_folds
invert
invlist_array
invlist_clear
invlist_clone
invlist_contents
_invlistEQ
invlist_extend
invlist_highest
invlist_is_iterating
invlist_iterfinish
invlist_iterinit
invlist_iternext
invlist_lowest
invlist_max
invlist_previous_index
invlist_set_len
invlist_set_previous_index
invlist_trim
_invlist_array_init
_invlist_contains_cp
_invlist_dump
_invlist_intersection
_invlist_intersection_maybe_complement_2nd
_invlist_invert
_invlist_len
_invlist_search
_invlist_subtract
_invlist_union
_invlist_union_maybe_complement_2nd
invmap_dump
io_close
isFF_overlong
is_grapheme
is_invlist
is_utf8_char_helper_
is_utf8_common
is_utf8_FF_helper_
is_utf8_overlong
_is_cur_LC_category_utf8
_is_in_locale_category
_is_uni_FOO
_is_uni_perl_idcont
_is_uni_perl_idstart
_is_utf8_FOO
_is_utf8_perl_idcont
_is_utf8_perl_idstart
jmaybe
keyword
keyword_plugin_standard
list
load_charnames
localize
lossless_NV_to_IV
lsbit_pos32
lsbit_pos64
magic_cleararylen_p
magic_clearenv
magic_clearisa
magic_clearpack
magic_clearsig
magic_clear_all_env
magic_copycallchecker
magic_existspack
magic_freearylen_p
magic_freecollxfrm
magic_freemglob
magic_freeovrld
magic_freeutf8
magic_get
magic_getarylen
magic_getdebugvar
magic_getdefelem
magic_getnkeys
magic_getpack
magic_getpos
magic_getsig
magic_getsubstr
magic_gettaint
magic_getuvar
magic_getvec
magic_killbackrefs
magic_nextpack
magic_regdata_cnt
magic_regdatum_get
magic_regdatum_set
magic_scalarpack
magic_set
magic_setarylen
magic_setcollxfrm
magic_setdbline
magic_setdebugvar
magic_setdefelem
magic_setenv
magic_setisa
magic_setlvref
magic_setmglob
magic_setnkeys
magic_setnonelem
magic_setpack
magic_setpos
magic_setregexp
magic_setsig
magic_setsigall
magic_setsubstr
magic_settaint
magic_setutf8
magic_setuvar
magic_setvec
magic_set_all_env
magic_sizepack
magic_wipepack
malloced_size
malloc_good_size
markstack_grow
mem_collxfrm
mem_log_alloc
mem_log_free
mem_log_realloc
_mem_collxfrm
mg_find_mglob
mg_size
mode_from_discipline
more_bodies
more_sv
moreswitches
mortal_getenv
mro_get_private_data
mro_meta_dup
mro_meta_init
msbit_pos32
msbit_pos64
multiconcat_stringify
multideref_stringify
my_atof2
my_atof3
my_attrs
my_clearenv
my_lstat
my_lstat_flags
my_memrchr
my_mkostemp_cloexec
my_mkstemp_cloexec
my_stat
my_stat_flags
my_strerror
my_unexec
NATIVE_TO_NEED
newFORM
newGP
newMETHOP_internal
newMYSUB
newPROG
new_stackinfo
newSTUB
newSVavdefelem
new_warnings_bitfield
newXS_deffile
_new_invlist
_new_invlist_C_array
nextargv
no_bareword_filehandle
noperl_die
notify_parser_that_changed_to_utf8
oopsAV
oopsHV
op_clear
op_integerize
op_lvalue_flags
opmethod_stash
op_refcnt_dec
op_refcnt_inc
op_relocate_sv
opslab_force_free
opslab_free
opslab_free_nopad
op_std_init
op_unscope
package
package_version
pad_add_weakref
padlist_store
padname_free
PadnameIN_SCOPE
padnamelist_free
parser_dup
parser_free
parser_free_nexttoke_ops
parse_unicode_opts
path_is_searchable
peep
perl_alloc_using
perl_clone_using
PerlIO_context_layers
PerlIO_restore_errno
PerlIO_save_errno
PerlLIO_dup2_cloexec
PerlLIO_dup_cloexec
PerlLIO_open3_cloexec
PerlLIO_open_cloexec
PerlProc_pipe_cloexec
PerlSock_accept_cloexec
PerlSock_socketpair_cloexec
PerlSock_socket_cloexec
perly_sighandler
pmruntime
POPMARK
populate_isa
pregfree
pregfree2
qerror
ReANY
reentrant_free
reentrant_init
reentrant_retry
reentrant_size
re_exec_indentf
ref
regcurly
regdump
regdupe_internal
regexec_flags
regfree_internal
reginitcolors
reg_named_buff
reg_named_buff_all
reg_named_buff_exists
reg_named_buff_fetch
reg_named_buff_firstkey
reg_named_buff_iter
reg_named_buff_nextkey
reg_named_buff_scalar
regnext
reg_numbered_buff_fetch
reg_numbered_buff_length
reg_numbered_buff_store
regprop
reg_qr_package
reg_skipcomment
reg_temp_copy
re_indentf
re_intuit_start
re_intuit_string
re_op_compile
report_evil_fh
report_redefined_cv
report_wrongway_fh
re_printf
rpeep
rsignal_restore
rsignal_save
rvpv_dup
rxres_save
same_dirent
save_bool
save_clearsv
save_delete
save_destructor
save_destructor_x
save_freeop
save_freepv
save_freesv
save_I16
save_I32
save_I8
save_int
save_iv
save_long
save_mortalizesv
save_pptr
save_re_context
save_sptr
savestack_grow
savestack_grow_cnt
save_strlen
save_to_buffer
sawparens
scalar
scalarvoid
scan_num
scan_str
scan_word
seed
set_caret_X
setfd_cloexec
setfd_cloexec_for_nonsysfd
setfd_cloexec_or_inhexec_by_sysfdness
setfd_inhexec
setfd_inhexec_for_sysfd
set_numeric_standard
set_numeric_underlying
set_padlist
_setup_canned_invlist
share_hek
should_warn_nl
should_we_output_Debug_r
sighandler
sighandler1
sighandler3
single_1bit_pos32
single_1bit_pos64
skipspace_flags
Slab_Alloc
Slab_Free
Slab_to_ro
Slab_to_rw
softref2xv
sortsv_flags_impl
stack_grow
str_to_version
sub_crush_depth
sv_2iv
sv_2uv
sv_add_backref
sv_buf_to_ro
sv_del_backref
sv_free2
sv_i_ncmp
sv_i_ncmp_desc
sv_kill_backrefs
sv_magicext_mglob
sv_ncmp
sv_ncmp_desc
sv_only_taint_gmagic
sv_or_pv_pos_u2b
sv_resetpvn
sv_sethek
sv_setsv_cow
SvTRUE_common
sv_unglob
sys_init
sys_init3
sys_intern_clear
sys_intern_dup
sys_intern_init
sys_term
tied_method
tmps_grow_p
TOPMARK
to_uni_fold
to_uni_lower
to_uni_title
to_uni_upper
_to_fold_latin1
_to_uni_fold_flags
_to_upper_title_latin1
_to_utf8_fold_flags
_to_utf8_lower_flags
_to_utf8_title_flags
_to_utf8_upper_flags
translate_substr_offsets
try_amagic_bin
try_amagic_un
uiv_2buf
unlnk
unshare_hek
utf16_to_utf8
utf16_to_utf8_base
utf16_to_utf8_reversed
_utf8n_to_uvchr_msgs_helper
utf8_to_utf16_base
utf8_to_uvchr_buf_helper
utilize
uvoffuni_to_utf8_flags_msgs
uvuni_to_utf8
valid_utf8_to_uvuni
variant_byte_number
varname
vivify_defelem
vivify_ref
wait4pid
_warn_problematic_locale
was_lvalue_sub
watch
win32_croak_not_implemented
write_to_stderr
xs_boot_epilog
xs_handshake
yyerror
yyerror_pv
yyerror_pvn
yylex
yyparse
yyquit
yyunlex
```
AUTHORS
-------
The autodocumentation system was originally added to the Perl core by Benjamin Stuhl. Documentation is by whoever was kind enough to document their functions.
SEE ALSO
---------
*config.h*, <perlapi>, <perlapio>, <perlcall>, <perlclib>, <perlembed>, <perlfilter>, <perlguts>, <perlhacktips>, <perlinterp>, <perliol>, <perlmroapi>, <perlreapi>, <perlreguts>, <perlxs>
| programming_docs |
perl ExtUtils::Manifest ExtUtils::Manifest
==================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [mkmanifest](#mkmanifest)
+ [manifind](#manifind)
+ [manicheck](#manicheck)
+ [filecheck](#filecheck)
+ [fullcheck](#fullcheck)
+ [skipcheck](#skipcheck)
+ [maniread](#maniread)
+ [maniskip](#maniskip)
+ [manicopy](#manicopy)
+ [maniadd](#maniadd)
+ [MANIFEST](#MANIFEST)
+ [MANIFEST.SKIP](#MANIFEST.SKIP)
+ [EXPORT\_OK](#EXPORT_OK)
+ [GLOBAL VARIABLES](#GLOBAL-VARIABLES)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [ENVIRONMENT](#ENVIRONMENT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
ExtUtils::Manifest - Utilities to write and check a MANIFEST file
VERSION
-------
version 1.73
SYNOPSIS
--------
```
use ExtUtils::Manifest qw(...funcs to import...);
mkmanifest();
my @missing_files = manicheck;
my @skipped = skipcheck;
my @extra_files = filecheck;
my($missing, $extra) = fullcheck;
my $found = manifind();
my $manifest = maniread();
manicopy($read,$target);
maniadd({$file => $comment, ...});
```
DESCRIPTION
-----------
...
FUNCTIONS
---------
ExtUtils::Manifest exports no functions by default. The following are exported on request:
### mkmanifest
```
mkmanifest();
```
Writes all files in and below the current directory to your *MANIFEST*. It works similar to the result of the Unix command
```
find . > MANIFEST
```
All files that match any regular expression in a file *MANIFEST.SKIP* (if it exists) are ignored.
Any existing *MANIFEST* file will be saved as *MANIFEST.bak*.
### manifind
```
my $found = manifind();
```
returns a hash reference. The keys of the hash are the files found below the current directory.
### manicheck
```
my @missing_files = manicheck();
```
checks if all the files within a `MANIFEST` in the current directory really do exist. If `MANIFEST` and the tree below the current directory are in sync it silently returns an empty list. Otherwise it returns a list of files which are listed in the `MANIFEST` but missing from the directory, and by default also outputs these names to STDERR.
### filecheck
```
my @extra_files = filecheck();
```
finds files below the current directory that are not mentioned in the `MANIFEST` file. An optional file `MANIFEST.SKIP` will be consulted. Any file matching a regular expression in such a file will not be reported as missing in the `MANIFEST` file. The list of any extraneous files found is returned, and by default also reported to STDERR.
### fullcheck
```
my($missing, $extra) = fullcheck();
```
does both a manicheck() and a filecheck(), returning then as two array refs.
### skipcheck
```
my @skipped = skipcheck();
```
lists all the files that are skipped due to your `MANIFEST.SKIP` file.
### maniread
```
my $manifest = maniread();
my $manifest = maniread($manifest_file);
```
reads a named `MANIFEST` file (defaults to `MANIFEST` in the current directory) and returns a HASH reference with files being the keys and comments being the values of the HASH. Blank lines and lines which start with `#` in the `MANIFEST` file are discarded.
### maniskip
```
my $skipchk = maniskip();
my $skipchk = maniskip($manifest_skip_file);
if ($skipchk->($file)) { .. }
```
reads a named `MANIFEST.SKIP` file (defaults to `MANIFEST.SKIP` in the current directory) and returns a CODE reference that tests whether a given filename should be skipped.
### manicopy
```
manicopy(\%src, $dest_dir);
manicopy(\%src, $dest_dir, $how);
```
Copies the files that are the keys in %src to the $dest\_dir. %src is typically returned by the maniread() function.
```
manicopy( maniread(), $dest_dir );
```
This function is useful for producing a directory tree identical to the intended distribution tree.
$how can be used to specify a different methods of "copying". Valid values are `cp`, which actually copies the files, `ln` which creates hard links, and `best` which mostly links the files but copies any symbolic link to make a tree without any symbolic link. `cp` is the default.
### maniadd
```
maniadd({ $file => $comment, ...});
```
Adds an entry to an existing *MANIFEST* unless its already there.
$file will be normalized (ie. Unixified). **UNIMPLEMENTED**
### MANIFEST
A list of files in the distribution, one file per line. The MANIFEST always uses Unix filepath conventions even if you're not on Unix. This means *foo/bar* style not *foo\bar*.
Anything between white space and an end of line within a `MANIFEST` file is considered to be a comment. Any line beginning with # is also a comment. Beginning with ExtUtils::Manifest 1.52, a filename may contain whitespace characters if it is enclosed in single quotes; single quotes or backslashes in that filename must be backslash-escaped.
```
# this a comment
some/file
some/other/file comment about some/file
'some/third file' comment
```
###
MANIFEST.SKIP
The file MANIFEST.SKIP may contain regular expressions of files that should be ignored by mkmanifest() and filecheck(). The regular expressions should appear one on each line. Blank lines and lines which start with `#` are skipped. Use `\#` if you need a regular expression to start with a `#`.
For example:
```
# Version control files and dirs.
\bRCS\b
\bCVS\b
,v$
\B\.svn\b
# Makemaker generated files and dirs.
^MANIFEST\.
^Makefile$
^blib/
^MakeMaker-\d
# Temp, old and emacs backup files.
~$
\.old$
^#.*#$
^\.#
```
If no MANIFEST.SKIP file is found, a default set of skips will be used, similar to the example above. If you want nothing skipped, simply make an empty MANIFEST.SKIP file.
In one's own MANIFEST.SKIP file, certain directives can be used to include the contents of other MANIFEST.SKIP files. At present two such directives are recognized.
#!include\_default This inserts the contents of the default MANIFEST.SKIP file
#!include /Path/to/another/manifest.skip This inserts the contents of the specified external file
The included contents will be inserted into the MANIFEST.SKIP file in between *#!start included /path/to/manifest.skip* and *#!end included /path/to/manifest.skip* markers. The original MANIFEST.SKIP is saved as MANIFEST.SKIP.bak.
### EXPORT\_OK
`&mkmanifest`, `&manicheck`, `&filecheck`, `&fullcheck`, `&maniread`, and `&manicopy` are exportable.
###
GLOBAL VARIABLES
`$ExtUtils::Manifest::MANIFEST` defaults to `MANIFEST`. Changing it results in both a different `MANIFEST` and a different `MANIFEST.SKIP` file. This is useful if you want to maintain different distributions for different audiences (say a user version and a developer version including RCS).
`$ExtUtils::Manifest::Quiet` defaults to 0. If set to a true value, all functions act silently.
`$ExtUtils::Manifest::Debug` defaults to 0. If set to a true value, or if PERL\_MM\_MANIFEST\_DEBUG is true, debugging output will be produced.
DIAGNOSTICS
-----------
All diagnostic output is sent to `STDERR`.
`Not in MANIFEST:` *file*
is reported if a file is found which is not in `MANIFEST`.
`Skipping` *file*
is reported if a file is skipped due to an entry in `MANIFEST.SKIP`.
`No such file:` *file*
is reported if a file mentioned in a `MANIFEST` file does not exist.
`MANIFEST:` *$!*
is reported if `MANIFEST` could not be opened.
`Added to MANIFEST:` *file*
is reported by mkmanifest() if $Verbose is set and a file is added to MANIFEST. $Verbose is set to 1 by default.
ENVIRONMENT
-----------
**PERL\_MM\_MANIFEST\_DEBUG** Turns on debugging
SEE ALSO
---------
<ExtUtils::MakeMaker> which has handy targets for most of the functionality.
AUTHOR
------
Andreas Koenig `[email protected]`
Currently maintained by the Perl Toolchain Gang.
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 1996- by Andreas Koenig.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl TAP::Parser::Scheduler::Spinner TAP::Parser::Scheduler::Spinner
===============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [is\_spinner](#is_spinner)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Scheduler::Spinner - A no-op job.
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Scheduler::Spinner;
```
DESCRIPTION
-----------
A no-op job. Returned by `TAP::Parser::Scheduler` as an instruction to the harness to spin (keep executing tests) while the scheduler can't return a real job.
METHODS
-------
###
Class Methods
#### `new`
```
my $job = TAP::Parser::Scheduler::Spinner->new;
```
Ignores any arguments and returns a new `TAP::Parser::Scheduler::Spinner` object.
###
Instance Methods
#### `is_spinner`
Returns true indicating that is a 'spinner' job. Spinners are returned when the scheduler still has pending jobs but can't (because of locking) return one right now.
SEE ALSO
---------
<TAP::Parser::Scheduler>, <TAP::Parser::Scheduler::Job>
perl Parse::CPAN::Meta Parse::CPAN::Meta
=================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [load\_file](#load_file)
+ [load\_yaml\_string](#load_yaml_string)
+ [load\_json\_string](#load_json_string)
+ [load\_string](#load_string)
+ [yaml\_backend](#yaml_backend)
+ [json\_backend](#json_backend)
+ [json\_decoder](#json_decoder)
* [FUNCTIONS](#FUNCTIONS)
+ [Load](#Load)
+ [LoadFile](#LoadFile)
* [ENVIRONMENT](#ENVIRONMENT)
+ [CPAN\_META\_JSON\_DECODER](#CPAN_META_JSON_DECODER)
+ [CPAN\_META\_JSON\_BACKEND](#CPAN_META_JSON_BACKEND)
+ [PERL\_JSON\_BACKEND](#PERL_JSON_BACKEND)
+ [PERL\_YAML\_BACKEND](#PERL_YAML_BACKEND)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Parse::CPAN::Meta - Parse META.yml and META.json CPAN metadata files
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
#############################################
# In your file
---
name: My-Distribution
version: 1.23
resources:
homepage: "http://example.com/dist/My-Distribution"
#############################################
# In your program
use Parse::CPAN::Meta;
my $distmeta = Parse::CPAN::Meta->load_file('META.yml');
# Reading properties
my $name = $distmeta->{name};
my $version = $distmeta->{version};
my $homepage = $distmeta->{resources}{homepage};
```
DESCRIPTION
-----------
**Parse::CPAN::Meta** is a parser for *META.json* and *META.yml* files, using <JSON::PP> and/or <CPAN::Meta::YAML>.
**Parse::CPAN::Meta** provides three methods: `load_file`, `load_json_string`, and `load_yaml_string`. These will read and deserialize CPAN metafiles, and are described below in detail.
**Parse::CPAN::Meta** provides a legacy API of only two functions, based on the YAML functions of the same name. Wherever possible, identical calling semantics are used. These may only be used with YAML sources.
All error reporting is done with exceptions (die'ing).
Note that META files are expected to be in UTF-8 encoding, only. When converted string data, it must first be decoded from UTF-8.
METHODS
-------
### load\_file
```
my $metadata_structure = Parse::CPAN::Meta->load_file('META.json');
my $metadata_structure = Parse::CPAN::Meta->load_file('META.yml');
```
This method will read the named file and deserialize it to a data structure, determining whether it should be JSON or YAML based on the filename. The file will be read using the ":utf8" IO layer.
### load\_yaml\_string
```
my $metadata_structure = Parse::CPAN::Meta->load_yaml_string($yaml_string);
```
This method deserializes the given string of YAML and returns the first document in it. (CPAN metadata files should always have only one document.) If the source was UTF-8 encoded, the string must be decoded before calling `load_yaml_string`.
### load\_json\_string
```
my $metadata_structure = Parse::CPAN::Meta->load_json_string($json_string);
```
This method deserializes the given string of JSON and the result. If the source was UTF-8 encoded, the string must be decoded before calling `load_json_string`.
### load\_string
```
my $metadata_structure = Parse::CPAN::Meta->load_string($some_string);
```
If you don't know whether a string contains YAML or JSON data, this method will use some heuristics and guess. If it can't tell, it assumes YAML.
### yaml\_backend
```
my $backend = Parse::CPAN::Meta->yaml_backend;
```
Returns the module name of the YAML serializer. See ["ENVIRONMENT"](#ENVIRONMENT) for details.
### json\_backend
```
my $backend = Parse::CPAN::Meta->json_backend;
```
Returns the module name of the JSON serializer. If `CPAN_META_JSON_BACKEND` is set, this will be whatever that's set to. If not, this will either be <JSON::PP> or [JSON](json). If `PERL_JSON_BACKEND` is set, this will return [JSON](json) as further delegation is handled by the [JSON](json) module. See ["ENVIRONMENT"](#ENVIRONMENT) for details.
### json\_decoder
```
my $decoder = Parse::CPAN::Meta->json_decoder;
```
Returns the module name of the JSON decoder. Unlike ["json\_backend"](#json_backend), this is not necessarily a full [JSON](json)-style module, but only something that will provide a `decode_json` subroutine. If `CPAN_META_JSON_DECODER` is set, this will be whatever that's set to. If not, this will be whatever has been selected as ["json\_backend"](#json_backend). See ["ENVIRONMENT"](#ENVIRONMENT) for more notes.
FUNCTIONS
---------
For maintenance clarity, no functions are exported by default. These functions are available for backwards compatibility only and are best avoided in favor of `load_file`.
### Load
```
my @yaml = Parse::CPAN::Meta::Load( $string );
```
Parses a string containing a valid YAML stream into a list of Perl data structures.
### LoadFile
```
my @yaml = Parse::CPAN::Meta::LoadFile( 'META.yml' );
```
Reads the YAML stream from a file instead of a string.
ENVIRONMENT
-----------
### CPAN\_META\_JSON\_DECODER
By default, <JSON::PP> will be used for deserializing JSON data. If the `CPAN_META_JSON_DECODER` environment variable exists, this is expected to be the name of a loadable module that provides a `decode_json` subroutine, which will then be used for deserialization. Relying only on the existence of said subroutine allows for maximum compatibility, since this API is provided by all of <JSON::PP>, <JSON::XS>, <Cpanel::JSON::XS>, <JSON::MaybeXS>, <JSON::Tiny>, and <Mojo::JSON>.
### CPAN\_META\_JSON\_BACKEND
By default, <JSON::PP> will be used for deserializing JSON data. If the `CPAN_META_JSON_BACKEND` environment variable exists, this is expected to be the name of a loadable module that provides the [JSON](json) API, since downstream code expects to be able to call `new` on this class. As such, while <JSON::PP>, <JSON::XS>, <Cpanel::JSON::XS> and <JSON::MaybeXS> will work for this, to use <Mojo::JSON> or <JSON::Tiny> for decoding requires setting ["CPAN\_META\_JSON\_DECODER"](#CPAN_META_JSON_DECODER).
### PERL\_JSON\_BACKEND
If the `CPAN_META_JSON_BACKEND` environment variable does not exist, and if `PERL_JSON_BACKEND` environment variable exists, is true and is not "JSON::PP", then the [JSON](json) module (version 2.5 or greater) will be loaded and used to interpret `PERL_JSON_BACKEND`. If [JSON](json) is not installed or is too old, an exception will be thrown. Note that at the time of writing, the only useful values are 1, which will tell [JSON](json) to guess, or <JSON::XS> - if you want to use a newer JSON module, see ["CPAN\_META\_JSON\_BACKEND"](#CPAN_META_JSON_BACKEND).
### PERL\_YAML\_BACKEND
By default, <CPAN::Meta::YAML> will be used for deserializing YAML data. If the `PERL_YAML_BACKEND` environment variable is defined, then it is interpreted as a module to use for deserialization. The given module must be installed, must load correctly and must implement the `Load()` function or an exception will be thrown.
AUTHORS
-------
* David Golden <[email protected]>
* Ricardo Signes <[email protected]>
* Adam Kennedy <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by David Golden, Ricardo Signes, Adam Kennedy and Contributors.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl Pod::Simple::HTML Pod::Simple::HTML
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CALLING FROM THE COMMAND LINE](#CALLING-FROM-THE-COMMAND-LINE)
* [CALLING FROM PERL](#CALLING-FROM-PERL)
+ [Minimal code](#Minimal-code)
+ [More detailed example](#More-detailed-example)
* [METHODS](#METHODS)
+ [html\_css](#html_css)
+ [html\_javascript](#html_javascript)
+ [title\_prefix](#title_prefix)
+ [title\_postfix](#title_postfix)
+ [html\_header\_before\_title](#html_header_before_title)
+ [top\_anchor](#top_anchor)
+ [html\_h\_level](#html_h_level)
+ [index](#index)
+ [html\_header\_after\_title](#html_header_after_title)
+ [html\_footer](#html_footer)
* [SUBCLASSING](#SUBCLASSING)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::HTML - convert Pod to HTML
SYNOPSIS
--------
```
perl -MPod::Simple::HTML -e Pod::Simple::HTML::go thingy.pod
```
DESCRIPTION
-----------
This class is for making an HTML rendering of a Pod document.
This is a subclass of <Pod::Simple::PullParser> and inherits all its methods (and options).
Note that if you want to do a batch conversion of a lot of Pod documents to HTML, you should see the module <Pod::Simple::HTMLBatch>.
CALLING FROM THE COMMAND LINE
------------------------------
TODO
```
perl -MPod::Simple::HTML -e Pod::Simple::HTML::go Thing.pod Thing.html
```
CALLING FROM PERL
------------------
###
Minimal code
```
use Pod::Simple::HTML;
my $p = Pod::Simple::HTML->new;
$p->output_string(\my $html);
$p->parse_file('path/to/Module/Name.pm');
open my $out, '>', 'out.html' or die "Cannot open 'out.html': $!\n";
print $out $html;
```
###
More detailed example
```
use Pod::Simple::HTML;
```
Set the content type:
```
$Pod::Simple::HTML::Content_decl = q{<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >};
my $p = Pod::Simple::HTML->new;
```
Include a single javascript source:
```
$p->html_javascript('http://abc.com/a.js');
```
Or insert multiple javascript source in the header (or for that matter include anything, thought this is not recommended)
```
$p->html_javascript('
<script type="text/javascript" src="http://abc.com/b.js"></script>
<script type="text/javascript" src="http://abc.com/c.js"></script>');
```
Include a single css source in the header:
```
$p->html_css('/style.css');
```
or insert multiple css sources:
```
$p->html_css('
<link rel="stylesheet" type="text/css" title="pod_stylesheet" href="http://remote.server.com/jquery.css">
<link rel="stylesheet" type="text/css" title="pod_stylesheet" href="/style.css">');
```
Tell the parser where should the output go. In this case it will be placed in the $html variable:
```
my $html;
$p->output_string(\$html);
```
Parse and process a file with pod in it:
```
$p->parse_file('path/to/Module/Name.pm');
```
METHODS
-------
TODO all (most?) accessorized methods
The following variables need to be set **before** the call to the ->new constructor.
Set the string that is included before the opening <html> tag:
```
$Pod::Simple::HTML::Doctype_decl = qq{<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">\n};
```
Set the content-type in the HTML head: (defaults to ISO-8859-1)
```
$Pod::Simple::HTML::Content_decl = q{<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >};
```
Set the value that will be embedded in the opening tags of F, C tags and verbatim text. F maps to <em>, C maps to <code>, Verbatim text maps to <pre> (Computerese defaults to "")
```
$Pod::Simple::HTML::Computerese = ' class="some_class_name';
```
### html\_css
### html\_javascript
### title\_prefix
### title\_postfix
### html\_header\_before\_title
This includes everything before the <title> opening tag including the Document type and including the opening <title> tag. The following call will set it to be a simple HTML file:
```
$p->html_header_before_title('<html><head><title>');
```
### top\_anchor
By default Pod::Simple::HTML adds a dummy anchor at the top of the HTML. You can change it by calling
```
$p->top_anchor('<a name="zz" >');
```
### html\_h\_level
Normally =head1 will become <h1>, =head2 will become <h2> etc. Using the html\_h\_level method will change these levels setting the h level of =head1 tags:
```
$p->html_h_level(3);
```
Will make sure that =head1 will become <h3> and =head2 will become <h4> etc...
### index
Set it to some true value if you want to have an index (in reality a table of contents) to be added at the top of the generated HTML.
```
$p->index(1);
```
### html\_header\_after\_title
Includes the closing tag of </title> and through the rest of the head till the opening of the body
```
$p->html_header_after_title('</title>...</head><body id="my_id">');
```
### html\_footer
The very end of the document:
```
$p->html_footer( qq[\n<!-- end doc -->\n\n</body></html>\n] );
```
SUBCLASSING
-----------
Can use any of the methods described above but for further customization one needs to override some of the methods:
```
package My::Pod;
use strict;
use warnings;
use base 'Pod::Simple::HTML';
# needs to return a URL string such
# http://some.other.com/page.html
# #anchor_in_the_same_file
# /internal/ref.html
sub do_pod_link {
# My::Pod object and Pod::Simple::PullParserStartToken object
my ($self, $link) = @_;
say $link->tagname; # will be L for links
say $link->attr('to'); #
say $link->attr('type'); # will be 'pod' always
say $link->attr('section');
# Links local to our web site
if ($link->tagname eq 'L' and $link->attr('type') eq 'pod') {
my $to = $link->attr('to');
if ($to =~ /^Padre::/) {
$to =~ s{::}{/}g;
return "/docs/Padre/$to.html";
}
}
# all other links are generated by the parent class
my $ret = $self->SUPER::do_pod_link($link);
return $ret;
}
1;
```
Meanwhile in script.pl:
```
use My::Pod;
my $p = My::Pod->new;
my $html;
$p->output_string(\$html);
$p->parse_file('path/to/Module/Name.pm');
open my $out, '>', 'out.html' or die;
print $out $html;
```
TODO
maybe override do\_beginning do\_end
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::HTMLBatch>
TODO: a corpus of sample Pod input and HTML output? Or common idioms?
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002-2004 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
ACKNOWLEDGEMENTS
----------------
Thanks to [Hurricane Electric](http://he.net/) for permission to use its [Linux man pages online](http://man.he.net/) site for man page links.
Thanks to [search.cpan.org](http://search.cpan.org/) for permission to use the site for Perl module links.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
| programming_docs |
perl Test::Tester::CaptureRunner Test::Tester::CaptureRunner
===========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
Test::Tester::CaptureRunner - Help testing test modules built with Test::Builder
DESCRIPTION
-----------
This stuff if needed to allow me to play with other ways of monitoring the test results.
AUTHOR
------
Copyright 2003 by Fergal Daly <[email protected]>.
LICENSE
-------
Under the same license as Perl itself
See http://www.perl.com/perl/misc/Artistic.html
perl File::Spec::OS2 File::Spec::OS2
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
File::Spec::OS2 - methods for OS/2 file specs
SYNOPSIS
--------
```
require File::Spec::OS2; # Done internally by File::Spec if needed
```
DESCRIPTION
-----------
See <File::Spec> and <File::Spec::Unix>. This package overrides the implementation of these methods, not the semantics.
Amongst the changes made for OS/2 are...
tmpdir Modifies the list of places temp directory information is looked for.
```
$ENV{TMPDIR}
$ENV{TEMP}
$ENV{TMP}
/tmp
/
```
splitpath Volumes can be drive letters or UNC sharenames (\\server\share).
COPYRIGHT
---------
Copyright (c) 2004 by the Perl 5 Porters. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl TAP::Parser::Result::Plan TAP::Parser::Result::Plan
=========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDDEN METHODS](#OVERRIDDEN-METHODS)
+ [Instance Methods](#Instance-Methods)
- [plan](#plan)
- [tests\_planned](#tests_planned)
- [directive](#directive)
- [has\_skip](#has_skip)
- [explanation](#explanation)
- [todo\_list](#todo_list)
NAME
----
TAP::Parser::Result::Plan - Plan result token.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This is a subclass of <TAP::Parser::Result>. A token of this class will be returned if a plan line is encountered.
```
1..1
ok 1 - woo hooo!
```
`1..1` is the plan. Gotta have a plan.
OVERRIDDEN METHODS
-------------------
Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night.
* `as_string`
* `raw`
###
Instance Methods
#### `plan`
```
if ( $result->is_plan ) {
print $result->plan;
}
```
This is merely a synonym for `as_string`.
#### `tests_planned`
```
my $planned = $result->tests_planned;
```
Returns the number of tests planned. For example, a plan of `1..17` will cause this method to return '17'.
#### `directive`
```
my $directive = $plan->directive;
```
If a SKIP directive is included with the plan, this method will return it.
```
1..0 # SKIP: why bother?
```
#### `has_skip`
```
if ( $result->has_skip ) { ... }
```
Returns a boolean value indicating whether or not this test has a SKIP directive.
#### `explanation`
```
my $explanation = $plan->explanation;
```
If a SKIP directive was included with the plan, this method will return the explanation, if any.
#### `todo_list`
```
my $todo = $result->todo_list;
for ( @$todo ) {
...
}
```
perl File::Fetch File::Fetch
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [ACCESSORS](#ACCESSORS)
* [METHODS](#METHODS)
+ [$ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' );](#%24ff-=-File::Fetch-%3Enew(-uri-=%3E-'http://some.where.com/dir/file.txt'-);)
+ [$where = $ff->fetch( [to => /my/output/dir/ | \$scalar] )](#%24where-=-%24ff-%3Efetch(-%5Bto-=%3E-/my/output/dir/-%7C-%5C%24scalar%5D-))
+ [$ff->error([BOOL])](#%24ff-%3Eerror(%5BBOOL%5D))
* [HOW IT WORKS](#HOW-IT-WORKS)
* [GLOBAL VARIABLES](#GLOBAL-VARIABLES)
+ [$File::Fetch::FROM\_EMAIL](#%24File::Fetch::FROM_EMAIL)
+ [$File::Fetch::USER\_AGENT](#%24File::Fetch::USER_AGENT)
+ [$File::Fetch::FTP\_PASSIVE](#%24File::Fetch::FTP_PASSIVE)
+ [$File::Fetch::TIMEOUT](#%24File::Fetch::TIMEOUT)
+ [$File::Fetch::WARN](#%24File::Fetch::WARN)
+ [$File::Fetch::DEBUG](#%24File::Fetch::DEBUG)
+ [$File::Fetch::BLACKLIST](#%24File::Fetch::BLACKLIST)
+ [$File::Fetch::METHOD\_FAIL](#%24File::Fetch::METHOD_FAIL)
* [MAPPING](#MAPPING)
* [FREQUENTLY ASKED QUESTIONS](#FREQUENTLY-ASKED-QUESTIONS)
+ [So how do I use a proxy with File::Fetch?](#So-how-do-I-use-a-proxy-with-File::Fetch?)
+ [I used 'lynx' to fetch a file, but its contents is all wrong!](#I-used-'lynx'-to-fetch-a-file,-but-its-contents-is-all-wrong!)
+ [Files I'm trying to fetch have reserved characters or non-ASCII characters in them. What do I do?](#Files-I'm-trying-to-fetch-have-reserved-characters-or-non-ASCII-characters-in-them.-What-do-I-do?)
* [TODO](#TODO)
* [BUG REPORTS](#BUG-REPORTS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
File::Fetch - A generic file fetching mechanism
SYNOPSIS
--------
```
use File::Fetch;
### build a File::Fetch object ###
my $ff = File::Fetch->new(uri => 'http://some.where.com/dir/a.txt');
### fetch the uri to cwd() ###
my $where = $ff->fetch() or die $ff->error;
### fetch the uri to /tmp ###
my $where = $ff->fetch( to => '/tmp' );
### parsed bits from the uri ###
$ff->uri;
$ff->scheme;
$ff->host;
$ff->path;
$ff->file;
```
DESCRIPTION
-----------
File::Fetch is a generic file fetching mechanism.
It allows you to fetch any file pointed to by a `ftp`, `http`, `file`, `git` or `rsync` uri by a number of different means.
See the `HOW IT WORKS` section further down for details.
ACCESSORS
---------
A `File::Fetch` object has the following accessors
$ff->uri The uri you passed to the constructor
$ff->scheme The scheme from the uri (like 'file', 'http', etc)
$ff->host The hostname in the uri. Will be empty if host was originally 'localhost' for a 'file://' url.
$ff->vol On operating systems with the concept of a volume the second element of a file:// is considered to the be volume specification for the file. Thus on Win32 this routine returns the volume, on other operating systems this returns nothing.
On Windows this value may be empty if the uri is to a network share, in which case the 'share' property will be defined. Additionally, volume specifications that use '|' as ':' will be converted on read to use ':'.
On VMS, which has a volume concept, this field will be empty because VMS file specifications are converted to absolute UNIX format and the volume information is transparently included.
$ff->share On systems with the concept of a network share (currently only Windows) returns the sharename from a file://// url. On other operating systems returns empty.
$ff->path The path from the uri, will be at least a single '/'.
$ff->file The name of the remote file. For the local file name, the result of $ff->output\_file will be used.
$ff->file\_default The name of the default local file, that $ff->output\_file falls back to if it would otherwise return no filename. For example when fetching a URI like http://www.abc.net.au/ the contents retrieved may be from a remote file called 'index.html'. The default value of this attribute is literally 'file\_default'.
$ff->output\_file The name of the output file. This is the same as $ff->file, but any query parameters are stripped off. For example:
```
http://example.com/index.html?x=y
```
would make the output file be `index.html` rather than `index.html?x=y`.
METHODS
-------
###
$ff = File::Fetch->new( uri => 'http://some.where.com/dir/file.txt' );
Parses the uri and creates a corresponding File::Fetch::Item object, that is ready to be `fetch`ed and returns it.
Returns false on failure.
###
$where = $ff->fetch( [to => /my/output/dir/ | \$scalar] )
Fetches the file you requested and returns the full path to the file.
By default it writes to `cwd()`, but you can override that by specifying the `to` argument:
```
### file fetch to /tmp, full path to the file in $where
$where = $ff->fetch( to => '/tmp' );
### file slurped into $scalar, full path to the file in $where
### file is downloaded to a temp directory and cleaned up at exit time
$where = $ff->fetch( to => \$scalar );
```
Returns the full path to the downloaded file on success, and false on failure.
###
$ff->error([BOOL])
Returns the last encountered error as string. Pass it a true value to get the `Carp::longmess()` output instead.
HOW IT WORKS
-------------
File::Fetch is able to fetch a variety of uris, by using several external programs and modules.
Below is a mapping of what utilities will be used in what order for what schemes, if available:
```
file => LWP, lftp, file
http => LWP, HTTP::Tiny, wget, curl, lftp, fetch, HTTP::Lite, lynx, iosock
ftp => LWP, Net::FTP, wget, curl, lftp, fetch, ncftp, ftp
rsync => rsync
git => git
```
If you'd like to disable the use of one or more of these utilities and/or modules, see the `$BLACKLIST` variable further down.
If a utility or module isn't available, it will be marked in a cache (see the `$METHOD_FAIL` variable further down), so it will not be tried again. The `fetch` method will only fail when all options are exhausted, and it was not able to retrieve the file.
The `fetch` utility is available on FreeBSD. NetBSD and Dragonfly BSD may also have it from `pkgsrc`. We only check for `fetch` on those three platforms.
`iosock` is a very limited <IO::Socket::INET> based mechanism for retrieving `http` schemed urls. It doesn't follow redirects for instance.
`git` only supports `git://` style urls.
A special note about fetching files from an ftp uri:
By default, all ftp connections are done in passive mode. To change that, see the `$FTP_PASSIVE` variable further down.
Furthermore, ftp uris only support anonymous connections, so no named user/password pair can be passed along.
`/bin/ftp` is blacklisted by default; see the `$BLACKLIST` variable further down.
GLOBAL VARIABLES
-----------------
The behaviour of File::Fetch can be altered by changing the following global variables:
###
$File::Fetch::FROM\_EMAIL
This is the email address that will be sent as your anonymous ftp password.
Default is `[email protected]`.
###
$File::Fetch::USER\_AGENT
This is the useragent as `LWP` will report it.
Default is `File::Fetch/$VERSION`.
###
$File::Fetch::FTP\_PASSIVE
This variable controls whether the environment variable `FTP_PASSIVE` and any passive switches to commandline tools will be set to true.
Default value is 1.
Note: When $FTP\_PASSIVE is true, `ncftp` will not be used to fetch files, since passive mode can only be set interactively for this binary
###
$File::Fetch::TIMEOUT
When set, controls the network timeout (counted in seconds).
Default value is 0.
###
$File::Fetch::WARN
This variable controls whether errors encountered internally by `File::Fetch` should be `carp`'d or not.
Set to false to silence warnings. Inspect the output of the `error()` method manually to see what went wrong.
Defaults to `true`.
###
$File::Fetch::DEBUG
This enables debugging output when calling commandline utilities to fetch files. This also enables `Carp::longmess` errors, instead of the regular `carp` errors.
Good for tracking down why things don't work with your particular setup.
Default is 0.
###
$File::Fetch::BLACKLIST
This is an array ref holding blacklisted modules/utilities for fetching files with.
To disallow the use of, for example, `LWP` and `Net::FTP`, you could set $File::Fetch::BLACKLIST to:
```
$File::Fetch::BLACKLIST = [qw|lwp netftp|]
```
The default blacklist is [qw|ftp|], as `/bin/ftp` is rather unreliable.
See the note on `MAPPING` below.
###
$File::Fetch::METHOD\_FAIL
This is a hashref registering what modules/utilities were known to fail for fetching files (mostly because they weren't installed).
You can reset this cache by assigning an empty hashref to it, or individually remove keys.
See the note on `MAPPING` below.
MAPPING
-------
Here's a quick mapping for the utilities/modules, and their names for the $BLACKLIST, $METHOD\_FAIL and other internal functions.
```
LWP => lwp
HTTP::Lite => httplite
HTTP::Tiny => httptiny
Net::FTP => netftp
wget => wget
lynx => lynx
ncftp => ncftp
ftp => ftp
curl => curl
rsync => rsync
lftp => lftp
fetch => fetch
IO::Socket => iosock
```
FREQUENTLY ASKED QUESTIONS
---------------------------
###
So how do I use a proxy with File::Fetch?
`File::Fetch` currently only supports proxies with LWP::UserAgent. You will need to set your environment variables accordingly. For example, to use an ftp proxy:
```
$ENV{ftp_proxy} = 'foo.com';
```
Refer to the LWP::UserAgent manpage for more details.
###
I used 'lynx' to fetch a file, but its contents is all wrong!
`lynx` can only fetch remote files by dumping its contents to `STDOUT`, which we in turn capture. If that content is a 'custom' error file (like, say, a `404 handler`), you will get that contents instead.
Sadly, `lynx` doesn't support any options to return a different exit code on non-`200 OK` status, giving us no way to tell the difference between a 'successful' fetch and a custom error page.
Therefor, we recommend to only use `lynx` as a last resort. This is why it is at the back of our list of methods to try as well.
###
Files I'm trying to fetch have reserved characters or non-ASCII characters in them. What do I do?
`File::Fetch` is relatively smart about things. When trying to write a file to disk, it removes the `query parameters` (see the `output_file` method for details) from the file name before creating it. In most cases this suffices.
If you have any other characters you need to escape, please install the `URI::Escape` module from CPAN, and pre-encode your URI before passing it to `File::Fetch`. You can read about the details of URIs and URI encoding here:
<https://datatracker.ietf.org/doc/html/rfc2396>
TODO
----
Implement $PREFER\_BIN To indicate to rather use commandline tools than modules
BUG REPORTS
------------
Please report bugs or other issues to <[email protected]<gt>.
AUTHOR
------
This module by Jos Boumans <[email protected]>.
COPYRIGHT
---------
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
perl podchecker podchecker
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS AND ARGUMENTS](#OPTIONS-AND-ARGUMENTS)
* [DESCRIPTION](#DESCRIPTION)
* [RETURN VALUE](#RETURN-VALUE)
* [ERRORS](#ERRORS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
NAME
----
podchecker - check the syntax of POD format documentation files
SYNOPSIS
--------
**podchecker** [**-help**] [**-man**] [**-(no)warnings**] [*file*...]
OPTIONS AND ARGUMENTS
----------------------
**-help**
Print a brief help message and exit.
**-man**
Print the manual page and exit.
**-warnings** **-nowarnings**
Turn on/off printing of warnings. Repeating **-warnings** increases the warning level, i.e. more warnings are printed. Currently increasing to level two causes flagging of unescaped "<,>" characters.
*file* The pathname of a POD file to syntax-check (defaults to standard input).
DESCRIPTION
-----------
**podchecker** will read the given input files looking for POD syntax errors in the POD documentation and will print any errors it find to STDERR. At the end, it will print a status message indicating the number of errors found.
Directories are ignored, an appropriate warning message is printed.
**podchecker** invokes the **podchecker()** function exported by **Pod::Checker** Please see ["podchecker()" in Pod::Checker](Pod::Checker#podchecker%28%29) for more details.
RETURN VALUE
-------------
**podchecker** returns a 0 (zero) exit status if all specified POD files are ok.
ERRORS
------
**podchecker** returns the exit status 1 if at least one of the given POD files has syntax errors.
The status 2 indicates that at least one of the specified files does not contain *any* POD commands.
Status 1 overrides status 2. If you want unambiguous results, call **podchecker** with one single argument only.
SEE ALSO
---------
<Pod::Simple> and <Pod::Checker>
AUTHORS
-------
Please report bugs using <http://rt.cpan.org>.
Brad Appleton <[email protected]>, Marek Rouchal <[email protected]>
Based on code for **Pod::Text::pod2text(1)** written by Tom Christiansen <[email protected]>
perl JSON::PP::Boolean JSON::PP::Boolean
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
JSON::PP::Boolean - dummy module providing JSON::PP::Boolean
SYNOPSIS
--------
```
# do not "use" yourself
```
DESCRIPTION
-----------
This module exists only to provide overload resolution for Storable and similar modules. See <JSON::PP> for more info about this class.
AUTHOR
------
This idea is from <JSON::XS::Boolean> written by Marc Lehmann <schmorp[at]schmorp.de>
LICENSE
-------
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl File::Find File::Find
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [%options](#%25options)
+ [The wanted function](#The-wanted-function)
* [WARNINGS](#WARNINGS)
* [BUGS AND CAVEATS](#BUGS-AND-CAVEATS)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Find - Traverse a directory tree.
SYNOPSIS
--------
```
use File::Find;
find(\&wanted, @directories_to_search);
sub wanted { ... }
use File::Find;
finddepth(\&wanted, @directories_to_search);
sub wanted { ... }
use File::Find;
find({ wanted => \&process, follow => 1 }, '.');
```
DESCRIPTION
-----------
These are functions for searching through directory trees doing work on each file found similar to the Unix *find* command. File::Find exports two functions, `find` and `finddepth`. They work similarly but have subtle differences.
**find**
```
find(\&wanted, @directories);
find(\%options, @directories);
```
`find()` does a depth-first search over the given `@directories` in the order they are given. For each file or directory found, it calls the `&wanted` subroutine. (See below for details on how to use the `&wanted` function). Additionally, for each directory found, it will `chdir()` into that directory and continue the search, invoking the `&wanted` function on each file or subdirectory in the directory.
**finddepth**
```
finddepth(\&wanted, @directories);
finddepth(\%options, @directories);
```
`finddepth()` works just like `find()` except that it invokes the `&wanted` function for a directory *after* invoking it for the directory's contents. It does a postorder traversal instead of a preorder traversal, working from the bottom of the directory tree up where `find()` works from the top of the tree down.
Despite the name of the `finddepth()` function, both `find()` and `finddepth()` perform a depth-first search of the directory hierarchy.
###
%options
The first argument to `find()` is either a code reference to your `&wanted` function, or a hash reference describing the operations to be performed for each file. The code reference is described in ["The wanted function"](#The-wanted-function) below.
Here are the possible keys for the hash:
`wanted` The value should be a code reference. This code reference is described in ["The wanted function"](#The-wanted-function) below. The `&wanted` subroutine is mandatory.
`bydepth` Reports the name of a directory only AFTER all its entries have been reported. Entry point `finddepth()` is a shortcut for specifying `{ bydepth => 1 }` in the first argument of `find()`.
`preprocess` The value should be a code reference. This code reference is used to preprocess the current directory. The name of the currently processed directory is in `$File::Find::dir`. Your preprocessing function is called after `readdir()`, but before the loop that calls the `wanted()` function. It is called with a list of strings (actually file/directory names) and is expected to return a list of strings. The code can be used to sort the file/directory names alphabetically, numerically, or to filter out directory entries based on their name alone. When *follow* or *follow\_fast* are in effect, `preprocess` is a no-op.
`postprocess` The value should be a code reference. It is invoked just before leaving the currently processed directory. It is called in void context with no arguments. The name of the current directory is in `$File::Find::dir`. This hook is handy for summarizing a directory, such as calculating its disk usage. When *follow* or *follow\_fast* are in effect, `postprocess` is a no-op.
`follow` Causes symbolic links to be followed. Since directory trees with symbolic links (followed) may contain files more than once and may even have cycles, a hash has to be built up with an entry for each file. This might be expensive both in space and time for a large directory tree. See ["follow\_fast"](#follow_fast) and ["follow\_skip"](#follow_skip) below. If either *follow* or *follow\_fast* is in effect:
* It is guaranteed that an *lstat* has been called before the user's `wanted()` function is called. This enables fast file checks involving `_`. Note that this guarantee no longer holds if *follow* or *follow\_fast* are not set.
* There is a variable `$File::Find::fullname` which holds the absolute pathname of the file with all symbolic links resolved. If the link is a dangling symbolic link, then fullname will be set to `undef`.
This is a no-op on Win32.
`follow_fast` This is similar to *follow* except that it may report some files more than once. It does detect cycles, however. Since only symbolic links have to be hashed, this is much cheaper both in space and time. If processing a file more than once (by the user's `wanted()` function) is worse than just taking time, the option *follow* should be used.
This is also a no-op on Win32.
`follow_skip` `follow_skip==1`, which is the default, causes all files which are neither directories nor symbolic links to be ignored if they are about to be processed a second time. If a directory or a symbolic link are about to be processed a second time, File::Find dies.
`follow_skip==0` causes File::Find to die if any file is about to be processed a second time.
`follow_skip==2` causes File::Find to ignore any duplicate files and directories but to proceed normally otherwise.
`dangling_symlinks` Specifies what to do with symbolic links whose target doesn't exist. If true and a code reference, will be called with the symbolic link name and the directory it lives in as arguments. Otherwise, if true and warnings are on, a warning of the form `"symbolic_link_name is a dangling symbolic link\n"` will be issued. If false, the dangling symbolic link will be silently ignored.
`no_chdir` Does not `chdir()` to each directory as it recurses. The `wanted()` function will need to be aware of this, of course. In this case, `$_` will be the same as `$File::Find::name`.
`untaint` If find is used in [taint-mode](perlsec#Taint-mode) (-T command line switch or if EUID != UID or if EGID != GID), then internally directory names have to be untainted before they can be `chdir`'d to. Therefore they are checked against a regular expression *untaint\_pattern*. Note that all names passed to the user's `wanted()` function are still tainted. If this option is used while not in taint-mode, `untaint` is a no-op.
`untaint_pattern` See above. This should be set using the `qr` quoting operator. The default is set to `qr|^([-+@\w./]+)$|`. Note that the parentheses are vital.
`untaint_skip` If set, a directory which fails the *untaint\_pattern* is skipped, including all its sub-directories. The default is to `die` in such a case.
###
The wanted function
The `wanted()` function does whatever verifications you want on each file and directory. Note that despite its name, the `wanted()` function is a generic callback function, and does **not** tell File::Find if a file is "wanted" or not. In fact, its return value is ignored.
The wanted function takes no arguments but rather does its work through a collection of variables.
`$File::Find::dir` is the current directory name,
`$_` is the current filename within that directory
`$File::Find::name` is the complete pathname to the file. The above variables have all been localized and may be changed without affecting data outside of the wanted function.
For example, when examining the file */some/path/foo.ext* you will have:
```
$File::Find::dir = /some/path/
$_ = foo.ext
$File::Find::name = /some/path/foo.ext
```
You are chdir()'d to `$File::Find::dir` when the function is called, unless `no_chdir` was specified. Note that when changing to directories is in effect, the root directory (*/*) is a somewhat special case inasmuch as the concatenation of `$File::Find::dir`, `'/'` and `$_` is not literally equal to `$File::Find::name`. The table below summarizes all variants:
```
$File::Find::name $File::Find::dir $_
default / / .
no_chdir=>0 /etc / etc
/etc/x /etc x
no_chdir=>1 / / /
/etc / /etc
/etc/x /etc /etc/x
```
When `follow` or `follow_fast` are in effect, there is also a `$File::Find::fullname`. The function may set `$File::Find::prune` to prune the tree unless `bydepth` was specified. Unless `follow` or `follow_fast` is specified, for compatibility reasons (find.pl, find2perl) there are in addition the following globals available: `$File::Find::topdir`, `$File::Find::topdev`, `$File::Find::topino`, `$File::Find::topmode` and `$File::Find::topnlink`.
This library is useful for the `find2perl` tool (distributed as part of the App-find2perl CPAN distribution), which when fed,
```
find2perl / -name .nfs\* -mtime +7 \
-exec rm -f {} \; -o -fstype nfs -prune
```
produces something like:
```
sub wanted {
/^\.nfs.*\z/s &&
(($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_)) &&
int(-M _) > 7 &&
unlink($_)
||
($nlink || (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_))) &&
$dev < 0 &&
($File::Find::prune = 1);
}
```
Notice the `_` in the above `int(-M _)`: the `_` is a magical filehandle that caches the information from the preceding `stat()`, `lstat()`, or filetest.
Here's another interesting wanted function. It will find all symbolic links that don't resolve:
```
sub wanted {
-l && !-e && print "bogus link: $File::Find::name\n";
}
```
Note that you may mix directories and (non-directory) files in the list of directories to be searched by the `wanted()` function.
```
find(\&wanted, "./foo", "./bar", "./baz/epsilon");
```
In the example above, no file in *./baz/* other than *./baz/epsilon* will be evaluated by `wanted()`.
See also the script `pfind` on CPAN for a nice application of this module.
WARNINGS
--------
If you run your program with the `-w` switch, or if you use the `warnings` pragma, File::Find will report warnings for several weird situations. You can disable these warnings by putting the statement
```
no warnings 'File::Find';
```
in the appropriate scope. See <warnings> for more info about lexical warnings.
BUGS AND CAVEATS
-----------------
$dont\_use\_nlink You can set the variable `$File::Find::dont_use_nlink` to 0 if you are sure the filesystem you are scanning reflects the number of subdirectories in the parent directory's `nlink` count.
If you do set `$File::Find::dont_use_nlink` to 0, you may notice an improvement in speed at the risk of not recursing into subdirectories if a filesystem doesn't populate `nlink` as expected.
`$File::Find::dont_use_nlink` now defaults to 1 on all platforms.
symlinks Be aware that the option to follow symbolic links can be dangerous. Depending on the structure of the directory tree (including symbolic links to directories) you might traverse a given (physical) directory more than once (only if `follow_fast` is in effect). Furthermore, deleting or changing files in a symbolically linked directory might cause very unpleasant surprises, since you delete or change files in an unknown directory.
HISTORY
-------
File::Find used to produce incorrect results if called recursively. During the development of perl 5.8 this bug was fixed. The first fixed version of File::Find was 1.01.
SEE ALSO
---------
[find(1)](http://man.he.net/man1/find), find2perl.
| programming_docs |
perl FindBin FindBin
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTABLE VARIABLES](#EXPORTABLE-VARIABLES)
* [KNOWN ISSUES](#KNOWN-ISSUES)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
FindBin - Locate directory of original perl script
SYNOPSIS
--------
```
use FindBin;
use lib "$FindBin::Bin/../lib";
or
use FindBin qw($Bin);
use lib "$Bin/../lib";
```
DESCRIPTION
-----------
Locates the full path to the script bin directory to allow the use of paths relative to the bin directory.
This allows a user to setup a directory tree for some software with directories `<root>/bin` and `<root>/lib`, and then the above example will allow the use of modules in the lib directory without knowing where the software tree is installed.
If perl is invoked using the **-e** option or the perl script is read from `STDIN` then FindBin sets both `$Bin` and `$RealBin` to the current directory.
EXPORTABLE VARIABLES
---------------------
```
$Bin - path to bin directory from where script was invoked
$Script - basename of script from which perl was invoked
$RealBin - $Bin with all links resolved
$RealScript - $Script with all links resolved
```
KNOWN ISSUES
-------------
If there are two modules using `FindBin` from different directories under the same interpreter, this won't work. Since `FindBin` uses a `BEGIN` block, it'll be executed only once, and only the first caller will get it right. This is a problem under mod\_perl and other persistent Perl environments, where you shouldn't use this module. Which also means that you should avoid using `FindBin` in modules that you plan to put on CPAN. To make sure that `FindBin` will work is to call the `again` function:
```
use FindBin;
FindBin::again(); # or FindBin->again;
```
In former versions of FindBin there was no `again` function. The workaround was to force the `BEGIN` block to be executed again:
```
delete $INC{'FindBin.pm'};
require FindBin;
```
AUTHORS
-------
FindBin is supported as part of the core perl distribution. Please submit bug reports at <https://github.com/Perl/perl5/issues>.
Graham Barr <*[email protected]*> Nick Ing-Simmons <*[email protected]*>
COPYRIGHT
---------
Copyright (c) 1995 Graham Barr & Nick Ing-Simmons. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Test2::EventFacet::Error Test2::EventFacet::Error
========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [FIELDS](#FIELDS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Error - Facet for errors that need to be shown.
DESCRIPTION
-----------
This facet is used when an event needs to convey errors.
NOTES
-----
This facet has the hash key `'errors'`, and is a list of facets instead of a single item.
FIELDS
------
$string = $error->{details}
$string = $error->details() Explanation of the error, or the error itself (such as an exception). In perl exceptions may be blessed objects, so this field may contain a blessed object.
$short\_string = $error->{tag}
$short\_string = $error->tag() Short tag to categorize the error. This is usually 10 characters or less, formatters may truncate longer tags.
$bool = $error->{fail}
$bool = $error->fail() Not all errors are fatal, some are displayed having already been handled. Set this to true if you want the error to cause the test to fail. Without this the error is simply a diagnostics message that has no effect on the overall pass/fail result.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl DBM_Filter::utf8 DBM\_Filter::utf8
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter::utf8 - filter for DBM\_Filter
SYNOPSIS
--------
```
use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File
use DBM_Filter;
$db = tie %hash, ...
$db->Filter_Push('utf8');
```
DESCRIPTION
-----------
This Filter will ensure that all data written to the DBM will be encoded in UTF-8.
This module uses the Encode module.
SEE ALSO
---------
[DBM\_Filter](dbm_filter), <perldbmfilter>, [Encode](encode)
AUTHOR
------
Paul Marquess [email protected]
perl Encode::PerlIO Encode::PerlIO
==============
CONTENTS
--------
* [NAME](#NAME)
* [Overview](#Overview)
* [How does it work?](#How-does-it-work?)
* [Line Buffering](#Line-Buffering)
+ [How can I tell whether my encoding fully supports PerlIO ?](#How-can-I-tell-whether-my-encoding-fully-supports-PerlIO-?)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::PerlIO -- a detailed document on Encode and PerlIO
Overview
--------
It is very common to want to do encoding transformations when reading or writing files, network connections, pipes etc. If Perl is configured to use the new 'perlio' IO system then `Encode` provides a "layer" (see [PerlIO](perlio)) which can transform data as it is read or written.
Here is how the blind poet would modernise the encoding:
```
use Encode;
open(my $iliad,'<:encoding(iso-8859-7)','iliad.greek');
open(my $utf8,'>:utf8','iliad.utf8');
my @epic = <$iliad>;
print $utf8 @epic;
close($utf8);
close($illiad);
```
In addition, the new IO system can also be configured to read/write UTF-8 encoded characters (as noted above, this is efficient):
```
open(my $fh,'>:utf8','anything');
print $fh "Any \x{0021} string \N{SMILEY FACE}\n";
```
Either of the above forms of "layer" specifications can be made the default for a lexical scope with the `use open ...` pragma. See <open>.
Once a handle is open, its layers can be altered using `binmode`.
Without any such configuration, or if Perl itself is built using the system's own IO, then write operations assume that the file handle accepts only *bytes* and will `die` if a character larger than 255 is written to the handle. When reading, each octet from the handle becomes a byte-in-a-character. Note that this default is the same behaviour as bytes-only languages (including Perl before v5.6) would have, and is sufficient to handle native 8-bit encodings e.g. iso-8859-1, EBCDIC etc. and any legacy mechanisms for handling other encodings and binary data.
In other cases, it is the program's responsibility to transform characters into bytes using the API above before doing writes, and to transform the bytes read from a handle into characters before doing "character operations" (e.g. `lc`, `/\W+/`, ...).
You can also use PerlIO to convert larger amounts of data you don't want to bring into memory. For example, to convert between ISO-8859-1 (Latin 1) and UTF-8 (or UTF-EBCDIC in EBCDIC machines):
```
open(F, "<:encoding(iso-8859-1)", "data.txt") or die $!;
open(G, ">:utf8", "data.utf") or die $!;
while (<F>) { print G }
# Could also do "print G <F>" but that would pull
# the whole file into memory just to write it out again.
```
More examples:
```
open(my $f, "<:encoding(cp1252)")
open(my $g, ">:encoding(iso-8859-2)")
open(my $h, ">:encoding(latin9)") # iso-8859-15
```
See also <encoding> for how to change the default encoding of the data in your script.
How does it work?
------------------
Here is a crude diagram of how filehandle, PerlIO, and Encode interact.
```
filehandle <-> PerlIO PerlIO <-> scalar (read/printed)
\ /
Encode
```
When PerlIO receives data from either direction, it fills a buffer (currently with 1024 bytes) and passes the buffer to Encode. Encode tries to convert the valid part and passes it back to PerlIO, leaving invalid parts (usually a partial character) in the buffer. PerlIO then appends more data to the buffer, calls Encode again, and so on until the data stream ends.
To do so, PerlIO always calls (de|en)code methods with CHECK set to 1. This ensures that the method stops at the right place when it encounters partial character. The following is what happens when PerlIO and Encode tries to encode (from utf8) more than 1024 bytes and the buffer boundary happens to be in the middle of a character.
```
A B C .... ~ \x{3000} ....
41 42 43 .... 7E e3 80 80 ....
<- buffer --------------->
<< encoded >>>>>>>>>>
<- next buffer ------
```
Encode converts from the beginning to \x7E, leaving \xe3 in the buffer because it is invalid (partial character).
Unfortunately, this scheme does not work well with escape-based encodings such as ISO-2022-JP.
Line Buffering
---------------
Now let's see what happens when you try to decode from ISO-2022-JP and the buffer ends in the middle of a character.
```
JIS208-ESC \x{5f3e}
A B C .... ~ \e $ B |DAN | ....
41 42 43 .... 7E 1b 24 41 43 46 ....
<- buffer --------------------------->
<< encoded >>>>>>>>>>>>>>>>>>>>>>>
```
As you see, the next buffer begins with \x43. But \x43 is 'C' in ASCII, which is wrong in this case because we are now in JISX 0208 area so it has to convert \x43\x46, not \x43. Unlike utf8 and EUC, in escape-based encodings you can't tell if a given octet is a whole character or just part of it.
Fortunately PerlIO also supports line buffer if you tell PerlIO to use one instead of fixed buffer. Since ISO-2022-JP is guaranteed to revert to ASCII at the end of the line, partial character will never happen when line buffer is used.
To tell PerlIO to use line buffer, implement ->needs\_lines method for your encoding object. See <Encode::Encoding> for details.
Thanks to these efforts most encodings that come with Encode support PerlIO but that still leaves following encodings.
```
iso-2022-kr
MIME-B
MIME-Header
MIME-Q
```
Fortunately iso-2022-kr is hardly used (according to Jungshik) and MIME-\* are very unlikely to be fed to PerlIO because they are for mail headers. See <Encode::MIME::Header> for details.
###
How can I tell whether my encoding fully supports PerlIO ?
As of this writing, any encoding whose class belongs to Encode::XS and Encode::Unicode works. The Encode module has a `perlio_ok` method which you can use before applying PerlIO encoding to the filehandle. Here is an example:
```
my $use_perlio = perlio_ok($enc);
my $layer = $use_perlio ? "<:raw" : "<:encoding($enc)";
open my $fh, $layer, $file or die "$file : $!";
while(<$fh>){
$_ = decode($enc, $_) unless $use_perlio;
# ....
}
```
SEE ALSO
---------
<Encode::Encoding>, <Encode::Supported>, <Encode::PerlIO>, <encoding>, <perlebcdic>, ["open" in perlfunc](perlfunc#open), <perlunicode>, <utf8>, the Perl Unicode Mailing List <[email protected]>
perl Unicode::Collate::Locale Unicode::Collate::Locale
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Constructor](#Constructor)
+ [Methods](#Methods)
+ [A list of tailorable locales](#A-list-of-tailorable-locales)
+ [A list of variant codes and their aliases](#A-list-of-variant-codes-and-their-aliases)
* [INSTALL](#INSTALL)
* [CAVEAT](#CAVEAT)
+ [Reference](#Reference)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::Locale - Linguistic tailoring for DUCET via Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate::Locale;
#construct
$Collator = Unicode::Collate::Locale->
new(locale => $locale_name, %tailoring);
#sort
@sorted = $Collator->sort(@not_sorted);
#compare
$result = $Collator->cmp($a, $b); # returns 1, 0, or -1.
```
**Note:** Strings in `@not_sorted`, `$a` and `$b` are interpreted according to Perl's Unicode support. See <perlunicode>, <perluniintro>, <perlunitut>, <perlunifaq>, <utf8>. Otherwise you can use `preprocess` (cf. `Unicode::Collate`) or should decode them before.
DESCRIPTION
-----------
This module provides linguistic tailoring for it taking advantage of `Unicode::Collate`.
### Constructor
The `new` method returns a collator object.
A parameter list for the constructor is a hash, which can include a special key `locale` and its value (case-insensitive) standing for a Unicode base language code (two or three-letter). For example, `Unicode::Collate::Locale->new(locale => 'ES')` returns a collator tailored for Spanish.
`$locale_name` may be suffixed with a Unicode script code (four-letter), a Unicode region (territory) code, a Unicode language variant code. These codes are case-insensitive, and separated with `'_'` or `'-'`. E.g. `en_US` for English in USA, `az_Cyrl` for Azerbaijani in the Cyrillic script, `es_ES_traditional` for Spanish in Spain (Traditional).
If `$locale_name` is not available, fallback is selected in the following order:
```
1. language with a variant code
2. language with a script code
3. language with a region code
4. language
5. default
```
Tailoring tags provided by `Unicode::Collate` are allowed as long as they are not used for `locale` support. Esp. the `table` tag is always untailorable, since it is reserved for DUCET.
However `entry` is allowed, even if it is used for `locale` support, to add or override mappings.
E.g. a collator for Spanish, which ignores diacritics and case difference (i.e. level 1), with reversed case ordering and no normalization.
```
Unicode::Collate::Locale->new(
level => 1,
locale => 'es',
upper_before_lower => 1,
normalization => undef
)
```
Overriding a behavior already tailored by `locale` is disallowed if such a tailoring is passed to `new()`.
```
Unicode::Collate::Locale->new(
locale => 'da',
upper_before_lower => 0, # causes error as reserved by 'da'
)
```
However `change()` inherited from `Unicode::Collate` allows such a tailoring that is reserved by `locale`. Examples:
```
new(locale => 'fr_ca')->change(backwards => undef)
new(locale => 'da')->change(upper_before_lower => 0)
new(locale => 'ja')->change(overrideCJK => undef)
```
### Methods
`Unicode::Collate::Locale` is a subclass of `Unicode::Collate` and methods other than `new` are inherited from `Unicode::Collate`.
Here is a list of additional methods:
`$Collator->getlocale`
Returns a language code accepted and used actually on collation. If linguistic tailoring is not provided for a language code you passed (intensionally for some languages, or due to the incomplete implementation), this method returns a string `'default'` meaning no special tailoring.
`$Collator->locale_version`
(Since Unicode::Collate::Locale 0.87) Returns the version number (perhaps `/\d\.\d\d/`) of the locale, as that of *Locale/\*.pl*.
**Note:** *Locale/\*.pl* that a collator uses should be identified by a combination of return values from `getlocale` and `locale_version`.
###
A list of tailorable locales
```
locale name description
--------------------------------------------------------------
af Afrikaans
ar Arabic
as Assamese
az Azerbaijani (Azeri)
be Belarusian
bn Bengali
bs Bosnian (tailored as Croatian)
bs_Cyrl Bosnian in Cyrillic (tailored as Serbian)
ca Catalan
cs Czech
cu Church Slavic
cy Welsh
da Danish
de__phonebook German (umlaut as 'ae', 'oe', 'ue')
de_AT_phonebook Austrian German (umlaut primary greater)
dsb Lower Sorbian
ee Ewe
eo Esperanto
es Spanish
es__traditional Spanish ('ch' and 'll' as a grapheme)
et Estonian
fa Persian
fi Finnish (v and w are primary equal)
fi__phonebook Finnish (v and w as separate characters)
fil Filipino
fo Faroese
fr_CA Canadian French
gu Gujarati
ha Hausa
haw Hawaiian
he Hebrew
hi Hindi
hr Croatian
hu Hungarian
hy Armenian
ig Igbo
is Icelandic
ja Japanese [1]
kk Kazakh
kl Kalaallisut
kn Kannada
ko Korean [2]
kok Konkani
lkt Lakota
ln Lingala
lt Lithuanian
lv Latvian
mk Macedonian
ml Malayalam
mr Marathi
mt Maltese
nb Norwegian Bokmal
nn Norwegian Nynorsk
nso Northern Sotho
om Oromo
or Oriya
pa Punjabi
pl Polish
ro Romanian
sa Sanskrit
se Northern Sami
si Sinhala
si__dictionary Sinhala (U+0DA5 = U+0DA2,0DCA,0DA4)
sk Slovak
sl Slovenian
sq Albanian
sr Serbian
sr_Latn Serbian in Latin (tailored as Croatian)
sv Swedish (v and w are primary equal)
sv__reformed Swedish (v and w as separate characters)
ta Tamil
te Telugu
th Thai
tn Tswana
to Tonga
tr Turkish
ug_Cyrl Uyghur in Cyrillic
uk Ukrainian
ur Urdu
vi Vietnamese
vo Volapu"k
wae Walser
wo Wolof
yo Yoruba
zh Chinese
zh__big5han Chinese (ideographs: big5 order)
zh__gb2312han Chinese (ideographs: GB-2312 order)
zh__pinyin Chinese (ideographs: pinyin order) [3]
zh__stroke Chinese (ideographs: stroke order) [3]
zh__zhuyin Chinese (ideographs: zhuyin order) [3]
--------------------------------------------------------------
```
Locales according to the default UCA rules include am (Amharic) without `[reorder Ethi]`, bg (Bulgarian) without `[reorder Cyrl]`, chr (Cherokee) without `[reorder Cher]`, de (German), en (English), fr (French), ga (Irish), id (Indonesian), it (Italian), ka (Georgian) without `[reorder Geor]`, mn (Mongolian) without `[reorder Cyrl Mong]`, ms (Malay), nl (Dutch), pt (Portuguese), ru (Russian) without `[reorder Cyrl]`, sw (Swahili), zu (Zulu).
**Note**
[1] ja: Ideographs are sorted in JIS X 0208 order. Fullwidth and halfwidth forms are identical to their regular form. The difference between hiragana and katakana is at the 4th level, the comparison also requires `(variable => 'Non-ignorable')`, and then `katakana_before_hiragana` has no effect.
[2] ko: Plenty of ideographs are sorted by their reading. Such an ideograph is primary (level 1) equal to, and secondary (level 2) greater than, the corresponding hangul syllable.
[3] zh\_\_pinyin, zh\_\_stroke and zh\_\_zhuyin: implemented alt='short', where a smaller number of ideographs are tailored.
###
A list of variant codes and their aliases
```
variant code alias
------------------------------------------
dictionary dict
phonebook phone phonebk
reformed reform
traditional trad
------------------------------------------
big5han big5
gb2312han gb2312
pinyin
stroke
zhuyin
------------------------------------------
```
Note: 'pinyin' is Han in Latin, 'zhuyin' is Han in Bopomofo.
INSTALL
-------
Installation of `Unicode::Collate::Locale` requires *Collate/Locale.pm*, *Collate/Locale/\*.pm*, *Collate/CJK/\*.pm* and *Collate/allkeys.txt*. On building, `Unicode::Collate::Locale` doesn't require any of *data/\*.txt*, *gendata/\**, and *mklocale*. Tests for `Unicode::Collate::Locale` are named *t/loc\_\*.t*.
CAVEAT
------
Tailoring is not maximum Even if a certain letter is tailored, its equivalent would not always tailored as well as it. For example, even though W is tailored, fullwidth W (`U+FF37`), W with acute (`U+1E82`), etc. are not tailored. The result may depend on whether source strings are normalized or not, and whether decomposed or composed. Thus `(normalization => undef)` is less preferred.
Collation reordering is not supported The order of any groups including scripts is not changed.
### Reference
```
locale based CLDR or other reference
--------------------------------------------------------------------
af 30 = 1.8.1
ar 30 = 28 ("compat" wo [reorder Arab]) = 1.9.0
as 30 = 28 (without [reorder Beng..]) = 23
az 30 = 24 ("standard" wo [reorder Latn Cyrl])
be 30 = 28 (without [reorder Cyrl])
bn 30 = 28 ("standard" wo [reorder Beng..]) = 2.0.1
bs 30 = 28 (type="standard": [import hr])
bs_Cyrl 30 = 28 (type="standard": [import sr])
ca 30 = 23 (alt="proposed" type="standard")
cs 30 = 1.8.1 (type="standard")
cu 34 = 30 (without [reorder Cyrl])
cy 30 = 1.8.1
da 22.1 = 1.8.1 (type="standard")
de__phonebook 30 = 2.0 (type="phonebook")
de_AT_phonebook 30 = 27 (type="phonebook")
dsb 30 = 26
ee 30 = 21
eo 30 = 1.8.1
es 30 = 1.9.0 (type="standard")
es__traditional 30 = 1.8.1 (type="traditional")
et 30 = 26
fa 22.1 = 1.8.1
fi 22.1 = 1.8.1 (type="standard" alt="proposed")
fi__phonebook 22.1 = 1.8.1 (type="phonebook")
fil 30 = 1.9.0 (type="standard") = 1.8.1
fo 22.1 = 1.8.1 (alt="proposed" type="standard")
fr_CA 30 = 1.9.0
gu 30 = 28 ("standard" wo [reorder Gujr..]) = 1.9.0
ha 30 = 1.9.0
haw 30 = 24
he 30 = 28 (without [reorder Hebr]) = 23
hi 30 = 28 (without [reorder Deva..]) = 1.9.0
hr 30 = 28 ("standard" wo [reorder Latn Cyrl]) = 1.9.0
hu 22.1 = 1.8.1 (alt="proposed" type="standard")
hy 30 = 28 (without [reorder Armn]) = 1.8.1
ig 30 = 1.8.1
is 22.1 = 1.8.1 (type="standard")
ja 22.1 = 1.8.1 (type="standard")
kk 30 = 28 (without [reorder Cyrl])
kl 22.1 = 1.8.1 (type="standard")
kn 30 = 28 ("standard" wo [reorder Knda..]) = 1.9.0
ko 22.1 = 1.8.1 (type="standard")
kok 30 = 28 (without [reorder Deva..]) = 1.8.1
lkt 30 = 25
ln 30 = 2.0 (type="standard") = 1.8.1
lt 22.1 = 1.9.0
lv 22.1 = 1.9.0 (type="standard") = 1.8.1
mk 30 = 28 (without [reorder Cyrl])
ml 22.1 = 1.9.0
mr 30 = 28 (without [reorder Deva..]) = 1.8.1
mt 22.1 = 1.9.0
nb 22.1 = 2.0 (type="standard")
nn 22.1 = 2.0 (type="standard")
nso [*] 26 = 1.8.1
om 22.1 = 1.8.1
or 30 = 28 (without [reorder Orya..]) = 1.9.0
pa 22.1 = 1.8.1
pl 30 = 1.8.1
ro 30 = 1.9.0 (type="standard")
sa [*] 1.9.1 = 1.8.1 (type="standard" alt="proposed")
se 22.1 = 1.8.1 (type="standard")
si 30 = 28 ("standard" wo [reorder Sinh..]) = 1.9.0
si__dictionary 30 = 28 ("dictionary" wo [reorder Sinh..]) = 1.9.0
sk 22.1 = 1.9.0 (type="standard")
sl 22.1 = 1.8.1 (type="standard" alt="proposed")
sq 22.1 = 1.8.1 (alt="proposed" type="standard")
sr 30 = 28 (without [reorder Cyrl])
sr_Latn 30 = 28 (type="standard": [import hr])
sv 22.1 = 1.9.0 (type="standard")
sv__reformed 22.1 = 1.8.1 (type="reformed")
ta 22.1 = 1.9.0
te 30 = 28 (without [reorder Telu..]) = 1.9.0
th 22.1 = 22
tn [*] 26 = 1.8.1
to 22.1 = 22
tr 22.1 = 1.8.1 (type="standard")
uk 30 = 28 (without [reorder Cyrl])
ug_Cyrl https://en.wikipedia.org/wiki/Uyghur_Cyrillic_alphabet
ur 22.1 = 1.9.0
vi 22.1 = 1.8.1
vo 30 = 25
wae 30 = 2.0
wo [*] 1.9.1 = 1.8.1
yo 30 = 1.8.1
zh 22.1 = 1.8.1 (type="standard")
zh__big5han 22.1 = 1.8.1 (type="big5han")
zh__gb2312han 22.1 = 1.8.1 (type="gb2312han")
zh__pinyin 22.1 = 2.0 (type='pinyin' alt='short')
zh__stroke 22.1 = 1.9.1 (type='stroke' alt='short')
zh__zhuyin 22.1 = 22 (type='zhuyin' alt='short')
--------------------------------------------------------------------
```
[\*] http://www.unicode.org/repos/cldr/tags/latest/seed/collation/
AUTHOR
------
The Unicode::Collate::Locale module for perl was written by SADAHIRO Tomoyuki, <[email protected]>. This module is Copyright(C) 2004-2020, SADAHIRO Tomoyuki. Japan. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
Unicode Collation Algorithm - UTS #10 <http://www.unicode.org/reports/tr10/>
The Default Unicode Collation Element Table (DUCET) <http://www.unicode.org/Public/UCA/latest/allkeys.txt>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
<Unicode::Collate>
<Unicode::Normalize>
| programming_docs |
perl Unicode::Collate::CJK::Stroke Unicode::Collate::CJK::Stroke
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::Stroke - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::Stroke;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::Stroke::weightStroke
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::Stroke` provides `weightStroke()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's stroke ordering.
CAVEAT
------
The stroke ordering includes some characters that are not CJK Unified Ideographs and can't utilize `weightStroke()` for collation. For them, use `entry` instead.
SEE ALSO
---------
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
<Unicode::Collate>
<Unicode::Collate::Locale>
perl ExtUtils::Typemaps::Type ExtUtils::Typemaps::Type
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [proto](#proto)
+ [xstype](#xstype)
+ [ctype](#ctype)
+ [tidy\_ctype](#tidy_ctype)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
ExtUtils::Typemaps::Type - Entry in the TYPEMAP section of a typemap
SYNOPSIS
--------
```
use ExtUtils::Typemaps;
...
my $type = $typemap->get_type_map('char*');
my $input = $typemap->get_input_map($type->xstype);
```
DESCRIPTION
-----------
Refer to <ExtUtils::Typemaps> for details. Object associates `ctype` with `xstype`, which is the index into the in- and output mapping tables.
METHODS
-------
### new
Requires `xstype` and `ctype` parameters.
Optionally takes `prototype` parameter.
### proto
Returns or sets the prototype.
### xstype
Returns the name of the XS type that this C type is associated to.
### ctype
Returns the name of the C type as it was set on construction.
### tidy\_ctype
Returns the canonicalized name of the C type.
SEE ALSO
---------
<ExtUtils::Typemaps>
AUTHOR
------
Steffen Mueller `<[email protected]`>
COPYRIGHT & LICENSE
--------------------
Copyright 2009, 2010, 2011, 2012 Steffen Mueller
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Pod::Simple::RTF Pod::Simple::RTF
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FORMAT CONTROL ATTRIBUTES](#FORMAT-CONTROL-ATTRIBUTES)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::RTF -- format Pod as RTF
SYNOPSIS
--------
```
perl -MPod::Simple::RTF -e \
"exit Pod::Simple::RTF->filter(shift)->any_errata_seen" \
thingy.pod > thingy.rtf
```
DESCRIPTION
-----------
This class is a formatter that takes Pod and renders it as RTF, good for viewing/printing in MSWord, WordPad/write.exe, TextEdit, etc.
This is a subclass of <Pod::Simple> and inherits all its methods.
FORMAT CONTROL ATTRIBUTES
--------------------------
You can set these attributes on the parser object before you call `parse_file` (or a similar method) on it:
$parser->head1\_halfpoint\_size( *halfpoint\_integer* );
$parser->head2\_halfpoint\_size( *halfpoint\_integer* );
$parser->head3\_halfpoint\_size( *halfpoint\_integer* );
$parser->head4\_halfpoint\_size( *halfpoint\_integer* ); These methods set the size (in half-points, like 52 for 26-point) that these heading levels will appear as.
$parser->codeblock\_halfpoint\_size( *halfpoint\_integer* ); This method sets the size (in half-points, like 21 for 10.5-point) that codeblocks ("verbatim sections") will appear as.
$parser->header\_halfpoint\_size( *halfpoint\_integer* ); This method sets the size (in half-points, like 15 for 7.5-point) that the header on each page will appear in. The header is usually just "*modulename* p. *pagenumber*".
$parser->normal\_halfpoint\_size( *halfpoint\_integer* ); This method sets the size (in half-points, like 26 for 13-point) that normal paragraphic text will appear in.
$parser->no\_proofing\_exemptions( *true\_or\_false* ); Set this value to true if you don't want the formatter to try putting a hidden code on all Perl symbols (as best as it can notice them) that labels them as being not in English, and so not worth spellchecking.
$parser->doc\_lang( *microsoft\_decimal\_language\_code* ) This sets the language code to tag this document as being in. By default, it is currently the value of the environment variable `RTFDEFLANG`, or if that's not set, then the value 1033 (for US English).
Setting this appropriately is useful if you want to use the RTF to spellcheck, and/or if you want it to hyphenate right.
Here are some notable values:
```
1033 US English
2057 UK English
3081 Australia English
4105 Canada English
1034 Spain Spanish
2058 Mexico Spanish
1031 Germany German
1036 France French
3084 Canada French
1035 Finnish
1044 Norwegian (Bokmal)
2068 Norwegian (Nynorsk)
```
If you are particularly interested in customizing this module's output even more, see the source and/or write to me.
SEE ALSO
---------
<Pod::Simple>, <RTF::Writer>, <RTF::Cookbook>, <RTF::Document>, <RTF::Generator>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl ExtUtils::MM_VMS ExtUtils::MM\_VMS
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Methods always loaded](#Methods-always-loaded)
+ [Methods](#Methods1)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::MM\_VMS - methods to override UN\*X behaviour in ExtUtils::MakeMaker
SYNOPSIS
--------
```
Do not use this directly.
Instead, use ExtUtils::MM and it will figure out which MM_*
class to use for you.
```
DESCRIPTION
-----------
See <ExtUtils::MM_Unix> for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics.
###
Methods always loaded
wraplist Converts a list into a string wrapped at approximately 80 columns.
### Methods
Those methods which override default MM\_Unix methods are marked "(override)", while methods unique to MM\_VMS are marked "(specific)". For overridden methods, documentation is limited to an explanation of why this method overrides the MM\_Unix method; see the <ExtUtils::MM_Unix> documentation for more details.
guess\_name (override) Try to determine name of extension being built. We begin with the name of the current directory. Since VMS filenames are case-insensitive, however, we look for a *.pm* file whose name matches that of the current directory (presumably the 'main' *.pm* file for this extension), and try to find a `package` statement from which to obtain the Mixed::Case package name.
find\_perl (override) Use VMS file specification syntax and CLI commands to find and invoke Perl images.
\_fixin\_replace\_shebang (override) Helper routine for [MM->fixin()](ExtUtils::MM_Unix#fixin), overridden because there's no such thing as an actual shebang line that will be interpreted by the shell, so we just prepend $Config{startperl} and preserve the shebang line argument for any switches it may contain.
maybe\_command (override) Follows VMS naming conventions for executable files. If the name passed in doesn't exactly match an executable file, appends *.Exe* (or equivalent) to check for executable image, and *.Com* to check for DCL procedure. If this fails, checks directories in DCL$PATH and finally *Sys$System:* for an executable file having the name specified, with or without the *.Exe*-equivalent suffix.
pasthru (override) The list of macro definitions to be passed through must be specified using the /MACRO qualifier and must not add another /DEFINE qualifier. We prepend our own comma here to the contents of $(PASTHRU\_DEFINE) because it is often empty and a comma always present in CCFLAGS would generate a missing qualifier value error.
pm\_to\_blib (override) VMS wants a dot in every file so we can't have one called 'pm\_to\_blib', it becomes 'pm\_to\_blib.' and MMS/K isn't smart enough to know that when you have a target called 'pm\_to\_blib' it should look for 'pm\_to\_blib.'.
So in VMS its pm\_to\_blib.ts.
perl\_script (override) If name passed in doesn't specify a readable file, appends *.com* or *.pl* and tries again, since it's customary to have file types on all files under VMS.
replace\_manpage\_separator Use as separator a character which is legal in a VMS-syntax file name.
init\_DEST (override) Because of the difficulty concatenating VMS filepaths we must pre-expand the DEST\* variables.
init\_DIRFILESEP No separator between a directory path and a filename on VMS.
init\_main (override)
init\_tools (override) Provide VMS-specific forms of various utility commands.
Sets DEV\_NULL to nothing because I don't know how to do it on VMS.
Changes EQUALIZE\_TIMESTAMP to set revision date of target file to one second later than source file, since MMK interprets precisely equal revision dates for a source and target file as a sign that the target needs to be updated.
init\_platform (override) Add PERL\_VMS, MM\_VMS\_REVISION and MM\_VMS\_VERSION.
MM\_VMS\_REVISION is for backwards compatibility before MM\_VMS had a $VERSION.
platform\_constants
init\_VERSION (override) Override the \*DEFINE\_VERSION macros with VMS semantics. Translate the MAKEMAKER filepath to VMS style.
constants (override) Fixes up numerous file and directory macros to insure VMS syntax regardless of input syntax. Also makes lists of files comma-separated.
special\_targets Clear the default .SUFFIXES and put in our own list.
cflags (override) Bypass shell script and produce qualifiers for CC directly (but warn user if a shell script for this extension exists). Fold multiple /Defines into one, since some C compilers pay attention to only one instance of this qualifier on the command line.
const\_cccmd (override) Adds directives to point C preprocessor to the right place when handling #include <sys/foo.h> directives. Also constructs CC command line a bit differently than MM\_Unix method.
tools\_other (override) Throw in some dubious extra macros for Makefile args.
Also keep around the old $(SAY) macro in case somebody's using it.
init\_dist (override) VMSish defaults for some values.
```
macro description default
ZIPFLAGS flags to pass to ZIP -Vu
COMPRESS compression command to gzip
use for tarfiles
SUFFIX suffix to put on -gz
compressed files
SHAR shar command to use vms_share
DIST_DEFAULT default target to use to tardist
create a distribution
DISTVNAME Use VERSION_SYM instead of $(DISTNAME)-$(VERSION_SYM)
VERSION for the name
```
c\_o (override) Use VMS syntax on command line. In particular, $(DEFINE) and $(PERL\_INC) have been pulled into $(CCCMD). Also use MM[SK] macros.
xs\_c (override) Use MM[SK] macros.
xs\_o (override) Use MM[SK] macros, and VMS command line for C compiler.
\_xsbuild\_replace\_macro (override) There is no simple replacement possible since a qualifier and all its subqualifiers must be considered together, so we use our own utility routine for the replacement.
\_xsbuild\_value (override) Convert the extension spec to Unix format, as that's what will match what's in the XSBUILD data structure.
dlsyms (override) Create VMS linker options files specifying universal symbols for this extension's shareable image(s), and listing other shareable images or libraries to which it should be linked.
xs\_obj\_opt Override to fixup -o flags.
dynamic\_lib (override) Use VMS Link command.
xs\_make\_static\_lib (override) Use VMS commands to manipulate object library.
static\_lib\_pure\_cmd (override) Use VMS commands to manipulate object library.
xs\_static\_lib\_is\_xs extra\_clean\_files Clean up some OS specific files. Plus the temp file used to shorten a lot of commands. And the name mangler database.
zipfile\_target tarfile\_target shdist\_target Syntax for invoking shar, tar and zip differs from that for Unix.
install (override) Work around DCL's 255 character limit several times,and use VMS-style command line quoting in a few cases.
perldepend (override) Use VMS-style syntax for files; it's cheaper to just do it directly here than to have the [MM\_Unix](ExtUtils::MM_Unix) method call `catfile` repeatedly. Also, if we have to rebuild Config.pm, use MM[SK] to do it.
makeaperl (override) Undertake to build a new set of Perl images using VMS commands. Since VMS does dynamic loading, it's not necessary to statically link each extension into the Perl image, so this isn't the normal build path. Consequently, it hasn't really been tested, and may well be incomplete.
maketext\_filter (override) Ensure that colons marking targets are preceded by space, in order to distinguish the target delimiter from a colon appearing as part of a filespec.
prefixify (override) prefixifying on VMS is simple. Each should simply be:
```
perl_root:[some.dir]
```
which can just be converted to:
```
volume:[your.prefix.some.dir]
```
otherwise you get the default layout.
In effect, your search prefix is ignored and $Config{vms\_prefix} is used instead.
cd oneliner **echo** perl trips up on "<foo>" thinking it's an input redirect. So we use the native Write command instead. Besides, it's faster.
quote\_literal escape\_dollarsigns Quote, don't escape.
escape\_all\_dollarsigns Quote, don't escape.
escape\_newlines max\_exec\_len 256 characters.
init\_linker
catdir (override)
catfile (override) Eliminate the macros in the output to the MMS/MMK file.
(<File::Spec::VMS> used to do this for us, but it's being removed)
eliminate\_macros Expands MM[KS]/Make macros in a text string, using the contents of identically named elements of `%$self`, and returns the result as a file specification in Unix syntax.
NOTE: This is the canonical version of the method. The version in <File::Spec::VMS> is deprecated.
fixpath
```
my $path = $mm->fixpath($path);
my $path = $mm->fixpath($path, $is_dir);
```
Catchall routine to clean up problem MM[SK]/Make macros. Expands macros in any directory specification, in order to avoid juxtaposing two VMS-syntax directories when MM[SK] is run. Also expands expressions which are all macro, so that we can tell how long the expansion is, and avoid overrunning DCL's command buffer when MM[KS] is running.
fixpath() checks to see whether the result matches the name of a directory in the current default directory and returns a directory or file specification accordingly. `$is_dir` can be set to true to force fixpath() to consider the path to be a directory or false to force it to be a file.
NOTE: This is the canonical version of the method. The version in <File::Spec::VMS> is deprecated.
os\_flavor VMS is VMS.
is\_make\_type (override) None of the make types being checked for is viable on VMS, plus our $self->{MAKE} is an unexpanded (and unexpandable) macro whose value is known only to the make utility itself.
make\_type (override) Returns a suitable string describing the type of makefile being written.
AUTHOR
------
Original author Charles Bailey *[email protected]*
Maintained by Michael G Schwern *[email protected]*
See <ExtUtils::MakeMaker> for patching and contact information.
perl IO::Uncompress::Gunzip IO::Uncompress::Gunzip
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [gunzip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#gunzip-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [read](#read)
+ [read](#read1)
+ [getline](#getline)
+ [getc](#getc)
+ [ungetc](#ungetc)
+ [inflateSync](#inflateSync)
+ [getHeaderInfo](#getHeaderInfo)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [nextStream](#nextStream)
+ [trailingData](#trailingData)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
+ [Working with Net::FTP](#Working-with-Net::FTP)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::Gunzip - Read RFC 1952 files/buffers
SYNOPSIS
--------
```
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
my $status = gunzip $input => $output [,OPTS]
or die "gunzip failed: $GunzipError\n";
my $z = IO::Uncompress::Gunzip->new( $input [OPTS] )
or die "gunzip failed: $GunzipError\n";
$status = $z->read($buffer)
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$line = $z->getline()
$char = $z->getc()
$char = $z->ungetc()
$char = $z->opened()
$status = $z->inflateSync()
$data = $z->trailingData()
$status = $z->nextStream()
$data = $z->getHeaderInfo()
$z->tell()
$z->seek($position, $whence)
$z->binmode()
$z->fileno()
$z->eof()
$z->close()
$GunzipError ;
# IO::File mode
<$z>
read($z, $buffer);
read($z, $buffer, $length);
read($z, $buffer, $length, $offset);
tell($z)
seek($z, $position, $whence)
binmode($z)
fileno($z)
eof($z)
close($z)
```
DESCRIPTION
-----------
This module provides a Perl interface that allows the reading of files/buffers that conform to RFC 1952.
For writing RFC 1952 files/buffers, see the companion module IO::Compress::Gzip.
Functional Interface
---------------------
A top-level function, `gunzip`, is provided to carry out "one-shot" uncompression between buffers and/or files. For finer control over the uncompression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
gunzip $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "gunzip failed: $GunzipError\n";
```
The functional interface needs Perl5.005 or better.
###
gunzip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`gunzip` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the compressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is uncompressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `gunzip` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the uncompressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the uncompressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the uncompressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the uncompressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the uncompressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `gunzip` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple compressed files/buffers and `$output_filename_or_reference` is a single file/buffer, after uncompression `$output_filename_or_reference` will contain a concatenation of all the uncompressed data from each of the input files/buffers.
###
Optional Parameters
The optional parameters for the one-shot function `gunzip` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `gunzip` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `gunzip` has completed.
This parameter defaults to 0.
`BinModeOut => 0|1`
This option is now a no-op. All files will be written in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all uncompressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any uncompressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any uncompressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any uncompressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all uncompressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any uncompressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all uncompressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any uncompressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any uncompressed data is output.
Defaults to 0.
`MultiStream => 0|1`
If the input file/buffer contains multiple compressed data streams, this option will uncompress the whole lot as a single data stream.
Defaults to 0.
`TrailingData => $scalar`
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option.
### Examples
To read the contents of the file `file1.txt.gz` and write the uncompressed data to the file `file1.txt`.
```
use strict ;
use warnings ;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
my $input = "file1.txt.gz";
my $output = "file1.txt";
gunzip $input => $output
or die "gunzip failed: $GunzipError\n";
```
To read from an existing Perl filehandle, `$input`, and write the uncompressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.gz" )
or die "Cannot open 'file1.txt.gz': $!\n" ;
my $buffer ;
gunzip $input => \$buffer
or die "gunzip failed: $GunzipError\n";
```
To uncompress all files in the directory "/my/home" that match "\*.txt.gz" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
gunzip '</my/home/*.txt.gz>' => '</my/home/#1.txt>'
or die "gunzip failed: $GunzipError\n";
```
and if you want to compress each file one at a time, this will do the trick
```
use strict ;
use warnings ;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
for my $input ( glob "/my/home/*.txt.gz" )
{
my $output = $input;
$output =~ s/.gz// ;
gunzip $input => $output
or die "Error compressing '$input': $GunzipError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::Gunzip is shown below
```
my $z = IO::Uncompress::Gunzip->new( $input [OPTS] )
or die "IO::Uncompress::Gunzip failed: $GunzipError\n";
```
Returns an `IO::Uncompress::Gunzip` object on success and undef on failure. The variable `$GunzipError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::Gunzip can be used exactly like an <IO::File> filehandle. This means that all normal input file operations can be carried out with `$z`. For example, to read a line from a compressed file/buffer you can use either of these forms
```
$line = $z->getline();
$line = <$z>;
```
The mandatory parameter `$input` is used to determine the source of the compressed data. This parameter can take one of three forms.
A filename If the `$input` parameter is a scalar, it is assumed to be a filename. This file will be opened for reading and the compressed data will be read from it.
A filehandle If the `$input` parameter is a filehandle, the compressed data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input` is a scalar reference, the compressed data will be read from `$$input`.
###
Constructor Options
The option names defined below are case insensitive and can be optionally prefixed by a '-'. So all of the following are valid
```
-AutoClose
-autoclose
AUTOCLOSE
autoclose
```
OPTS is a combination of the following options:
`AutoClose => 0|1`
This option is only valid when the `$input` parameter is a filehandle. If specified, and the value is true, it will result in the file being closed once either the `close` method is called or the IO::Uncompress::Gunzip object is destroyed.
This parameter defaults to 0.
`MultiStream => 0|1`
Allows multiple concatenated compressed streams to be treated as a single compressed stream. Decompression will stop once either the end of the file/buffer is reached, an error is encountered (premature eof, corrupt compressed data) or the end of a stream is not immediately followed by the start of another stream.
This parameter defaults to 0.
`Prime => $string`
This option will uncompress the contents of `$string` before processing the input file/buffer.
This option can be useful when the compressed data is embedded in another file/data structure and it is not possible to work out where the compressed data begins without having to read the first few bytes. If this is the case, the uncompression can be *primed* with these bytes using this option.
`Transparent => 0|1`
If this option is set and the input file/buffer is not compressed data, the module will allow reading of it anyway.
In addition, if the input file/buffer does contain compressed data and there is non-compressed data immediately following it, setting this option will make this module treat the whole file/buffer as a single data stream.
This option defaults to 1.
`BlockSize => $num`
When reading the compressed input data, IO::Uncompress::Gunzip will read it in blocks of `$num` bytes.
This option defaults to 4096.
`InputLength => $size`
When present this option will limit the number of compressed bytes read from the input file/buffer to `$size`. This option can be used in the situation where there is useful data directly after the compressed data stream and you know beforehand the exact length of the compressed data stream.
This option is mostly used when reading from a filehandle, in which case the file pointer will be left pointing to the first byte directly after the compressed data stream.
This option defaults to off.
`Append => 0|1`
This option controls what the `read` method does with uncompressed data.
If set to 1, all uncompressed data will be appended to the output parameter of the `read` method.
If set to 0, the contents of the output parameter of the `read` method will be overwritten by the uncompressed data.
Defaults to 0.
`Strict => 0|1`
This option controls whether the extra checks defined below are used when carrying out the decompression. When Strict is on, the extra tests are carried out, when Strict is off they are not.
The default for this option is off.
1. If the FHCRC bit is set in the gzip FLG header byte, the CRC16 bytes in the header must match the crc16 value of the gzip header actually read.
2. If the gzip header contains a name field (FNAME) it consists solely of ISO 8859-1 characters.
3. If the gzip header contains a comment field (FCOMMENT) it consists solely of ISO 8859-1 characters plus line-feed.
4. If the gzip FEXTRA header field is present it must conform to the sub-field structure as defined in RFC 1952.
5. The CRC32 and ISIZE trailer fields must be present.
6. The value of the CRC32 field read must match the crc32 value of the uncompressed data actually contained in the gzip file.
7. The value of the ISIZE fields read must match the length of the uncompressed data actually read from the file.
`ParseExtra => 0|1` If the gzip FEXTRA header field is present and this option is set, it will force the module to check that it conforms to the sub-field structure as defined in RFC 1952. If the `Strict` is on it will automatically enable this option.
Defaults to 0.
### Examples
TODO
Methods
-------
### read
Usage is
```
$status = $z->read($buffer)
```
Reads a block of compressed data (the size of the compressed block is determined by the `Buffer` option in the constructor), uncompresses it and writes any uncompressed data into `$buffer`. If the `Append` parameter is set in the constructor, the uncompressed data will be appended to the `$buffer` parameter. Otherwise `$buffer` will be overwritten.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### read
Usage is
```
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$status = read($z, $buffer, $length)
$status = read($z, $buffer, $length, $offset)
```
Attempt to read `$length` bytes of uncompressed data into `$buffer`.
The main difference between this form of the `read` method and the previous one, is that this one will attempt to return *exactly* `$length` bytes. The only circumstances that this function will not is if end-of-file or an IO error is encountered.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### getline
Usage is
```
$line = $z->getline()
$line = <$z>
```
Reads a single line.
This method fully supports the use of the variable `$/` (or `$INPUT_RECORD_SEPARATOR` or `$RS` when `English` is in use) to determine what constitutes an end of line. Paragraph mode, record mode and file slurp mode are all supported.
### getc
Usage is
```
$char = $z->getc()
```
Read a single character.
### ungetc
Usage is
```
$char = $z->ungetc($string)
```
### inflateSync
Usage is
```
$status = $z->inflateSync()
```
TODO
### getHeaderInfo
Usage is
```
$hdr = $z->getHeaderInfo();
@hdrs = $z->getHeaderInfo();
```
This method returns either a hash reference (in scalar context) or a list or hash references (in array context) that contains information about each of the header fields in the compressed data stream(s).
Name The contents of the Name header field, if present. If no name is present, the value will be undef. Note this is different from a zero length name, which will return an empty string.
Comment The contents of the Comment header field, if present. If no comment is present, the value will be undef. Note this is different from a zero length comment, which will return an empty string.
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the end of the compressed input stream has been reached.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the input file/buffer. It is a fatal error to attempt to seek backward.
Note that the implementation of `seek` in this module does not provide true random access to a compressed file/buffer. It works by uncompressing data from the current offset in the file/buffer until it reaches the uncompressed offset specified in the parameters to `seek`. For very small files this may be acceptable behaviour. For large files it may cause an unacceptable delay.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
Returns the current uncompressed line number. If `EXPR` is present it has the effect of setting the line number. Note that setting the line number does not change the current position within the file/buffer being read.
The contents of `$/` are used to determine what constitutes a line terminator.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Uncompress::Gunzip object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Uncompress::Gunzip object was created, and the object is associated with a file, the underlying file will also be closed.
### nextStream
Usage is
```
my $status = $z->nextStream();
```
Skips to the next compressed data stream in the input file/buffer. If a new compressed data stream is found, the eof marker will be cleared and `$.` will be reset to 0.
Returns 1 if a new stream was found, 0 if none was found, and -1 if an error was encountered.
### trailingData
Usage is
```
my $data = $z->trailingData();
```
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete. It only makes sense to call this method once the end of the compressed data stream has been encountered.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option in the constructor.
Importing
---------
No symbolic constants are required by IO::Uncompress::Gunzip at present.
:all Imports `gunzip` and `$GunzipError`. Same as doing this
```
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
```
EXAMPLES
--------
###
Working with Net::FTP
See [IO::Compress::FAQ](IO::Compress::FAQ#Compressed-files-and-Net%3A%3AFTP)
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
For RFC 1950, 1951 and 1952 see <https://datatracker.ietf.org/doc/html/rfc1950>, <https://datatracker.ietf.org/doc/html/rfc1951> and <https://datatracker.ietf.org/doc/html/rfc1952>
The *zlib* compression library was written by Jean-loup Gailly `[email protected]` and Mark Adler `[email protected]`.
The primary site for the *zlib* compression library is <http://www.zlib.org>.
The primary site for gzip is <http://www.gzip.org>.
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl ExtUtils::MM_OS390 ExtUtils::MM\_OS390
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overriden methods](#Overriden-methods)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MM\_OS390 - OS390 specific subclass of ExtUtils::MM\_Unix
SYNOPSIS
--------
```
Don't use this module directly.
Use ExtUtils::MM and let it choose.
```
DESCRIPTION
-----------
This is a subclass of <ExtUtils::MM_Unix> which contains functionality for OS390.
Unless otherwise stated it works just like ExtUtils::MM\_Unix.
###
Overriden methods
xs\_make\_dynamic\_lib Defines the recipes for the `dynamic_lib` section.
AUTHOR
------
Michael G Schwern <[email protected]> with code from ExtUtils::MM\_Unix
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl PerlIO PerlIO
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Layers](#Layers)
+ [Custom Layers](#Custom-Layers)
+ [Alternatives to raw](#Alternatives-to-raw)
+ [Defaults and how to override them](#Defaults-and-how-to-override-them)
+ [Querying the layers of filehandles](#Querying-the-layers-of-filehandles)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
PerlIO - On demand loader for PerlIO layers and root of PerlIO::\* name space
SYNOPSIS
--------
```
# support platform-native and CRLF text files
open(my $fh, "<:crlf", "my.txt") or die "open failed: $!";
# append UTF-8 encoded text
open(my $fh, ">>:encoding(UTF-8)", "some.log")
or die "open failed: $!";
# portably open a binary file for reading
open(my $fh, "<", "his.jpg") or die "open failed: $!";
binmode($fh) or die "binmode failed: $!";
Shell:
PERLIO=:perlio perl ....
```
DESCRIPTION
-----------
When an undefined layer 'foo' is encountered in an `open` or `binmode` layer specification then C code performs the equivalent of:
```
use PerlIO 'foo';
```
The Perl code in PerlIO.pm then attempts to locate a layer by doing
```
require PerlIO::foo;
```
Otherwise the `PerlIO` package is a place holder for additional PerlIO related functions.
### Layers
Generally speaking, PerlIO layers (previously sometimes referred to as "disciplines") are an ordered stack applied to a filehandle (specified as a space- or colon-separated list, conventionally written with a leading colon). Each layer performs some operation on any input or output, except when bypassed such as with `sysread` or `syswrite`. Read operations go through the stack in the order they are set (left to right), and write operations in the reverse order.
There are also layers which actually just set flags on lower layers, or layers that modify the current stack but don't persist on the stack themselves; these are referred to as pseudo-layers.
When opening a handle, it will be opened with any layers specified explicitly in the open() call (or the platform defaults, if specified as a colon with no following layers).
If layers are not explicitly specified, the handle will be opened with the layers specified by the [${^OPEN}](perlvar#%24%7B%5EOPEN%7D) variable (usually set by using the <open> pragma for a lexical scope, or the `-C` command-line switch or `PERL_UNICODE` environment variable for the main program scope).
If layers are not specified in the open() call or `${^OPEN}` variable, the handle will be opened with the default layer stack configured for that architecture; see ["Defaults and how to override them"](#Defaults-and-how-to-override-them).
Some layers will automatically insert required lower level layers if not present; for example `:perlio` will insert `:unix` below itself for low level IO, and `:encoding` will insert the platform defaults for buffered IO.
The `binmode` function can be called on an opened handle to push additional layers onto the stack, which may also modify the existing layers. `binmode` called with no layers will remove or unset any existing layers which transform the byte stream, making the handle suitable for binary data.
The following layers are currently defined:
:unix Lowest level layer which provides basic PerlIO operations in terms of UNIX/POSIX numeric file descriptor calls (open(), read(), write(), lseek(), close()). It is used even on non-Unix architectures, and most other layers operate on top of it.
:stdio Layer which calls `fread`, `fwrite` and `fseek`/`ftell` etc. Note that as this is "real" stdio it will ignore any layers beneath it and go straight to the operating system via the C library as usual. This layer implements both low level IO and buffering, but is rarely used on modern architectures.
:perlio A from scratch implementation of buffering for PerlIO. Provides fast access to the buffer for `sv_gets` which implements Perl's readline/<> and in general attempts to minimize data copying.
`:perlio` will insert a `:unix` layer below itself to do low level IO.
:crlf A layer that implements DOS/Windows like CRLF line endings. On read converts pairs of CR,LF to a single "\n" newline character. On write converts each "\n" to a CR,LF pair. Note that this layer will silently refuse to be pushed on top of itself.
It currently does *not* mimic MS-DOS as far as treating of Control-Z as being an end-of-file marker.
On DOS/Windows like architectures where this layer is part of the defaults, it also acts like the `:perlio` layer, and removing the CRLF translation (such as with `:raw`) will only unset the CRLF translation flag. Since Perl 5.14, you can also apply another `:crlf` layer later, such as when the CRLF translation must occur after an encoding layer. On other architectures, it is a mundane CRLF translation layer and can be added and removed normally.
```
# translate CRLF after encoding on Perl 5.14 or newer
binmode $fh, ":raw:encoding(UTF-16LE):crlf"
or die "binmode failed: $!";
```
:utf8 Pseudo-layer that declares that the stream accepts Perl's *internal* upgraded encoding of characters, which is approximately UTF-8 on ASCII machines, but UTF-EBCDIC on EBCDIC machines. This allows any character Perl can represent to be read from or written to the stream.
This layer (which actually sets a flag on the preceding layer, and is implicitly set by any `:encoding` layer) does not translate or validate byte sequences. It instead indicates that the byte stream will have been arranged by other layers to be provided in Perl's internal upgraded encoding, which Perl code (and correctly written XS code) will interpret as decoded Unicode characters.
**CAUTION**: Do not use this layer to translate from UTF-8 bytes, as invalid UTF-8 or binary data will result in malformed Perl strings. It is unlikely to produce invalid UTF-8 when used for output, though it will instead produce UTF-EBCDIC on EBCDIC systems. The `:encoding(UTF-8)` layer (hyphen is significant) is preferred as it will ensure translation between valid UTF-8 bytes and valid Unicode characters.
:bytes This is the inverse of the `:utf8` pseudo-layer. It turns off the flag on the layer below so that data read from it is considered to be Perl's internal downgraded encoding, thus interpreted as the native single-byte encoding of Latin-1 or EBCDIC. Likewise on output Perl will warn if a "wide" character (a codepoint not in the range 0..255) is written to a such a stream.
This is very dangerous to push on a handle using an `:encoding` layer, as such a layer assumes to be working with Perl's internal upgraded encoding, so you will likely get a mangled result. Instead use `:raw` or `:pop` to remove encoding layers.
:raw The `:raw` pseudo-layer is *defined* as being identical to calling `binmode($fh)` - the stream is made suitable for passing binary data, i.e. each byte is passed as-is. The stream will still be buffered (but this was not always true before Perl 5.14).
In Perl 5.6 and some books the `:raw` layer is documented as the inverse of the `:crlf` layer. That is no longer the case - other layers which would alter the binary nature of the stream are also disabled. If you want UNIX line endings on a platform that normally does CRLF translation, but still want UTF-8 or encoding defaults, the appropriate thing to do is to add `:perlio` to the PERLIO environment variable, or open the handle explicitly with that layer, to replace the platform default of `:crlf`.
The implementation of `:raw` is as a pseudo-layer which when "pushed" pops itself and then any layers which would modify the binary data stream. (Undoing `:utf8` and `:crlf` may be implemented by clearing flags rather than popping layers but that is an implementation detail.)
As a consequence of the fact that `:raw` normally pops layers, it usually only makes sense to have it as the only or first element in a layer specification. When used as the first element it provides a known base on which to build e.g.
```
open(my $fh,">:raw:encoding(UTF-8)",...)
or die "open failed: $!";
```
will construct a "binary" stream regardless of the platform defaults, but then enable UTF-8 translation.
:pop A pseudo-layer that removes the top-most layer. Gives Perl code a way to manipulate the layer stack. Note that `:pop` only works on real layers and will not undo the effects of pseudo-layers or flags like `:utf8`. An example of a possible use might be:
```
open(my $fh,...) or die "open failed: $!";
...
binmode($fh,":encoding(...)") or die "binmode failed: $!";
# next chunk is encoded
...
binmode($fh,":pop") or die "binmode failed: $!";
# back to un-encoded
```
A more elegant (and safer) interface is needed.
###
Custom Layers
It is possible to write custom layers in addition to the above builtin ones, both in C/XS and Perl, as a module named `PerlIO::<layer name>`. Some custom layers come with the Perl distribution.
:encoding Use `:encoding(ENCODING)` to transparently do character set and encoding transformations, for example from Shift-JIS to Unicode. Note that an `:encoding` also enables `:utf8`. See <PerlIO::encoding> for more information.
:mmap A layer which implements "reading" of files by using `mmap()` to make a (whole) file appear in the process's address space, and then using that as PerlIO's "buffer". This *may* be faster in certain circumstances for large files, and may result in less physical memory use when multiple processes are reading the same file.
Files which are not `mmap()`-able revert to behaving like the `:perlio` layer. Writes also behave like the `:perlio` layer, as `mmap()` for write needs extra house-keeping (to extend the file) which negates any advantage.
The `:mmap` layer will not exist if the platform does not support `mmap()`. See <PerlIO::mmap> for more information.
:via `:via(MODULE)` allows a transformation to be applied by an arbitrary Perl module, for example compression / decompression, encryption / decryption. See <PerlIO::via> for more information.
:scalar A layer implementing "in memory" files using scalar variables, automatically used in place of the platform defaults for IO when opening such a handle. As such, the scalar is expected to act like a file, only containing or storing bytes. See <PerlIO::scalar> for more information.
###
Alternatives to raw
To get a binary stream an alternate method is to use:
```
open(my $fh,"<","whatever") or die "open failed: $!";
binmode($fh) or die "binmode failed: $!";
```
This has the advantage of being backward compatible with older versions of Perl that did not use PerlIO or where `:raw` was buggy (as it was before Perl 5.14).
To get an unbuffered stream specify an unbuffered layer (e.g. `:unix`) in the open call:
```
open(my $fh,"<:unix",$path) or die "open failed: $!";
```
###
Defaults and how to override them
If the platform is MS-DOS like and normally does CRLF to "\n" translation for text files then the default layers are:
```
:unix:crlf
```
Otherwise if `Configure` found out how to do "fast" IO using the system's stdio (not common on modern architectures), then the default layers are:
```
:stdio
```
Otherwise the default layers are
```
:unix:perlio
```
Note that the "default stack" depends on the operating system and on the Perl version, and both the compile-time and runtime configurations of Perl. The default can be overridden by setting the environment variable PERLIO to a space or colon separated list of layers, however this cannot be used to set layers that require loading modules like `:encoding`.
This can be used to see the effect of/bugs in the various layers e.g.
```
cd .../perl/t
PERLIO=:stdio ./perl harness
PERLIO=:perlio ./perl harness
```
For the various values of PERLIO see ["PERLIO" in perlrun](perlrun#PERLIO).
The following table summarizes the default layers on UNIX-like and DOS-like platforms and depending on the setting of `$ENV{PERLIO}`:
```
PERLIO UNIX-like DOS-like
------ --------- --------
unset / "" :unix:perlio / :stdio [1] :unix:crlf
:stdio :stdio :stdio
:perlio :unix:perlio :unix:perlio
# [1] ":stdio" if Configure found out how to do "fast stdio" (depends
# on the stdio implementation) and in Perl 5.8, else ":unix:perlio"
```
###
Querying the layers of filehandles
The following returns the **names** of the PerlIO layers on a filehandle.
```
my @layers = PerlIO::get_layers($fh); # Or FH, *FH, "FH".
```
The layers are returned in the order an open() or binmode() call would use them, and without colons.
By default the layers from the input side of the filehandle are returned; to get the output side, use the optional `output` argument:
```
my @layers = PerlIO::get_layers($fh, output => 1);
```
(Usually the layers are identical on either side of a filehandle but for example with sockets there may be differences.)
There is no set\_layers(), nor does get\_layers() return a tied array mirroring the stack, or anything fancy like that. This is not accidental or unintentional. The PerlIO layer stack is a bit more complicated than just a stack (see for example the behaviour of `:raw`). You are supposed to use open() and binmode() to manipulate the stack.
**Implementation details follow, please close your eyes.**
The arguments to layers are by default returned in parentheses after the name of the layer, and certain layers (like `:utf8`) are not real layers but instead flags on real layers; to get all of these returned separately, use the optional `details` argument:
```
my @layer_and_args_and_flags = PerlIO::get_layers($fh, details => 1);
```
The result will be up to be three times the number of layers: the first element will be a name, the second element the arguments (unspecified arguments will be `undef`), the third element the flags, the fourth element a name again, and so forth.
**You may open your eyes now.**
AUTHOR
------
Nick Ing-Simmons <[email protected]>
SEE ALSO
---------
["binmode" in perlfunc](perlfunc#binmode), ["open" in perlfunc](perlfunc#open), <perlunicode>, <perliol>, [Encode](encode)
perl PerlIO::scalar PerlIO::scalar
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [IMPLEMENTATION NOTE](#IMPLEMENTATION-NOTE)
NAME
----
PerlIO::scalar - in-memory IO, scalar IO
SYNOPSIS
--------
```
my $scalar = '';
...
open my $fh, "<", \$scalar or die;
open my $fh, ">", \$scalar or die;
open my $fh, ">>", \$scalar or die;
```
or
```
my $scalar = '';
...
open my $fh, "<:scalar", \$scalar or die;
open my $fh, ">:scalar", \$scalar or die;
open my $fh, ">>:scalar", \$scalar or die;
```
DESCRIPTION
-----------
A filehandle is opened but the file operations are performed "in-memory" on a scalar variable. All the normal file operations can be performed on the handle. The scalar is considered a stream of bytes. Currently fileno($fh) returns -1.
Attempting to open a read-only scalar for writing will fail, and if warnings are enabled, produce a warning.
IMPLEMENTATION NOTE
--------------------
`PerlIO::scalar` only exists to use XSLoader to load C code that provides support for treating a scalar as an "in memory" file. One does not need to explicitly `use PerlIO::scalar`.
perl perlamiga perlamiga
=========
CONTENTS
--------
* [NAME](#NAME)
* [NOTE](#NOTE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Prerequisites for running Perl 5.22.1 under AmigaOS 4.1](#Prerequisites-for-running-Perl-5.22.1-under-AmigaOS-4.1)
+ [Starting Perl programs under AmigaOS 4.1](#Starting-Perl-programs-under-AmigaOS-4.1)
+ [Limitations of Perl under AmigaOS 4.1](#Limitations-of-Perl-under-AmigaOS-4.1)
* [INSTALLATION](#INSTALLATION)
* [Amiga Specific Modules](#Amiga-Specific-Modules)
+ [Amiga::ARexx](#Amiga::ARexx)
+ [Amiga::Exec](#Amiga::Exec)
* [BUILDING](#BUILDING)
* [CHANGES](#CHANGES)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlamiga - Perl under AmigaOS 4.1
NOTE
----
This is a port of Perl 5.22.1, it is a fresh port and not in any way compatible with my previous ports of Perl 5.8 and 5.16.3. This means you will need to reinstall / rebuild any third party modules you have installed.
newlib.library version 53.28 or greater is required.
SYNOPSIS
--------
Once perl is installed you can read this document in the following way
```
sh -c "perldoc perlamiga"
```
or you may read *as is*: either as *README.amiga*, or *pod/perlamiga.pod*.
DESCRIPTION
-----------
###
Prerequisites for running Perl 5.22.1 under AmigaOS 4.1
**AmigaOS 4.1 update 6 with all updates applied as of 9th October 2013**
The most important of which is:
**newlib.library version 53.28 or greater**
**AmigaOS SDK**
Perl installs into the SDK directory structure and expects many of the build tools present in the SDK to be available. So for the best results install the SDK first.
**abc-shell**
If you do not have the SDK installed you must at least have abc-shell installed or some other suitable sh port. This is required to run external commands and should be available as 'sh' in your path.
###
Starting Perl programs under AmigaOS 4.1
Perl may be run from the AmigaOS shell but for best results should be run under abc-shell. (abc-shell handles file globbing, pattern expansion, and sets up environment variables in the UN\*Xy way that Perl expects.)
For example:
```
New Shell process 10
10.AmigaOS4:> sh
/AmigaOS4>perl path:to/myprog arg1 arrg2 arg3
```
Abc-shell can also launch programs via the #! syntax at the start of the program file, it's best use the form #!SDK:Local/C/perl so that the AmigaOS shell may also find perl in the same way. AmigaOS requires the script bit to be set for this to work
```
10.AmigaOS4:> sh
/AmigaOS4>myprog arg1 arrg2 arg3
```
###
Limitations of Perl under AmigaOS 4.1
**Nested Piped programs can crash when run from older abc-shells**
abc-shell version 53.2 has a bug that can cause crashes in the subprocesses used to run piped programs, if a later version is available you should install it instead.
**Incorrect or unexpected command line unescaping**
newlib.library 53.30 and earlier incorrectly unescape slashed escape sequences e.g. \" \n \t etc requiring unusual extra escaping.
**Starting subprocesses via open has limitations**
```
open FH, "command |"
```
Subprocesses started with open use a minimal popen() routine and therefore they do not return pids usable with waitpid etc.
If you find any other limitations or bugs then let me know. Please report bugs in this version of perl to [email protected] in the first instance.
INSTALLATION
------------
This guide assumes you have obtained a prebuilt archive from os4depot.net.
Unpack the main archive to a temporary location (RAM: is fine).
Execute the provided install script from shell or via its icon.
You **must not** attempt to install by hand.
Once installed you may delete the temporary archive.
This approach will preserve links in the installation without creating duplicate binaries.
If you have the earlier ports perl 5.16 or 5.8 installed you may like to rename your perl executable to perl516 or perl58 or something similar before the installation of 5.22.1, this will allow you to use both versions at the same time.
Amiga Specific Modules
-----------------------
###
Amiga::ARexx
The Amiga::ARexx module allows you to easily create a perl based ARexx host or to send ARexx commands to other programs.
Try `perldoc Amiga::ARexx` for more info.
###
Amiga::Exec
The Amiga::Exec module introduces support for Wait().
Try `perldoc Amiga::Exec` for more info.
BUILDING
--------
To build perl under AmigaOS from the patched sources you will need to have a recent version of the SDK. Version 53.29 is recommended, earlier versions will probably work too.
With the help of Jarkko Hietaniemi the Configure system has been tweaked to run under abc-shell so the recommend build process is as follows.
```
stack 2000000
sh Configure -de
gmake
```
This will build the default setup that installs under SDK:local/newlib/lib/
CHANGES
-------
**August 2015**
Port to Perl 5.22
Add handling of NIL: to afstat()
Fix inheritance of environment variables by subprocesses.
Fix exec, and exit in "forked" subprocesses.
Fix issue with newlib's unlink, which could cause infinite loops.
Add flock() emulation using IDOS->LockRecord thanks to Tony Cook for the suggestion.
Fix issue where kill was using the wrong kind of process ID
**27th November 2013**
Create new installation system based on installperl links and Amiga protection bits now set correctly.
Pod now defaults to text.
File::Spec should now recognise an Amiga style absolute path as well as an Unix style one. Relative paths must always be Unix style.
**20th November 2013**
Configured to use SDK:Local/C/perl to start standard scripts
Added Amiga::Exec module with support for Wait() and AmigaOS signal numbers.
**10th October 13**
First release of port to 5.16.3.
SEE ALSO
---------
You like this port? See <http://www.broad.ology.org.uk/amiga/> for how you can help.
| programming_docs |
perl perlsynology perlsynology
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Setting up the build environment](#Setting-up-the-build-environment)
- [DSM 5](#DSM-5)
- [DSM 6](#DSM-6)
+ [Compiling Perl 5](#Compiling-Perl-5)
+ [Known problems](#Known-problems)
- [Configure](#Configure)
- [Build](#Build)
- [Failing tests](#Failing-tests)
+ [Smoke testing Perl 5](#Smoke-testing-Perl-5)
- [Local patches](#Local-patches)
+ [Adding libraries](#Adding-libraries)
* [REVISION](#REVISION)
* [AUTHOR](#AUTHOR)
NAME
----
perlsynology - Perl 5 on Synology DSM systems
DESCRIPTION
-----------
Synology manufactures a vast number of Network Attached Storage (NAS) devices that are very popular in large organisations as well as small businesses and homes.
The NAS systems are equipped with Synology Disk Storage Manager (DSM), which is a trimmed-down Linux system enhanced with several tools for managing the NAS. There are several flavours of hardware: Marvell Armada (ARMv5tel, ARMv7l), Intel Atom (i686, x86\_64), Freescale QorIQ (PPC), and more. For a full list see the [Synology FAQ](https://kb.synology.com/en-global/DSM/tutorial/What_kind_of_CPU_does_my_NAS_have).
Since it is based on Linux, the NAS can run many popular Linux software packages, including Perl. In fact, Synology provides a ready-to-install package for Perl, depending on the version of DSM the installed perl ranges from 5.8.6 on DSM-4.3 to 5.24.0 on DSM-6.1.
There is an active user community that provides many software packages for the Synology DSM systems; at the time of writing this document they provide Perl version 5.24.1.
This document describes various features of Synology DSM operating system that will affect how Perl 5 (hereafter just Perl) is configured, compiled and/or runs. It has been compiled and verified by Johan Vromans for the Synology DS413 (QorIQ), with feedback from H.Merijn Brand (DS213, ARMv5tel and RS815, Intel Atom x64).
###
Setting up the build environment
####
DSM 5
As DSM is a trimmed-down Linux system, it lacks many of the tools and libraries commonly found on Linux. The basic tools like sh, cp, rm, etc. are implemented using [BusyBox](https://en.wikipedia.org/wiki/BusyBox).
* Using your favourite browser open the DSM management page and start the Package Center.
* If you want to smoke test Perl, install `Perl`.
* In Settings, add the following Package Sources:
```
https://www.cphub.net
http://packages.quadrat4.de
```
* Still in Settings, in Channel Update, select Beta Channel.
* Press Refresh. In the left panel the item "Community" will appear. Click it. Select "Bootstrap Installer Beta" and install it.
* Likewise, install "iPKGui Beta".
The application window should now show an icon for iPKGui.
* Start iPKGui. Install the packages `make`, `gcc` and `coreutils`.
If you want to smoke test Perl, install `patch`.
The next step is to add some symlinks to system libraries. For example, the development software expect a library `libm.so` that normally is a symlink to `libm.so.6`. Synology only provides the latter and not the symlink.
Here the actual architecture of the Synology system matters. You have to find out where the gcc libraries have been installed. Look in /opt for a directory similar to arm-none-linux-gnueab or powerpc-linux-gnuspe. In the instructions below I'll use powerpc-linux-gnuspe as an example.
* On the DSM management page start the Control Panel.
* Click Terminal, and enable SSH service.
* Close Terminal and the Control Panel.
* Open a shell on the Synology using ssh and become root.
* Execute the following commands:
```
cd /lib
ln -s libm.so.6 libm.so
ln -s libcrypt.so.1 libcrypt.so
ln -s libdl.so.2 libdl.so
cd /opt/powerpc-linux-gnuspe/lib (or
/opt/arm-none-linux-gnueabi/lib)
ln -s /lib/libdl.so.2 libdl.so
```
**WARNING:** When you perform a system software upgrade, these links will disappear and need to be re-established.
####
DSM 6
Using iPkg has been deprecated on DSM 6, but an alternative is available for DSM 6: entware/opkg. For instructions on how to use that, please read [Install Entware-ng on Synology NAS](https://github.com/Entware-ng/Entware-ng/wiki/Install-on-Synology-NAS)
That sadly does not (yet) work on QorIQ. At the moment of writing, the supported architectures are armv5, armv7, mipsel, wl500g, x86\_32, and x86\_64. Check [here](https://pkg.entware.net/binaries/) for supported platforms.
Entware-ng comes with a precompiled 5.24.1 (June 2017) that allowes building shared XS code. Note that this installation does **not** use a site\_perl folder. The available `cpan` works. If all required development packages are installed too, also for XS.
###
Compiling Perl 5
When the build environment has been set up, building and testing Perl is straightforward. The only thing you need to do is download the sources as usual, and add a file Policy.sh as follows:
```
# Administrivia.
perladmin="[email protected]"
# Install Perl in a tree in /opt/perl instead of /opt/bin.
prefix=/opt/perl
# Select the compiler. Note that there is no 'cc' alias or link.
cc=gcc
# Build flags.
ccflags="-DDEBUGGING"
# Library and include paths.
libpth="/lib"
locincpth="/opt/include"
loclibpth="/lib"
```
You may want to create the destination directory and give it the right permissions before installing, thus eliminating the need to build Perl as a super user.
In the directory where you unpacked the sources, issue the familiar commands:
```
./Configure -des
make
make test
make install
```
###
Known problems
#### Configure
No known problems yet
#### Build
Error message "No error definitions found". This error is generated when it is not possible to find the local definitions for error codes, due to the uncommon structure of the Synology file system.
This error was fixed in the Perl development git for version 5.19, commit 7a8f1212e5482613c8a5b0402528e3105b26ff24.
####
Failing tests
*ext/DynaLoader/t/DynaLoader.t*
One subtest fails due to the uncommon structure of the Synology file system. The file */lib/glibc.so* is missing.
**WARNING:** Do not symlink */lib/glibc.so.6* to */lib/glibc.so* or some system components will start to fail.
###
Smoke testing Perl 5
If building completes successfully, you can set up smoke testing as described in the Test::Smoke documentation.
For smoke testing you need a running Perl. You can either install the Synology supplied package for Perl 5.8.6, or build and install your own, much more recent version.
Note that I could not run successful smokes when initiated by the Synology Task Scheduler. I resorted to initiating the smokes via a cron job run on another system, using ssh:
```
ssh nas1 wrk/Test-Smoke/smoke/smokecurrent.sh
```
####
Local patches
When local patches are applied with smoke testing, the test driver will automatically request regeneration of certain tables after the patches are applied. The Synology supplied Perl 5.8.6 (at least on the DS413) **is NOT capable** of generating these tables. It will generate opcodes with bogus values, causing the build to fail.
You can prevent regeneration by adding the setting
```
'flags' => 0,
```
to the smoke config, or by adding another patch that inserts
```
exit 0 if $] == 5.008006;
```
in the beginning of the `regen.pl` program.
###
Adding libraries
The above procedure describes a basic environment and hence results in a basic Perl. If you want to add additional libraries to Perl, you may need some extra settings.
For example, the basic Perl does not have any of the DB libraries (db, dbm, ndbm, gdsm). You can add these using iPKGui, however, you need to set environment variable LD\_LIBRARY\_PATH to the appropriate value:
```
LD_LIBRARY_PATH=/lib:/opt/lib
export LD_LIBRARY_PATH
```
This setting needs to be in effect while Perl is built, but also when the programs are run.
REVISION
--------
June 2017, for Synology DSM 5.1.5022 and DSM 6.1-15101-4.
AUTHOR
------
Johan Vromans <[email protected]> H. Merijn Brand <[email protected]>
perl TAP::Parser::Result TAP::Parser::Result
===================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
+ [DESCRIPTION](#DESCRIPTION)
+ [METHODS](#METHODS)
- [new](#new)
+ [Boolean methods](#Boolean-methods)
- [raw](#raw)
- [type](#type)
- [as\_string](#as_string)
- [is\_ok](#is_ok)
- [passed](#passed)
- [has\_directive](#has_directive)
- [has\_todo](#has_todo)
- [has\_skip](#has_skip)
- [set\_directive](#set_directive)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Result - Base class for TAP::Parser output objects
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
# abstract class - not meant to be used directly
# see TAP::Parser::ResultFactory for preferred usage
# directly:
use TAP::Parser::Result;
my $token = {...};
my $result = TAP::Parser::Result->new( $token );
```
### DESCRIPTION
This is a simple base class used by <TAP::Parser> to store objects that represent the current bit of test output data from TAP (usually a single line). Unless you're subclassing, you probably won't need to use this module directly.
### METHODS
#### `new`
```
# see TAP::Parser::ResultFactory for preferred usage
# to use directly:
my $result = TAP::Parser::Result->new($token);
```
Returns an instance the appropriate class for the test token passed in.
###
Boolean methods
The following methods all return a boolean value and are to be overridden in the appropriate subclass.
* `is_plan`
Indicates whether or not this is the test plan line.
```
1..3
```
* `is_pragma`
Indicates whether or not this is a pragma line.
```
pragma +strict
```
* `is_test`
Indicates whether or not this is a test line.
```
ok 1 Is OK!
```
* `is_comment`
Indicates whether or not this is a comment.
```
# this is a comment
```
* `is_bailout`
Indicates whether or not this is bailout line.
```
Bail out! We're out of dilithium crystals.
```
* `is_version`
Indicates whether or not this is a TAP version line.
```
TAP version 4
```
* `is_unknown`
Indicates whether or not the current line could be parsed.
```
... this line is junk ...
```
* `is_yaml`
Indicates whether or not this is a YAML chunk.
#### `raw`
```
print $result->raw;
```
Returns the original line of text which was parsed.
#### `type`
```
my $type = $result->type;
```
Returns the "type" of a token, such as `comment` or `test`.
#### `as_string`
```
print $result->as_string;
```
Prints a string representation of the token. This might not be the exact output, however. Tests will have test numbers added if not present, TODO and SKIP directives will be capitalized and, in general, things will be cleaned up. If you need the original text for the token, see the `raw` method.
#### `is_ok`
```
if ( $result->is_ok ) { ... }
```
Reports whether or not a given result has passed. Anything which is **not** a test result returns true. This is merely provided as a convenient shortcut.
#### `passed`
Deprecated. Please use `is_ok` instead.
#### `has_directive`
```
if ( $result->has_directive ) {
...
}
```
Indicates whether or not the given result has a TODO or SKIP directive.
#### `has_todo`
```
if ( $result->has_todo ) {
...
}
```
Indicates whether or not the given result has a TODO directive.
#### `has_skip`
```
if ( $result->has_skip ) {
...
}
```
Indicates whether or not the given result has a SKIP directive.
#### `set_directive`
Set the directive associated with this token. Used internally to fake TODO tests.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
Remember: if you want your subclass to be automatically used by the parser, you'll have to register it with ["register\_type" in TAP::Parser::ResultFactory](TAP::Parser::ResultFactory#register_type).
If you're creating a completely new result *type*, you'll probably need to subclass <TAP::Parser::Grammar> too, or else it'll never get used.
### Example
```
package MyResult;
use strict;
use base 'TAP::Parser::Result';
# register with the factory:
TAP::Parser::ResultFactory->register_type( 'my_type' => __PACKAGE__ );
sub as_string { 'My results all look the same' }
```
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::ResultFactory>, <TAP::Parser::Result::Bailout>, <TAP::Parser::Result::Comment>, <TAP::Parser::Result::Plan>, <TAP::Parser::Result::Pragma>, <TAP::Parser::Result::Test>, <TAP::Parser::Result::Unknown>, <TAP::Parser::Result::Version>, <TAP::Parser::Result::YAML>,
perl TAP::Parser::Result::Unknown TAP::Parser::Result::Unknown
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDDEN METHODS](#OVERRIDDEN-METHODS)
NAME
----
TAP::Parser::Result::Unknown - Unknown result token.
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This is a subclass of <TAP::Parser::Result>. A token of this class will be returned if the parser does not recognize the token line. For example:
```
1..5
VERSION 7
ok 1 - woo hooo!
... woo hooo! is cool!
```
In the above "TAP", the second and fourth lines will generate "Unknown" tokens.
OVERRIDDEN METHODS
-------------------
Mainly listed here to shut up the pitiful screams of the pod coverage tests. They keep me awake at night.
* `as_string`
* `raw`
perl Net::protoent Net::protoent
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
Net::protoent - by-name interface to Perl's built-in getproto\*() functions
SYNOPSIS
--------
```
use Net::protoent;
$p = getprotobyname(shift || 'tcp') || die "no proto";
printf "proto for %s is %d, aliases are %s\n",
$p->name, $p->proto, "@{$p->aliases}";
use Net::protoent qw(:FIELDS);
getprotobyname(shift || 'tcp') || die "no proto";
print "proto for $p_name is $p_proto, aliases are @p_aliases\n";
```
DESCRIPTION
-----------
This module's default exports override the core getprotoent(), getprotobyname(), and getnetbyport() functions, replacing them with versions that return "Net::protoent" objects. They take default second arguments of "tcp". This object has methods that return the similarly named structure field name from the C's protoent structure from *netdb.h*; namely name, aliases, and proto. The aliases method returns an array reference, the rest scalars.
You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. (Note that this still overrides your core functions.) Access these fields as variables named with a preceding `p_`. Thus, `$proto_obj->name()` corresponds to $p\_name if you import the fields. Array references are available as regular array variables, so for example `@{ $proto_obj->aliases() }` would be simply @p\_aliases.
The getproto() function is a simple front-end that forwards a numeric argument to getprotobyport(), and the rest to getprotobyname().
To access this functionality without the core overrides, pass the `use` an empty import list, and then access function functions with their full qualified names. On the other hand, the built-ins are still available via the `CORE::` pseudo-package.
NOTE
----
While this class is currently implemented using the Class::Struct module to build a struct-like class, you shouldn't rely upon this.
AUTHOR
------
Tom Christiansen
perl perlretut perlretut
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Part 1: The basics](#Part-1:-The-basics)
+ [Simple word matching](#Simple-word-matching)
+ [Using character classes](#Using-character-classes)
+ [Matching this or that](#Matching-this-or-that)
+ [Grouping things and hierarchical matching](#Grouping-things-and-hierarchical-matching)
+ [Extracting matches](#Extracting-matches)
+ [Backreferences](#Backreferences)
+ [Relative backreferences](#Relative-backreferences)
+ [Named backreferences](#Named-backreferences)
+ [Alternative capture group numbering](#Alternative-capture-group-numbering)
+ [Position information](#Position-information)
+ [Non-capturing groupings](#Non-capturing-groupings)
+ [Matching repetitions](#Matching-repetitions)
+ [Possessive quantifiers](#Possessive-quantifiers)
+ [Building a regexp](#Building-a-regexp)
+ [Using regular expressions in Perl](#Using-regular-expressions-in-Perl)
- [Prohibiting substitution](#Prohibiting-substitution)
- [Global matching](#Global-matching)
- [Search and replace](#Search-and-replace)
- [The split function](#The-split-function)
* [Part 2: Power tools](#Part-2:-Power-tools)
+ [More on characters, strings, and character classes](#More-on-characters,-strings,-and-character-classes)
+ [Compiling and saving regular expressions](#Compiling-and-saving-regular-expressions)
+ [Composing regular expressions at runtime](#Composing-regular-expressions-at-runtime)
+ [Embedding comments and modifiers in a regular expression](#Embedding-comments-and-modifiers-in-a-regular-expression)
+ [Looking ahead and looking behind](#Looking-ahead-and-looking-behind)
+ [Using independent subexpressions to prevent backtracking](#Using-independent-subexpressions-to-prevent-backtracking)
+ [Conditional expressions](#Conditional-expressions)
+ [Defining named patterns](#Defining-named-patterns)
+ [Recursive patterns](#Recursive-patterns)
+ [A bit of magic: executing Perl code in a regular expression](#A-bit-of-magic:-executing-Perl-code-in-a-regular-expression)
+ [Backtracking control verbs](#Backtracking-control-verbs)
+ [Pragmas and debugging](#Pragmas-and-debugging)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
+ [Acknowledgments](#Acknowledgments)
NAME
----
perlretut - Perl regular expressions tutorial
DESCRIPTION
-----------
This page provides a basic tutorial on understanding, creating and using regular expressions in Perl. It serves as a complement to the reference page on regular expressions <perlre>. Regular expressions are an integral part of the `m//`, `s///`, `qr//` and `split` operators and so this tutorial also overlaps with ["Regexp Quote-Like Operators" in perlop](perlop#Regexp-Quote-Like-Operators) and ["split" in perlfunc](perlfunc#split).
Perl is widely renowned for excellence in text processing, and regular expressions are one of the big factors behind this fame. Perl regular expressions display an efficiency and flexibility unknown in most other computer languages. Mastering even the basics of regular expressions will allow you to manipulate text with surprising ease.
What is a regular expression? At its most basic, a regular expression is a template that is used to determine if a string has certain characteristics. The string is most often some text, such as a line, sentence, web page, or even a whole book, but it doesn't have to be. It could be binary data, for example. Biologists often use Perl to look for patterns in long DNA sequences.
Suppose we want to determine if the text in variable, `$var` contains the sequence of characters `m u s h r o o m` (blanks added for legibility). We can write in Perl
```
$var =~ m/mushroom/
```
The value of this expression will be TRUE if `$var` contains that sequence of characters anywhere within it, and FALSE otherwise. The portion enclosed in `'/'` characters denotes the characteristic we are looking for. We use the term *pattern* for it. The process of looking to see if the pattern occurs in the string is called *matching*, and the `"=~"` operator along with the `m//` tell Perl to try to match the pattern against the string. Note that the pattern is also a string, but a very special kind of one, as we will see. Patterns are in common use these days; examples are the patterns typed into a search engine to find web pages and the patterns used to list files in a directory, *e.g.*, "`ls *.txt`" or "`dir *.*`". In Perl, the patterns described by regular expressions are used not only to search strings, but to also extract desired parts of strings, and to do search and replace operations.
Regular expressions have the undeserved reputation of being abstract and difficult to understand. This really stems simply because the notation used to express them tends to be terse and dense, and not because of inherent complexity. We recommend using the `/x` regular expression modifier (described below) along with plenty of white space to make them less dense, and easier to read. Regular expressions are constructed using simple concepts like conditionals and loops and are no more difficult to understand than the corresponding `if` conditionals and `while` loops in the Perl language itself.
This tutorial flattens the learning curve by discussing regular expression concepts, along with their notation, one at a time and with many examples. The first part of the tutorial will progress from the simplest word searches to the basic regular expression concepts. If you master the first part, you will have all the tools needed to solve about 98% of your needs. The second part of the tutorial is for those comfortable with the basics and hungry for more power tools. It discusses the more advanced regular expression operators and introduces the latest cutting-edge innovations.
A note: to save time, "regular expression" is often abbreviated as regexp or regex. Regexp is a more natural abbreviation than regex, but is harder to pronounce. The Perl pod documentation is evenly split on regexp vs regex; in Perl, there is more than one way to abbreviate it. We'll use regexp in this tutorial.
New in v5.22, [`use re 'strict'`](re#%27strict%27-mode) applies stricter rules than otherwise when compiling regular expression patterns. It can find things that, while legal, may not be what you intended.
Part 1: The basics
-------------------
###
Simple word matching
The simplest regexp is simply a word, or more generally, a string of characters. A regexp consisting of just a word matches any string that contains that word:
```
"Hello World" =~ /World/; # matches
```
What is this Perl statement all about? `"Hello World"` is a simple double-quoted string. `World` is the regular expression and the `//` enclosing `/World/` tells Perl to search a string for a match. The operator `=~` associates the string with the regexp match and produces a true value if the regexp matched, or false if the regexp did not match. In our case, `World` matches the second word in `"Hello World"`, so the expression is true. Expressions like this are useful in conditionals:
```
if ("Hello World" =~ /World/) {
print "It matches\n";
}
else {
print "It doesn't match\n";
}
```
There are useful variations on this theme. The sense of the match can be reversed by using the `!~` operator:
```
if ("Hello World" !~ /World/) {
print "It doesn't match\n";
}
else {
print "It matches\n";
}
```
The literal string in the regexp can be replaced by a variable:
```
my $greeting = "World";
if ("Hello World" =~ /$greeting/) {
print "It matches\n";
}
else {
print "It doesn't match\n";
}
```
If you're matching against the special default variable `$_`, the `$_ =~` part can be omitted:
```
$_ = "Hello World";
if (/World/) {
print "It matches\n";
}
else {
print "It doesn't match\n";
}
```
And finally, the `//` default delimiters for a match can be changed to arbitrary delimiters by putting an `'m'` out front:
```
"Hello World" =~ m!World!; # matches, delimited by '!'
"Hello World" =~ m{World}; # matches, note the paired '{}'
"/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
# '/' becomes an ordinary char
```
`/World/`, `m!World!`, and `m{World}` all represent the same thing. When, *e.g.*, the quote (`'"'`) is used as a delimiter, the forward slash `'/'` becomes an ordinary character and can be used in this regexp without trouble.
Let's consider how different regexps would match `"Hello World"`:
```
"Hello World" =~ /world/; # doesn't match
"Hello World" =~ /o W/; # matches
"Hello World" =~ /oW/; # doesn't match
"Hello World" =~ /World /; # doesn't match
```
The first regexp `world` doesn't match because regexps are by default case-sensitive. The second regexp matches because the substring `'o W'` occurs in the string `"Hello World"`. The space character `' '` is treated like any other character in a regexp and is needed to match in this case. The lack of a space character is the reason the third regexp `'oW'` doesn't match. The fourth regexp "`World` " doesn't match because there is a space at the end of the regexp, but not at the end of the string. The lesson here is that regexps must match a part of the string *exactly* in order for the statement to be true.
If a regexp matches in more than one place in the string, Perl will always match at the earliest possible point in the string:
```
"Hello World" =~ /o/; # matches 'o' in 'Hello'
"That hat is red" =~ /hat/; # matches 'hat' in 'That'
```
With respect to character matching, there are a few more points you need to know about. First of all, not all characters can be used "as-is" in a match. Some characters, called *metacharacters*, are generally reserved for use in regexp notation. The metacharacters are
```
{}[]()^$.|*+?-#\
```
This list is not as definitive as it may appear (or be claimed to be in other documentation). For example, `"#"` is a metacharacter only when the `/x` pattern modifier (described below) is used, and both `"}"` and `"]"` are metacharacters only when paired with opening `"{"` or `"["` respectively; other gotchas apply.
The significance of each of these will be explained in the rest of the tutorial, but for now, it is important only to know that a metacharacter can be matched as-is by putting a backslash before it:
```
"2+2=4" =~ /2+2/; # doesn't match, + is a metacharacter
"2+2=4" =~ /2\+2/; # matches, \+ is treated like an ordinary +
"The interval is [0,1)." =~ /[0,1)./ # is a syntax error!
"The interval is [0,1)." =~ /\[0,1\)\./ # matches
"#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/; # matches
```
In the last regexp, the forward slash `'/'` is also backslashed, because it is used to delimit the regexp. This can lead to LTS (leaning toothpick syndrome), however, and it is often more readable to change delimiters.
```
"#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!; # easier to read
```
The backslash character `'\'` is a metacharacter itself and needs to be backslashed:
```
'C:\WIN32' =~ /C:\\WIN/; # matches
```
In situations where it doesn't make sense for a particular metacharacter to mean what it normally does, it automatically loses its metacharacter-ness and becomes an ordinary character that is to be matched literally. For example, the `'}'` is a metacharacter only when it is the mate of a `'{'` metacharacter. Otherwise it is treated as a literal RIGHT CURLY BRACKET. This may lead to unexpected results. [`use re 'strict'`](re#%27strict%27-mode) can catch some of these.
In addition to the metacharacters, there are some ASCII characters which don't have printable character equivalents and are instead represented by *escape sequences*. Common examples are `\t` for a tab, `\n` for a newline, `\r` for a carriage return and `\a` for a bell (or alert). If your string is better thought of as a sequence of arbitrary bytes, the octal escape sequence, *e.g.*, `\033`, or hexadecimal escape sequence, *e.g.*, `\x1B` may be a more natural representation for your bytes. Here are some examples of escapes:
```
"1000\t2000" =~ m(0\t2) # matches
"1000\n2000" =~ /0\n20/ # matches
"1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
"cat" =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
# to spell cat
```
If you've been around Perl a while, all this talk of escape sequences may seem familiar. Similar escape sequences are used in double-quoted strings and in fact the regexps in Perl are mostly treated as double-quoted strings. This means that variables can be used in regexps as well. Just like double-quoted strings, the values of the variables in the regexp will be substituted in before the regexp is evaluated for matching purposes. So we have:
```
$foo = 'house';
'housecat' =~ /$foo/; # matches
'cathouse' =~ /cat$foo/; # matches
'housecat' =~ /${foo}cat/; # matches
```
So far, so good. With the knowledge above you can already perform searches with just about any literal string regexp you can dream up. Here is a *very simple* emulation of the Unix grep program:
```
% cat > simple_grep
#!/usr/bin/perl
$regexp = shift;
while (<>) {
print if /$regexp/;
}
^D
% chmod +x simple_grep
% simple_grep abba /usr/dict/words
Babbage
cabbage
cabbages
sabbath
Sabbathize
Sabbathizes
sabbatical
scabbard
scabbards
```
This program is easy to understand. `#!/usr/bin/perl` is the standard way to invoke a perl program from the shell. `$regexp = shift;` saves the first command line argument as the regexp to be used, leaving the rest of the command line arguments to be treated as files. `while (<>)` loops over all the lines in all the files. For each line, `print if /$regexp/;` prints the line if the regexp matches the line. In this line, both `print` and `/$regexp/` use the default variable `$_` implicitly.
With all of the regexps above, if the regexp matched anywhere in the string, it was considered a match. Sometimes, however, we'd like to specify *where* in the string the regexp should try to match. To do this, we would use the *anchor* metacharacters `'^'` and `'$'`. The anchor `'^'` means match at the beginning of the string and the anchor `'$'` means match at the end of the string, or before a newline at the end of the string. Here is how they are used:
```
"housekeeper" =~ /keeper/; # matches
"housekeeper" =~ /^keeper/; # doesn't match
"housekeeper" =~ /keeper$/; # matches
"housekeeper\n" =~ /keeper$/; # matches
```
The second regexp doesn't match because `'^'` constrains `keeper` to match only at the beginning of the string, but `"housekeeper"` has keeper starting in the middle. The third regexp does match, since the `'$'` constrains `keeper` to match only at the end of the string.
When both `'^'` and `'$'` are used at the same time, the regexp has to match both the beginning and the end of the string, *i.e.*, the regexp matches the whole string. Consider
```
"keeper" =~ /^keep$/; # doesn't match
"keeper" =~ /^keeper$/; # matches
"" =~ /^$/; # ^$ matches an empty string
```
The first regexp doesn't match because the string has more to it than `keep`. Since the second regexp is exactly the string, it matches. Using both `'^'` and `'$'` in a regexp forces the complete string to match, so it gives you complete control over which strings match and which don't. Suppose you are looking for a fellow named bert, off in a string by himself:
```
"dogbert" =~ /bert/; # matches, but not what you want
"dilbert" =~ /^bert/; # doesn't match, but ..
"bertram" =~ /^bert/; # matches, so still not good enough
"bertram" =~ /^bert$/; # doesn't match, good
"dilbert" =~ /^bert$/; # doesn't match, good
"bert" =~ /^bert$/; # matches, perfect
```
Of course, in the case of a literal string, one could just as easily use the string comparison `$string eq 'bert'` and it would be more efficient. The `^...$` regexp really becomes useful when we add in the more powerful regexp tools below.
###
Using character classes
Although one can already do quite a lot with the literal string regexps above, we've only scratched the surface of regular expression technology. In this and subsequent sections we will introduce regexp concepts (and associated metacharacter notations) that will allow a regexp to represent not just a single character sequence, but a *whole class* of them.
One such concept is that of a *character class*. A character class allows a set of possible characters, rather than just a single character, to match at a particular point in a regexp. You can define your own custom character classes. These are denoted by brackets `[...]`, with the set of characters to be possibly matched inside. Here are some examples:
```
/cat/; # matches 'cat'
/[bcr]at/; # matches 'bat, 'cat', or 'rat'
/item[0123456789]/; # matches 'item0' or ... or 'item9'
"abc" =~ /[cab]/; # matches 'a'
```
In the last statement, even though `'c'` is the first character in the class, `'a'` matches because the first character position in the string is the earliest point at which the regexp can match.
```
/[yY][eE][sS]/; # match 'yes' in a case-insensitive way
# 'yes', 'Yes', 'YES', etc.
```
This regexp displays a common task: perform a case-insensitive match. Perl provides a way of avoiding all those brackets by simply appending an `'i'` to the end of the match. Then `/[yY][eE][sS]/;` can be rewritten as `/yes/i;`. The `'i'` stands for case-insensitive and is an example of a *modifier* of the matching operation. We will meet other modifiers later in the tutorial.
We saw in the section above that there were ordinary characters, which represented themselves, and special characters, which needed a backslash `'\'` to represent themselves. The same is true in a character class, but the sets of ordinary and special characters inside a character class are different than those outside a character class. The special characters for a character class are `-]\^$` (and the pattern delimiter, whatever it is). `']'` is special because it denotes the end of a character class. `'$'` is special because it denotes a scalar variable. `'\'` is special because it is used in escape sequences, just like above. Here is how the special characters `]$\` are handled:
```
/[\]c]def/; # matches ']def' or 'cdef'
$x = 'bcr';
/[$x]at/; # matches 'bat', 'cat', or 'rat'
/[\$x]at/; # matches '$at' or 'xat'
/[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
```
The last two are a little tricky. In `[\$x]`, the backslash protects the dollar sign, so the character class has two members `'$'` and `'x'`. In `[\\$x]`, the backslash is protected, so `$x` is treated as a variable and substituted in double quote fashion.
The special character `'-'` acts as a range operator within character classes, so that a contiguous set of characters can be written as a range. With ranges, the unwieldy `[0123456789]` and `[abc...xyz]` become the svelte `[0-9]` and `[a-z]`. Some examples are
```
/item[0-9]/; # matches 'item0' or ... or 'item9'
/[0-9bx-z]aa/; # matches '0aa', ..., '9aa',
# 'baa', 'xaa', 'yaa', or 'zaa'
/[0-9a-fA-F]/; # matches a hexadecimal digit
/[0-9a-zA-Z_]/; # matches a "word" character,
# like those in a Perl variable name
```
If `'-'` is the first or last character in a character class, it is treated as an ordinary character; `[-ab]`, `[ab-]` and `[a\-b]` are all equivalent.
The special character `'^'` in the first position of a character class denotes a *negated character class*, which matches any character but those in the brackets. Both `[...]` and `[^...]` must match a character, or the match fails. Then
```
/[^a]at/; # doesn't match 'aat' or 'at', but matches
# all other 'bat', 'cat, '0at', '%at', etc.
/[^0-9]/; # matches a non-numeric character
/[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary
```
Now, even `[0-9]` can be a bother to write multiple times, so in the interest of saving keystrokes and making regexps more readable, Perl has several abbreviations for common character classes, as shown below. Since the introduction of Unicode, unless the `/a` modifier is in effect, these character classes match more than just a few characters in the ASCII range.
* `\d` matches a digit, not just `[0-9]` but also digits from non-roman scripts
* `\s` matches a whitespace character, the set `[\ \t\r\n\f]` and others
* `\w` matches a word character (alphanumeric or `'_'`), not just `[0-9a-zA-Z_]` but also digits and characters from non-roman scripts
* `\D` is a negated `\d`; it represents any other character than a digit, or `[^\d]`
* `\S` is a negated `\s`; it represents any non-whitespace character `[^\s]`
* `\W` is a negated `\w`; it represents any non-word character `[^\w]`
* The period `'.'` matches any character but `"\n"` (unless the modifier `/s` is in effect, as explained below).
* `\N`, like the period, matches any character but `"\n"`, but it does so regardless of whether the modifier `/s` is in effect.
The `/a` modifier, available starting in Perl 5.14, is used to restrict the matches of `\d`, `\s`, and `\w` to just those in the ASCII range. It is useful to keep your program from being needlessly exposed to full Unicode (and its accompanying security considerations) when all you want is to process English-like text. (The "a" may be doubled, `/aa`, to provide even more restrictions, preventing case-insensitive matching of ASCII with non-ASCII characters; otherwise a Unicode "Kelvin Sign" would caselessly match a "k" or "K".)
The `\d\s\w\D\S\W` abbreviations can be used both inside and outside of bracketed character classes. Here are some in use:
```
/\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
/[\d\s]/; # matches any digit or whitespace character
/\w\W\w/; # matches a word char, followed by a
# non-word char, followed by a word char
/..rt/; # matches any two chars, followed by 'rt'
/end\./; # matches 'end.'
/end[.]/; # same thing, matches 'end.'
```
Because a period is a metacharacter, it needs to be escaped to match as an ordinary period. Because, for example, `\d` and `\w` are sets of characters, it is incorrect to think of `[^\d\w]` as `[\D\W]`; in fact `[^\d\w]` is the same as `[^\w]`, which is the same as `[\W]`. Think De Morgan's laws.
In actuality, the period and `\d\s\w\D\S\W` abbreviations are themselves types of character classes, so the ones surrounded by brackets are just one type of character class. When we need to make a distinction, we refer to them as "bracketed character classes."
An anchor useful in basic regexps is the *word anchor* `\b`. This matches a boundary between a word character and a non-word character `\w\W` or `\W\w`:
```
$x = "Housecat catenates house and cat";
$x =~ /cat/; # matches cat in 'housecat'
$x =~ /\bcat/; # matches cat in 'catenates'
$x =~ /cat\b/; # matches cat in 'housecat'
$x =~ /\bcat\b/; # matches 'cat' at end of string
```
Note in the last example, the end of the string is considered a word boundary.
For natural language processing (so that, for example, apostrophes are included in words), use instead `\b{wb}`
```
"don't" =~ / .+? \b{wb} /x; # matches the whole string
```
You might wonder why `'.'` matches everything but `"\n"` - why not every character? The reason is that often one is matching against lines and would like to ignore the newline characters. For instance, while the string `"\n"` represents one line, we would like to think of it as empty. Then
```
"" =~ /^$/; # matches
"\n" =~ /^$/; # matches, $ anchors before "\n"
"" =~ /./; # doesn't match; it needs a char
"" =~ /^.$/; # doesn't match; it needs a char
"\n" =~ /^.$/; # doesn't match; it needs a char other than "\n"
"a" =~ /^.$/; # matches
"a\n" =~ /^.$/; # matches, $ anchors before "\n"
```
This behavior is convenient, because we usually want to ignore newlines when we count and match characters in a line. Sometimes, however, we want to keep track of newlines. We might even want `'^'` and `'$'` to anchor at the beginning and end of lines within the string, rather than just the beginning and end of the string. Perl allows us to choose between ignoring and paying attention to newlines by using the `/s` and `/m` modifiers. `/s` and `/m` stand for single line and multi-line and they determine whether a string is to be treated as one continuous string, or as a set of lines. The two modifiers affect two aspects of how the regexp is interpreted: 1) how the `'.'` character class is defined, and 2) where the anchors `'^'` and `'$'` are able to match. Here are the four possible combinations:
* no modifiers: Default behavior. `'.'` matches any character except `"\n"`. `'^'` matches only at the beginning of the string and `'$'` matches only at the end or before a newline at the end.
* s modifier (`/s`): Treat string as a single long line. `'.'` matches any character, even `"\n"`. `'^'` matches only at the beginning of the string and `'$'` matches only at the end or before a newline at the end.
* m modifier (`/m`): Treat string as a set of multiple lines. `'.'` matches any character except `"\n"`. `'^'` and `'$'` are able to match at the start or end of *any* line within the string.
* both s and m modifiers (`/sm`): Treat string as a single long line, but detect multiple lines. `'.'` matches any character, even `"\n"`. `'^'` and `'$'`, however, are able to match at the start or end of *any* line within the string.
Here are examples of `/s` and `/m` in action:
```
$x = "There once was a girl\nWho programmed in Perl\n";
$x =~ /^Who/; # doesn't match, "Who" not at start of string
$x =~ /^Who/s; # doesn't match, "Who" not at start of string
$x =~ /^Who/m; # matches, "Who" at start of second line
$x =~ /^Who/sm; # matches, "Who" at start of second line
$x =~ /girl.Who/; # doesn't match, "." doesn't match "\n"
$x =~ /girl.Who/s; # matches, "." matches "\n"
$x =~ /girl.Who/m; # doesn't match, "." doesn't match "\n"
$x =~ /girl.Who/sm; # matches, "." matches "\n"
```
Most of the time, the default behavior is what is wanted, but `/s` and `/m` are occasionally very useful. If `/m` is being used, the start of the string can still be matched with `\A` and the end of the string can still be matched with the anchors `\Z` (matches both the end and the newline before, like `'$'`), and `\z` (matches only the end):
```
$x =~ /^Who/m; # matches, "Who" at start of second line
$x =~ /\AWho/m; # doesn't match, "Who" is not at start of string
$x =~ /girl$/m; # matches, "girl" at end of first line
$x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
$x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
$x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
```
We now know how to create choices among classes of characters in a regexp. What about choices among words or character strings? Such choices are described in the next section.
###
Matching this or that
Sometimes we would like our regexp to be able to match different possible words or character strings. This is accomplished by using the *alternation* metacharacter `'|'`. To match `dog` or `cat`, we form the regexp `dog|cat`. As before, Perl will try to match the regexp at the earliest possible point in the string. At each character position, Perl will first try to match the first alternative, `dog`. If `dog` doesn't match, Perl will then try the next alternative, `cat`. If `cat` doesn't match either, then the match fails and Perl moves to the next position in the string. Some examples:
```
"cats and dogs" =~ /cat|dog|bird/; # matches "cat"
"cats and dogs" =~ /dog|cat|bird/; # matches "cat"
```
Even though `dog` is the first alternative in the second regexp, `cat` is able to match earlier in the string.
```
"cats" =~ /c|ca|cat|cats/; # matches "c"
"cats" =~ /cats|cat|ca|c/; # matches "cats"
```
Here, all the alternatives match at the first string position, so the first alternative is the one that matches. If some of the alternatives are truncations of the others, put the longest ones first to give them a chance to match.
```
"cab" =~ /a|b|c/ # matches "c"
# /a|b|c/ == /[abc]/
```
The last example points out that character classes are like alternations of characters. At a given character position, the first alternative that allows the regexp match to succeed will be the one that matches.
###
Grouping things and hierarchical matching
Alternation allows a regexp to choose among alternatives, but by itself it is unsatisfying. The reason is that each alternative is a whole regexp, but sometime we want alternatives for just part of a regexp. For instance, suppose we want to search for housecats or housekeepers. The regexp `housecat|housekeeper` fits the bill, but is inefficient because we had to type `house` twice. It would be nice to have parts of the regexp be constant, like `house`, and some parts have alternatives, like `cat|keeper`.
The *grouping* metacharacters `()` solve this problem. Grouping allows parts of a regexp to be treated as a single unit. Parts of a regexp are grouped by enclosing them in parentheses. Thus we could solve the `housecat|housekeeper` by forming the regexp as `house(cat|keeper)`. The regexp `house(cat|keeper)` means match `house` followed by either `cat` or `keeper`. Some more examples are
```
/(a|b)b/; # matches 'ab' or 'bb'
/(ac|b)b/; # matches 'acb' or 'bb'
/(^a|b)c/; # matches 'ac' at start of string or 'bc' anywhere
/(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
/house(cat|)/; # matches either 'housecat' or 'house'
/house(cat(s|)|)/; # matches either 'housecats' or 'housecat' or
# 'house'. Note groups can be nested.
/(19|20|)\d\d/; # match years 19xx, 20xx, or the Y2K problem, xx
"20" =~ /(19|20|)\d\d/; # matches the null alternative '()\d\d',
# because '20\d\d' can't match
```
Alternations behave the same way in groups as out of them: at a given string position, the leftmost alternative that allows the regexp to match is taken. So in the last example at the first string position, `"20"` matches the second alternative, but there is nothing left over to match the next two digits `\d\d`. So Perl moves on to the next alternative, which is the null alternative and that works, since `"20"` is two digits.
The process of trying one alternative, seeing if it matches, and moving on to the next alternative, while going back in the string from where the previous alternative was tried, if it doesn't, is called *backtracking*. The term "backtracking" comes from the idea that matching a regexp is like a walk in the woods. Successfully matching a regexp is like arriving at a destination. There are many possible trailheads, one for each string position, and each one is tried in order, left to right. From each trailhead there may be many paths, some of which get you there, and some which are dead ends. When you walk along a trail and hit a dead end, you have to backtrack along the trail to an earlier point to try another trail. If you hit your destination, you stop immediately and forget about trying all the other trails. You are persistent, and only if you have tried all the trails from all the trailheads and not arrived at your destination, do you declare failure. To be concrete, here is a step-by-step analysis of what Perl does when it tries to match the regexp
```
"abcde" =~ /(abd|abc)(df|d|de)/;
```
0. Start with the first letter in the string `'a'`.
1. Try the first alternative in the first group `'abd'`.
2. Match `'a'` followed by `'b'`. So far so good.
3. `'d'` in the regexp doesn't match `'c'` in the string - a dead end. So backtrack two characters and pick the second alternative in the first group `'abc'`.
4. Match `'a'` followed by `'b'` followed by `'c'`. We are on a roll and have satisfied the first group. Set `$1` to `'abc'`.
5 Move on to the second group and pick the first alternative `'df'`.
6 Match the `'d'`.
7. `'f'` in the regexp doesn't match `'e'` in the string, so a dead end. Backtrack one character and pick the second alternative in the second group `'d'`.
8. `'d'` matches. The second grouping is satisfied, so set `$2` to `'d'`.
9. We are at the end of the regexp, so we are done! We have matched `'abcd'` out of the string `"abcde"`. There are a couple of things to note about this analysis. First, the third alternative in the second group `'de'` also allows a match, but we stopped before we got to it - at a given character position, leftmost wins. Second, we were able to get a match at the first character position of the string `'a'`. If there were no matches at the first position, Perl would move to the second character position `'b'` and attempt the match all over again. Only when all possible paths at all possible character positions have been exhausted does Perl give up and declare `$string =~ /(abd|abc)(df|d|de)/;` to be false.
Even with all this work, regexp matching happens remarkably fast. To speed things up, Perl compiles the regexp into a compact sequence of opcodes that can often fit inside a processor cache. When the code is executed, these opcodes can then run at full throttle and search very quickly.
###
Extracting matches
The grouping metacharacters `()` also serve another completely different function: they allow the extraction of the parts of a string that matched. This is very useful to find out what matched and for text processing in general. For each grouping, the part that matched inside goes into the special variables `$1`, `$2`, *etc*. They can be used just as ordinary variables:
```
# extract hours, minutes, seconds
if ($time =~ /(\d\d):(\d\d):(\d\d)/) { # match hh:mm:ss format
$hours = $1;
$minutes = $2;
$seconds = $3;
}
```
Now, we know that in scalar context, `$time =~ /(\d\d):(\d\d):(\d\d)/` returns a true or false value. In list context, however, it returns the list of matched values `($1,$2,$3)`. So we could write the code more compactly as
```
# extract hours, minutes, seconds
($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
```
If the groupings in a regexp are nested, `$1` gets the group with the leftmost opening parenthesis, `$2` the next opening parenthesis, *etc*. Here is a regexp with nested groups:
```
/(ab(cd|ef)((gi)|j))/;
1 2 34
```
If this regexp matches, `$1` contains a string starting with `'ab'`, `$2` is either set to `'cd'` or `'ef'`, `$3` equals either `'gi'` or `'j'`, and `$4` is either set to `'gi'`, just like `$3`, or it remains undefined.
For convenience, Perl sets `$+` to the string held by the highest numbered `$1`, `$2`,... that got assigned (and, somewhat related, `$^N` to the value of the `$1`, `$2`,... most-recently assigned; *i.e.* the `$1`, `$2`,... associated with the rightmost closing parenthesis used in the match).
### Backreferences
Closely associated with the matching variables `$1`, `$2`, ... are the *backreferences* `\g1`, `\g2`,... Backreferences are simply matching variables that can be used *inside* a regexp. This is a really nice feature; what matches later in a regexp is made to depend on what matched earlier in the regexp. Suppose we wanted to look for doubled words in a text, like "the the". The following regexp finds all 3-letter doubles with a space in between:
```
/\b(\w\w\w)\s\g1\b/;
```
The grouping assigns a value to `\g1`, so that the same 3-letter sequence is used for both parts.
A similar task is to find words consisting of two identical parts:
```
% simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
beriberi
booboo
coco
mama
murmur
papa
```
The regexp has a single grouping which considers 4-letter combinations, then 3-letter combinations, *etc*., and uses `\g1` to look for a repeat. Although `$1` and `\g1` represent the same thing, care should be taken to use matched variables `$1`, `$2`,... only *outside* a regexp and backreferences `\g1`, `\g2`,... only *inside* a regexp; not doing so may lead to surprising and unsatisfactory results.
###
Relative backreferences
Counting the opening parentheses to get the correct number for a backreference is error-prone as soon as there is more than one capturing group. A more convenient technique became available with Perl 5.10: relative backreferences. To refer to the immediately preceding capture group one now may write `\g-1` or `\g{-1}`, the next but last is available via `\g-2` or `\g{-2}`, and so on.
Another good reason in addition to readability and maintainability for using relative backreferences is illustrated by the following example, where a simple pattern for matching peculiar strings is used:
```
$a99a = '([a-z])(\d)\g2\g1'; # matches a11a, g22g, x33x, etc.
```
Now that we have this pattern stored as a handy string, we might feel tempted to use it as a part of some other pattern:
```
$line = "code=e99e";
if ($line =~ /^(\w+)=$a99a$/){ # unexpected behavior!
print "$1 is valid\n";
} else {
print "bad line: '$line'\n";
}
```
But this doesn't match, at least not the way one might expect. Only after inserting the interpolated `$a99a` and looking at the resulting full text of the regexp is it obvious that the backreferences have backfired. The subexpression `(\w+)` has snatched number 1 and demoted the groups in `$a99a` by one rank. This can be avoided by using relative backreferences:
```
$a99a = '([a-z])(\d)\g{-1}\g{-2}'; # safe for being interpolated
```
###
Named backreferences
Perl 5.10 also introduced named capture groups and named backreferences. To attach a name to a capturing group, you write either `(?<name>...)` or `(?'name'...)`. The backreference may then be written as `\g{name}`. It is permissible to attach the same name to more than one group, but then only the leftmost one of the eponymous set can be referenced. Outside of the pattern a named capture group is accessible through the `%+` hash.
Assuming that we have to match calendar dates which may be given in one of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write three suitable patterns where we use `'d'`, `'m'` and `'y'` respectively as the names of the groups capturing the pertaining components of a date. The matching operation combines the three patterns as alternatives:
```
$fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
$fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
$fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
print "day=$+{d} month=$+{m} year=$+{y}\n";
}
}
```
If any of the alternatives matches, the hash `%+` is bound to contain the three key-value pairs.
###
Alternative capture group numbering
Yet another capturing group numbering technique (also as from Perl 5.10) deals with the problem of referring to groups within a set of alternatives. Consider a pattern for matching a time of the day, civil or military style:
```
if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
# process hour and minute
}
```
Processing the results requires an additional if statement to determine whether `$1` and `$2` or `$3` and `$4` contain the goodies. It would be easier if we could use group numbers 1 and 2 in second alternative as well, and this is exactly what the parenthesized construct `(?|...)`, set around an alternative achieves. Here is an extended version of the previous pattern:
```
if($time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/){
print "hour=$1 minute=$2 zone=$3\n";
}
```
Within the alternative numbering group, group numbers start at the same position for each alternative. After the group, numbering continues with one higher than the maximum reached across all the alternatives.
###
Position information
In addition to what was matched, Perl also provides the positions of what was matched as contents of the `@-` and `@+` arrays. `$-[0]` is the position of the start of the entire match and `$+[0]` is the position of the end. Similarly, `$-[n]` is the position of the start of the `$n` match and `$+[n]` is the position of the end. If `$n` is undefined, so are `$-[n]` and `$+[n]`. Then this code
```
$x = "Mmm...donut, thought Homer";
$x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
foreach $exp (1..$#-) {
no strict 'refs';
print "Match $exp: '$$exp' at position ($-[$exp],$+[$exp])\n";
}
```
prints
```
Match 1: 'Mmm' at position (0,3)
Match 2: 'donut' at position (6,11)
```
Even if there are no groupings in a regexp, it is still possible to find out what exactly matched in a string. If you use them, Perl will set `$`` to the part of the string before the match, will set `$&` to the part of the string that matched, and will set `$'` to the part of the string after the match. An example:
```
$x = "the cat caught the mouse";
$x =~ /cat/; # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
$x =~ /the/; # $` = '', $& = 'the', $' = ' cat caught the mouse'
```
In the second match, `$`` equals `''` because the regexp matched at the first character position in the string and stopped; it never saw the second "the".
If your code is to run on Perl versions earlier than 5.20, it is worthwhile to note that using `$`` and `$'` slows down regexp matching quite a bit, while `$&` slows it down to a lesser extent, because if they are used in one regexp in a program, they are generated for *all* regexps in the program. So if raw performance is a goal of your application, they should be avoided. If you need to extract the corresponding substrings, use `@-` and `@+` instead:
```
$` is the same as substr( $x, 0, $-[0] )
$& is the same as substr( $x, $-[0], $+[0]-$-[0] )
$' is the same as substr( $x, $+[0] )
```
As of Perl 5.10, the `${^PREMATCH}`, `${^MATCH}` and `${^POSTMATCH}` variables may be used. These are only set if the `/p` modifier is present. Consequently they do not penalize the rest of the program. In Perl 5.20, `${^PREMATCH}`, `${^MATCH}` and `${^POSTMATCH}` are available whether the `/p` has been used or not (the modifier is ignored), and `$``, `$'` and `$&` do not cause any speed difference.
###
Non-capturing groupings
A group that is required to bundle a set of alternatives may or may not be useful as a capturing group. If it isn't, it just creates a superfluous addition to the set of available capture group values, inside as well as outside the regexp. Non-capturing groupings, denoted by `(?:regexp)`, still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time. Both capturing and non-capturing groupings are allowed to co-exist in the same regexp. Because there is no extraction, non-capturing groupings are faster than capturing groupings. Non-capturing groupings are also handy for choosing exactly which parts of a regexp are to be extracted to matching variables:
```
# match a number, $1-$4 are set, but we only want $1
/([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
# match a number faster , only $1 is set
/([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
# match a number, get $1 = whole number, $2 = exponent
/([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
```
Non-capturing groupings are also useful for removing nuisance elements gathered from a split operation where parentheses are required for some reason:
```
$x = '12aba34ba5';
@num = split /(a|b)+/, $x; # @num = ('12','a','34','a','5')
@num = split /(?:a|b)+/, $x; # @num = ('12','34','5')
```
In Perl 5.22 and later, all groups within a regexp can be set to non-capturing by using the new `/n` flag:
```
"hello" =~ /(hi|hello)/n; # $1 is not set!
```
See ["n" in perlre](perlre#n) for more information.
###
Matching repetitions
The examples in the previous section display an annoying weakness. We were only matching 3-letter words, or chunks of words of 4 letters or less. We'd like to be able to match words or, more generally, strings of any length, without writing out tedious alternatives like `\w\w\w\w|\w\w\w|\w\w|\w`.
This is exactly the problem the *quantifier* metacharacters `'?'`, `'*'`, `'+'`, and `{}` were created for. They allow us to delimit the number of repeats for a portion of a regexp we consider to be a match. Quantifiers are put immediately after the character, character class, or grouping that we want to specify. They have the following meanings:
* `a?` means: match `'a'` 1 or 0 times
* `a*` means: match `'a'` 0 or more times, *i.e.*, any number of times
* `a+` means: match `'a'` 1 or more times, *i.e.*, at least once
* `a{n,m}` means: match at least `n` times, but not more than `m` times.
* `a{n,}` means: match at least `n` or more times
* `a{,n}` means: match at most `n` times, or fewer
* `a{n}` means: match exactly `n` times
If you like, you can add blanks (tab or space characters) within the braces, but adjacent to them, and/or next to the comma (if any).
Here are some examples:
```
/[a-z]+\s+\d*/; # match a lowercase word, at least one space, and
# any number of digits
/(\w+)\s+\g1/; # match doubled words of arbitrary length
/y(es)?/i; # matches 'y', 'Y', or a case-insensitive 'yes'
$year =~ /^\d{2,4}$/; # make sure year is at least 2 but not more
# than 4 digits
$year =~ /^\d{ 2, 4 }$/; # Same; for those who like wide open
# spaces.
$year =~ /^\d{2, 4}$/; # Same.
$year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3-digit dates
$year =~ /^\d{2}(\d{2})?$/; # same thing written differently.
# However, this captures the last two
# digits in $1 and the other does not.
% simple_grep '^(\w+)\g1$' /usr/dict/words # isn't this easier?
beriberi
booboo
coco
mama
murmur
papa
```
For all of these quantifiers, Perl will try to match as much of the string as possible, while still allowing the regexp to succeed. Thus with `/a?.../`, Perl will first try to match the regexp with the `'a'` present; if that fails, Perl will try to match the regexp without the `'a'` present. For the quantifier `'*'`, we get the following:
```
$x = "the cat in the hat";
$x =~ /^(.*)(cat)(.*)$/; # matches,
# $1 = 'the '
# $2 = 'cat'
# $3 = ' in the hat'
```
Which is what we might expect, the match finds the only `cat` in the string and locks onto it. Consider, however, this regexp:
```
$x =~ /^(.*)(at)(.*)$/; # matches,
# $1 = 'the cat in the h'
# $2 = 'at'
# $3 = '' (0 characters match)
```
One might initially guess that Perl would find the `at` in `cat` and stop there, but that wouldn't give the longest possible string to the first quantifier `.*`. Instead, the first quantifier `.*` grabs as much of the string as possible while still having the regexp match. In this example, that means having the `at` sequence with the final `at` in the string. The other important principle illustrated here is that, when there are two or more elements in a regexp, the *leftmost* quantifier, if there is one, gets to grab as much of the string as possible, leaving the rest of the regexp to fight over scraps. Thus in our example, the first quantifier `.*` grabs most of the string, while the second quantifier `.*` gets the empty string. Quantifiers that grab as much of the string as possible are called *maximal match* or *greedy* quantifiers.
When a regexp can match a string in several different ways, we can use the principles above to predict which way the regexp will match:
* Principle 0: Taken as a whole, any regexp will be matched at the earliest possible position in the string.
* Principle 1: In an alternation `a|b|c...`, the leftmost alternative that allows a match for the whole regexp will be the one used.
* Principle 2: The maximal matching quantifiers `'?'`, `'*'`, `'+'` and `{n,m}` will in general match as much of the string as possible while still allowing the whole regexp to match.
* Principle 3: If there are two or more elements in a regexp, the leftmost greedy quantifier, if any, will match as much of the string as possible while still allowing the whole regexp to match. The next leftmost greedy quantifier, if any, will try to match as much of the string remaining available to it as possible, while still allowing the whole regexp to match. And so on, until all the regexp elements are satisfied.
As we have seen above, Principle 0 overrides the others. The regexp will be matched as early as possible, with the other principles determining how the regexp matches at that earliest character position.
Here is an example of these principles in action:
```
$x = "The programming republic of Perl";
$x =~ /^(.+)(e|r)(.*)$/; # matches,
# $1 = 'The programming republic of Pe'
# $2 = 'r'
# $3 = 'l'
```
This regexp matches at the earliest string position, `'T'`. One might think that `'e'`, being leftmost in the alternation, would be matched, but `'r'` produces the longest string in the first quantifier.
```
$x =~ /(m{1,2})(.*)$/; # matches,
# $1 = 'mm'
# $2 = 'ing republic of Perl'
```
Here, The earliest possible match is at the first `'m'` in `programming`. `m{1,2}` is the first quantifier, so it gets to match a maximal `mm`.
```
$x =~ /.*(m{1,2})(.*)$/; # matches,
# $1 = 'm'
# $2 = 'ing republic of Perl'
```
Here, the regexp matches at the start of the string. The first quantifier `.*` grabs as much as possible, leaving just a single `'m'` for the second quantifier `m{1,2}`.
```
$x =~ /(.?)(m{1,2})(.*)$/; # matches,
# $1 = 'a'
# $2 = 'mm'
# $3 = 'ing republic of Perl'
```
Here, `.?` eats its maximal one character at the earliest possible position in the string, `'a'` in `programming`, leaving `m{1,2}` the opportunity to match both `'m'`'s. Finally,
```
"aXXXb" =~ /(X*)/; # matches with $1 = ''
```
because it can match zero copies of `'X'` at the beginning of the string. If you definitely want to match at least one `'X'`, use `X+`, not `X*`.
Sometimes greed is not good. At times, we would like quantifiers to match a *minimal* piece of string, rather than a maximal piece. For this purpose, Larry Wall created the *minimal match* or *non-greedy* quantifiers `??`, `*?`, `+?`, and `{}?`. These are the usual quantifiers with a `'?'` appended to them. They have the following meanings:
* `a??` means: match `'a'` 0 or 1 times. Try 0 first, then 1.
* `a*?` means: match `'a'` 0 or more times, *i.e.*, any number of times, but as few times as possible
* `a+?` means: match `'a'` 1 or more times, *i.e.*, at least once, but as few times as possible
* `a{n,m}?` means: match at least `n` times, not more than `m` times, as few times as possible
* `a{n,}?` means: match at least `n` times, but as few times as possible
* `a{,n}?` means: match at most `n` times, but as few times as possible
* `a{n}?` means: match exactly `n` times. Because we match exactly `n` times, `a{n}?` is equivalent to `a{n}` and is just there for notational consistency.
Let's look at the example above, but with minimal quantifiers:
```
$x = "The programming republic of Perl";
$x =~ /^(.+?)(e|r)(.*)$/; # matches,
# $1 = 'Th'
# $2 = 'e'
# $3 = ' programming republic of Perl'
```
The minimal string that will allow both the start of the string `'^'` and the alternation to match is `Th`, with the alternation `e|r` matching `'e'`. The second quantifier `.*` is free to gobble up the rest of the string.
```
$x =~ /(m{1,2}?)(.*?)$/; # matches,
# $1 = 'm'
# $2 = 'ming republic of Perl'
```
The first string position that this regexp can match is at the first `'m'` in `programming`. At this position, the minimal `m{1,2}?` matches just one `'m'`. Although the second quantifier `.*?` would prefer to match no characters, it is constrained by the end-of-string anchor `'$'` to match the rest of the string.
```
$x =~ /(.*?)(m{1,2}?)(.*)$/; # matches,
# $1 = 'The progra'
# $2 = 'm'
# $3 = 'ming republic of Perl'
```
In this regexp, you might expect the first minimal quantifier `.*?` to match the empty string, because it is not constrained by a `'^'` anchor to match the beginning of the word. Principle 0 applies here, however. Because it is possible for the whole regexp to match at the start of the string, it *will* match at the start of the string. Thus the first quantifier has to match everything up to the first `'m'`. The second minimal quantifier matches just one `'m'` and the third quantifier matches the rest of the string.
```
$x =~ /(.??)(m{1,2})(.*)$/; # matches,
# $1 = 'a'
# $2 = 'mm'
# $3 = 'ing republic of Perl'
```
Just as in the previous regexp, the first quantifier `.??` can match earliest at position `'a'`, so it does. The second quantifier is greedy, so it matches `mm`, and the third matches the rest of the string.
We can modify principle 3 above to take into account non-greedy quantifiers:
* Principle 3: If there are two or more elements in a regexp, the leftmost greedy (non-greedy) quantifier, if any, will match as much (little) of the string as possible while still allowing the whole regexp to match. The next leftmost greedy (non-greedy) quantifier, if any, will try to match as much (little) of the string remaining available to it as possible, while still allowing the whole regexp to match. And so on, until all the regexp elements are satisfied.
Just like alternation, quantifiers are also susceptible to backtracking. Here is a step-by-step analysis of the example
```
$x = "the cat in the hat";
$x =~ /^(.*)(at)(.*)$/; # matches,
# $1 = 'the cat in the h'
# $2 = 'at'
# $3 = '' (0 matches)
```
0. Start with the first letter in the string `'t'`.
1. The first quantifier `'.*'` starts out by matching the whole string "`the cat in the hat`".
2. `'a'` in the regexp element `'at'` doesn't match the end of the string. Backtrack one character.
3. `'a'` in the regexp element `'at'` still doesn't match the last letter of the string `'t'`, so backtrack one more character.
4. Now we can match the `'a'` and the `'t'`.
5. Move on to the third element `'.*'`. Since we are at the end of the string and `'.*'` can match 0 times, assign it the empty string.
6. We are done! Most of the time, all this moving forward and backtracking happens quickly and searching is fast. There are some pathological regexps, however, whose execution time exponentially grows with the size of the string. A typical structure that blows up in your face is of the form
```
/(a|b+)*/;
```
The problem is the nested indeterminate quantifiers. There are many different ways of partitioning a string of length n between the `'+'` and `'*'`: one repetition with `b+` of length n, two repetitions with the first `b+` length k and the second with length n-k, m repetitions whose bits add up to length n, *etc*. In fact there are an exponential number of ways to partition a string as a function of its length. A regexp may get lucky and match early in the process, but if there is no match, Perl will try *every* possibility before giving up. So be careful with nested `'*'`'s, `{n,m}`'s, and `'+'`'s. The book *Mastering Regular Expressions* by Jeffrey Friedl gives a wonderful discussion of this and other efficiency issues.
###
Possessive quantifiers
Backtracking during the relentless search for a match may be a waste of time, particularly when the match is bound to fail. Consider the simple pattern
```
/^\w+\s+\w+$/; # a word, spaces, a word
```
Whenever this is applied to a string which doesn't quite meet the pattern's expectations such as `"abc "` or `"abc def "`, the regexp engine will backtrack, approximately once for each character in the string. But we know that there is no way around taking *all* of the initial word characters to match the first repetition, that *all* spaces must be eaten by the middle part, and the same goes for the second word.
With the introduction of the *possessive quantifiers* in Perl 5.10, we have a way of instructing the regexp engine not to backtrack, with the usual quantifiers with a `'+'` appended to them. This makes them greedy as well as stingy; once they succeed they won't give anything back to permit another solution. They have the following meanings:
* `a{n,m}+` means: match at least `n` times, not more than `m` times, as many times as possible, and don't give anything up. `a?+` is short for `a{0,1}+`
* `a{n,}+` means: match at least `n` times, but as many times as possible, and don't give anything up. `a++` is short for `a{1,}+`.
* `a{,n}+` means: match as many times as possible up to at most `n` times, and don't give anything up. `a*+` is short for `a{0,}+`.
* `a{n}+` means: match exactly `n` times. It is just there for notational consistency.
These possessive quantifiers represent a special case of a more general concept, the *independent subexpression*, see below.
As an example where a possessive quantifier is suitable we consider matching a quoted string, as it appears in several programming languages. The backslash is used as an escape character that indicates that the next character is to be taken literally, as another character for the string. Therefore, after the opening quote, we expect a (possibly empty) sequence of alternatives: either some character except an unescaped quote or backslash or an escaped character.
```
/"(?:[^"\\]++|\\.)*+"/;
```
###
Building a regexp
At this point, we have all the basic regexp concepts covered, so let's give a more involved example of a regular expression. We will build a regexp that matches numbers.
The first task in building a regexp is to decide what we want to match and what we want to exclude. In our case, we want to match both integers and floating point numbers and we want to reject any string that isn't a number.
The next task is to break the problem down into smaller problems that are easily converted into a regexp.
The simplest case is integers. These consist of a sequence of digits, with an optional sign in front. The digits we can represent with `\d+` and the sign can be matched with `[+-]`. Thus the integer regexp is
```
/[+-]?\d+/; # matches integers
```
A floating point number potentially has a sign, an integral part, a decimal point, a fractional part, and an exponent. One or more of these parts is optional, so we need to check out the different possibilities. Floating point numbers which are in proper form include 123., 0.345, .34, -1e6, and 25.4E-72. As with integers, the sign out front is completely optional and can be matched by `[+-]?`. We can see that if there is no exponent, floating point numbers must have a decimal point, otherwise they are integers. We might be tempted to model these with `\d*\.\d*`, but this would also match just a single decimal point, which is not a number. So the three cases of floating point number without exponent are
```
/[+-]?\d+\./; # 1., 321., etc.
/[+-]?\.\d+/; # .1, .234, etc.
/[+-]?\d+\.\d+/; # 1.0, 30.56, etc.
```
These can be combined into a single regexp with a three-way alternation:
```
/[+-]?(\d+\.\d+|\d+\.|\.\d+)/; # floating point, no exponent
```
In this alternation, it is important to put `'\d+\.\d+'` before `'\d+\.'`. If `'\d+\.'` were first, the regexp would happily match that and ignore the fractional part of the number.
Now consider floating point numbers with exponents. The key observation here is that *both* integers and numbers with decimal points are allowed in front of an exponent. Then exponents, like the overall sign, are independent of whether we are matching numbers with or without decimal points, and can be "decoupled" from the mantissa. The overall form of the regexp now becomes clear:
```
/^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
```
The exponent is an `'e'` or `'E'`, followed by an integer. So the exponent regexp is
```
/[eE][+-]?\d+/; # exponent
```
Putting all the parts together, we get a regexp that matches numbers:
```
/^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/; # Ta da!
```
Long regexps like this may impress your friends, but can be hard to decipher. In complex situations like this, the `/x` modifier for a match is invaluable. It allows one to put nearly arbitrary whitespace and comments into a regexp without affecting their meaning. Using it, we can rewrite our "extended" regexp in the more pleasing form
```
/^
[+-]? # first, match an optional sign
( # then match integers or f.p. mantissas:
\d+\.\d+ # mantissa of the form a.b
|\d+\. # mantissa of the form a.
|\.\d+ # mantissa of the form .b
|\d+ # integer of the form a
)
( [eE] [+-]? \d+ )? # finally, optionally match an exponent
$/x;
```
If whitespace is mostly irrelevant, how does one include space characters in an extended regexp? The answer is to backslash it `'\ '` or put it in a character class `[ ]`. The same thing goes for pound signs: use `\#` or `[#]`. For instance, Perl allows a space between the sign and the mantissa or integer, and we could add this to our regexp as follows:
```
/^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+\.\d+ # mantissa of the form a.b
|\d+\. # mantissa of the form a.
|\.\d+ # mantissa of the form .b
|\d+ # integer of the form a
)
( [eE] [+-]? \d+ )? # finally, optionally match an exponent
$/x;
```
In this form, it is easier to see a way to simplify the alternation. Alternatives 1, 2, and 4 all start with `\d+`, so it could be factored out:
```
/^
[+-]?\ * # first, match an optional sign
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
(
\.\d* # mantissa of the form a.b or a.
)? # ? takes care of integers of the form a
|\.\d+ # mantissa of the form .b
)
( [eE] [+-]? \d+ )? # finally, optionally match an exponent
$/x;
```
Starting in Perl v5.26, specifying `/xx` changes the square-bracketed portions of a pattern to ignore tabs and space characters unless they are escaped by preceding them with a backslash. So, we could write
```
/^
[ + - ]?\ * # first, match an optional sign
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
(
\.\d* # mantissa of the form a.b or a.
)? # ? takes care of integers of the form a
|\.\d+ # mantissa of the form .b
)
( [ e E ] [ + - ]? \d+ )? # finally, optionally match an exponent
$/xx;
```
This doesn't really improve the legibility of this example, but it's available in case you want it. Squashing the pattern down to the compact form, we have
```
/^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
```
This is our final regexp. To recap, we built a regexp by
* specifying the task in detail,
* breaking down the problem into smaller parts,
* translating the small parts into regexps,
* combining the regexps,
* and optimizing the final combined regexp.
These are also the typical steps involved in writing a computer program. This makes perfect sense, because regular expressions are essentially programs written in a little computer language that specifies patterns.
###
Using regular expressions in Perl
The last topic of Part 1 briefly covers how regexps are used in Perl programs. Where do they fit into Perl syntax?
We have already introduced the matching operator in its default `/regexp/` and arbitrary delimiter `m!regexp!` forms. We have used the binding operator `=~` and its negation `!~` to test for string matches. Associated with the matching operator, we have discussed the single line `/s`, multi-line `/m`, case-insensitive `/i` and extended `/x` modifiers. There are a few more things you might want to know about matching operators.
####
Prohibiting substitution
If you change `$pattern` after the first substitution happens, Perl will ignore it. If you don't want any substitutions at all, use the special delimiter `m''`:
```
@pattern = ('Seuss');
while (<>) {
print if m'@pattern'; # matches literal '@pattern', not 'Seuss'
}
```
Similar to strings, `m''` acts like apostrophes on a regexp; all other `'m'` delimiters act like quotes. If the regexp evaluates to the empty string, the regexp in the *last successful match* is used instead. So we have
```
"dog" =~ /d/; # 'd' matches
"dogbert" =~ //; # this matches the 'd' regexp used before
```
####
Global matching
The final two modifiers we will discuss here, `/g` and `/c`, concern multiple matches. The modifier `/g` stands for global matching and allows the matching operator to match within a string as many times as possible. In scalar context, successive invocations against a string will have `/g` jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the `pos()` function.
The use of `/g` is shown in the following example. Suppose we have a string that consists of words separated by spaces. If we know how many words there are in advance, we could extract the words using groupings:
```
$x = "cat dog house"; # 3 words
$x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
# $1 = 'cat'
# $2 = 'dog'
# $3 = 'house'
```
But what if we had an indeterminate number of words? This is the sort of task `/g` was made for. To extract all words, form the simple regexp `(\w+)` and loop over all matches with `/(\w+)/g`:
```
while ($x =~ /(\w+)/g) {
print "Word is $1, ends at position ", pos $x, "\n";
}
```
prints
```
Word is cat, ends at position 3
Word is dog, ends at position 7
Word is house, ends at position 13
```
A failed match or changing the target string resets the position. If you don't want the position reset after failure to match, add the `/c`, as in `/regexp/gc`. The current position in the string is associated with the string, not the regexp. This means that different strings have different positions and their respective positions can be set or read independently.
In list context, `/g` returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regexp. So if we wanted just the words, we could use
```
@words = ($x =~ /(\w+)/g); # matches,
# $words[0] = 'cat'
# $words[1] = 'dog'
# $words[2] = 'house'
```
Closely associated with the `/g` modifier is the `\G` anchor. The `\G` anchor matches at the point where the previous `/g` match left off. `\G` allows us to easily do context-sensitive matching:
```
$metric = 1; # use metric units
...
$x = <FILE>; # read in measurement
$x =~ /^([+-]?\d+)\s*/g; # get magnitude
$weight = $1;
if ($metric) { # error checking
print "Units error!" unless $x =~ /\Gkg\./g;
}
else {
print "Units error!" unless $x =~ /\Glbs\./g;
}
$x =~ /\G\s+(widget|sprocket)/g; # continue processing
```
The combination of `/g` and `\G` allows us to process the string a bit at a time and use arbitrary Perl logic to decide what to do next. Currently, the `\G` anchor is only fully supported when used to anchor to the start of the pattern.
`\G` is also invaluable in processing fixed-length records with regexps. Suppose we have a snippet of coding region DNA, encoded as base pair letters `ATCGTTGAAT...` and we want to find all the stop codons `TGA`. In a coding region, codons are 3-letter sequences, so we can think of the DNA snippet as a sequence of 3-letter records. The naive regexp
```
# expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
$dna = "ATCGTTGAATGCAAATGACATGAC";
$dna =~ /TGA/;
```
doesn't work; it may match a `TGA`, but there is no guarantee that the match is aligned with codon boundaries, *e.g.*, the substring `GTT GAA` gives a match. A better solution is
```
while ($dna =~ /(\w\w\w)*?TGA/g) { # note the minimal *?
print "Got a TGA stop codon at position ", pos $dna, "\n";
}
```
which prints
```
Got a TGA stop codon at position 18
Got a TGA stop codon at position 23
```
Position 18 is good, but position 23 is bogus. What happened?
The answer is that our regexp works well until we get past the last real match. Then the regexp will fail to match a synchronized `TGA` and start stepping ahead one character position at a time, not what we want. The solution is to use `\G` to anchor the match to the codon alignment:
```
while ($dna =~ /\G(\w\w\w)*?TGA/g) {
print "Got a TGA stop codon at position ", pos $dna, "\n";
}
```
This prints
```
Got a TGA stop codon at position 18
```
which is the correct answer. This example illustrates that it is important not only to match what is desired, but to reject what is not desired.
(There are other regexp modifiers that are available, such as `/o`, but their specialized uses are beyond the scope of this introduction. )
####
Search and replace
Regular expressions also play a big role in *search and replace* operations in Perl. Search and replace is accomplished with the `s///` operator. The general form is `s/regexp/replacement/modifiers`, with everything we know about regexps and modifiers applying in this case as well. The *replacement* is a Perl double-quoted string that replaces in the string whatever is matched with the `regexp`. The operator `=~` is also used here to associate a string with `s///`. If matching against `$_`, the `$_ =~` can be dropped. If there is a match, `s///` returns the number of substitutions made; otherwise it returns false. Here are a few examples:
```
$x = "Time to feed the cat!";
$x =~ s/cat/hacker/; # $x contains "Time to feed the hacker!"
if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
$more_insistent = 1;
}
$y = "'quoted words'";
$y =~ s/^'(.*)'$/$1/; # strip single quotes,
# $y contains "quoted words"
```
In the last example, the whole string was matched, but only the part inside the single quotes was grouped. With the `s///` operator, the matched variables `$1`, `$2`, *etc*. are immediately available for use in the replacement expression, so we use `$1` to replace the quoted string with just what was quoted. With the global modifier, `s///g` will search and replace all occurrences of the regexp in the string:
```
$x = "I batted 4 for 4";
$x =~ s/4/four/; # doesn't do it all:
# $x contains "I batted four for 4"
$x = "I batted 4 for 4";
$x =~ s/4/four/g; # does it all:
# $x contains "I batted four for four"
```
If you prefer "regex" over "regexp" in this tutorial, you could use the following program to replace it:
```
% cat > simple_replace
#!/usr/bin/perl
$regexp = shift;
$replacement = shift;
while (<>) {
s/$regexp/$replacement/g;
print;
}
^D
% simple_replace regexp regex perlretut.pod
```
In `simple_replace` we used the `s///g` modifier to replace all occurrences of the regexp on each line. (Even though the regular expression appears in a loop, Perl is smart enough to compile it only once.) As with `simple_grep`, both the `print` and the `s/$regexp/$replacement/g` use `$_` implicitly.
If you don't want `s///` to change your original variable you can use the non-destructive substitute modifier, `s///r`. This changes the behavior so that `s///r` returns the final substituted string (instead of the number of substitutions):
```
$x = "I like dogs.";
$y = $x =~ s/dogs/cats/r;
print "$x $y\n";
```
That example will print "I like dogs. I like cats". Notice the original `$x` variable has not been affected. The overall result of the substitution is instead stored in `$y`. If the substitution doesn't affect anything then the original string is returned:
```
$x = "I like dogs.";
$y = $x =~ s/elephants/cougars/r;
print "$x $y\n"; # prints "I like dogs. I like dogs."
```
One other interesting thing that the `s///r` flag allows is chaining substitutions:
```
$x = "Cats are great.";
print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
s/Frogs/Hedgehogs/r, "\n";
# prints "Hedgehogs are great."
```
A modifier available specifically to search and replace is the `s///e` evaluation modifier. `s///e` treats the replacement text as Perl code, rather than a double-quoted string. The value that the code returns is substituted for the matched substring. `s///e` is useful if you need to do a bit of computation in the process of replacing text. This example counts character frequencies in a line:
```
$x = "Bill the cat";
$x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
print "frequency of '$_' is $chars{$_}\n"
foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
```
This prints
```
frequency of ' ' is 2
frequency of 't' is 2
frequency of 'l' is 2
frequency of 'B' is 1
frequency of 'c' is 1
frequency of 'e' is 1
frequency of 'h' is 1
frequency of 'i' is 1
frequency of 'a' is 1
```
As with the match `m//` operator, `s///` can use other delimiters, such as `s!!!` and `s{}{}`, and even `s{}//`. If single quotes are used `s'''`, then the regexp and replacement are treated as single-quoted strings and there are no variable substitutions. `s///` in list context returns the same thing as in scalar context, *i.e.*, the number of matches.
####
The split function
The `split()` function is another place where a regexp is used. `split /regexp/, string, limit` separates the `string` operand into a list of substrings and returns that list. The regexp must be designed to match whatever constitutes the separators for the desired substrings. The `limit`, if present, constrains splitting into no more than `limit` number of strings. For example, to split a string into words, use
```
$x = "Calvin and Hobbes";
@words = split /\s+/, $x; # $word[0] = 'Calvin'
# $word[1] = 'and'
# $word[2] = 'Hobbes'
```
If the empty regexp `//` is used, the regexp always matches and the string is split into individual characters. If the regexp has groupings, then the resulting list contains the matched substrings from the groupings as well. For instance,
```
$x = "/usr/bin/perl";
@dirs = split m!/!, $x; # $dirs[0] = ''
# $dirs[1] = 'usr'
# $dirs[2] = 'bin'
# $dirs[3] = 'perl'
@parts = split m!(/)!, $x; # $parts[0] = ''
# $parts[1] = '/'
# $parts[2] = 'usr'
# $parts[3] = '/'
# $parts[4] = 'bin'
# $parts[5] = '/'
# $parts[6] = 'perl'
```
Since the first character of `$x` matched the regexp, `split` prepended an empty initial element to the list.
If you have read this far, congratulations! You now have all the basic tools needed to use regular expressions to solve a wide range of text processing problems. If this is your first time through the tutorial, why not stop here and play around with regexps a while.... Part 2 concerns the more esoteric aspects of regular expressions and those concepts certainly aren't needed right at the start.
Part 2: Power tools
--------------------
OK, you know the basics of regexps and you want to know more. If matching regular expressions is analogous to a walk in the woods, then the tools discussed in Part 1 are analogous to topo maps and a compass, basic tools we use all the time. Most of the tools in part 2 are analogous to flare guns and satellite phones. They aren't used too often on a hike, but when we are stuck, they can be invaluable.
What follows are the more advanced, less used, or sometimes esoteric capabilities of Perl regexps. In Part 2, we will assume you are comfortable with the basics and concentrate on the advanced features.
###
More on characters, strings, and character classes
There are a number of escape sequences and character classes that we haven't covered yet.
There are several escape sequences that convert characters or strings between upper and lower case, and they are also available within patterns. `\l` and `\u` convert the next character to lower or upper case, respectively:
```
$x = "perl";
$string =~ /\u$x/; # matches 'Perl' in $string
$x = "M(rs?|s)\\."; # note the double backslash
$string =~ /\l$x/; # matches 'mr.', 'mrs.', and 'ms.',
```
A `\L` or `\U` indicates a lasting conversion of case, until terminated by `\E` or thrown over by another `\U` or `\L`:
```
$x = "This word is in lower case:\L SHOUT\E";
$x =~ /shout/; # matches
$x = "I STILL KEYPUNCH CARDS FOR MY 360";
$x =~ /\Ukeypunch/; # matches punch card string
```
If there is no `\E`, case is converted until the end of the string. The regexps `\L\u$word` or `\u\L$word` convert the first character of `$word` to uppercase and the rest of the characters to lowercase. (Beyond ASCII characters, it gets somewhat more complicated; `\u` actually performs *titlecase* mapping, which for most characters is the same as uppercase, but not for all; see <https://unicode.org/faq/casemap_charprop.html#4>.)
Control characters can be escaped with `\c`, so that a control-Z character would be matched with `\cZ`. The escape sequence `\Q`...`\E` quotes, or protects most non-alphabetic characters. For instance,
```
$x = "\QThat !^*&%~& cat!";
$x =~ /\Q!^*&%~&\E/; # check for rough language
```
It does not protect `'$'` or `'@'`, so that variables can still be substituted.
`\Q`, `\L`, `\l`, `\U`, `\u` and `\E` are actually part of double-quotish syntax, and not part of regexp syntax proper. They will work if they appear in a regular expression embedded directly in a program, but not when contained in a string that is interpolated in a pattern.
Perl regexps can handle more than just the standard ASCII character set. Perl supports *Unicode*, a standard for representing the alphabets from virtually all of the world's written languages, and a host of symbols. Perl's text strings are Unicode strings, so they can contain characters with a value (codepoint or character number) higher than 255.
What does this mean for regexps? Well, regexp users don't need to know much about Perl's internal representation of strings. But they do need to know 1) how to represent Unicode characters in a regexp and 2) that a matching operation will treat the string to be searched as a sequence of characters, not bytes. The answer to 1) is that Unicode characters greater than `chr(255)` are represented using the `\x{hex}` notation, because `\x`*XY* (without curly braces and *XY* are two hex digits) doesn't go further than 255. (Starting in Perl 5.14, if you're an octal fan, you can also use `\o{oct}`.)
```
/\x{263a}/; # match a Unicode smiley face :)
/\x{ 263a }/; # Same
```
**NOTE**: In Perl 5.6.0 it used to be that one needed to say `use utf8` to use any Unicode features. This is no longer the case: for almost all Unicode processing, the explicit `utf8` pragma is not needed. (The only case where it matters is if your Perl script is in Unicode and encoded in UTF-8, then an explicit `use utf8` is needed.)
Figuring out the hexadecimal sequence of a Unicode character you want or deciphering someone else's hexadecimal Unicode regexp is about as much fun as programming in machine code. So another way to specify Unicode characters is to use the *named character* escape sequence `\N{*name*}`. *name* is a name for the Unicode character, as specified in the Unicode standard. For instance, if we wanted to represent or match the astrological sign for the planet Mercury, we could use
```
$x = "abc\N{MERCURY}def";
$x =~ /\N{MERCURY}/; # matches
$x =~ /\N{ MERCURY }/; # Also matches
```
One can also use "short" names:
```
print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
print "\N{greek:Sigma} is an upper-case sigma.\n";
```
You can also restrict names to a certain alphabet by specifying the <charnames> pragma:
```
use charnames qw(greek);
print "\N{sigma} is Greek sigma\n";
```
An index of character names is available on-line from the Unicode Consortium, <https://www.unicode.org/charts/charindex.html>; explanatory material with links to other resources at <https://www.unicode.org/standard/where>.
Starting in Perl v5.32, an alternative to `\N{...}` for full names is available, and that is to say
```
/\p{Name=greek small letter sigma}/
```
The casing of the character name is irrelevant when used in `\p{}`, as are most spaces, underscores and hyphens. (A few outlier characters cause problems with ignoring all of them always. The details (which you can look up when you get more proficient, and if ever needed) are in <https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>).
The answer to requirement 2) is that a regexp (mostly) uses Unicode characters. The "mostly" is for messy backward compatibility reasons, but starting in Perl 5.14, any regexp compiled in the scope of a `use feature 'unicode_strings'` (which is automatically turned on within the scope of a `use v5.12` or higher) will turn that "mostly" into "always". If you want to handle Unicode properly, you should ensure that `'unicode_strings'` is turned on. Internally, this is encoded to bytes using either UTF-8 or a native 8 bit encoding, depending on the history of the string, but conceptually it is a sequence of characters, not bytes. See <perlunitut> for a tutorial about that.
Let us now discuss Unicode character classes, most usually called "character properties". These are represented by the `\p{*name*}` escape sequence. The negation of this is `\P{*name*}`. For example, to match lower and uppercase characters,
```
$x = "BOB";
$x =~ /^\p{IsUpper}/; # matches, uppercase char class
$x =~ /^\P{IsUpper}/; # doesn't match, char class sans uppercase
$x =~ /^\p{IsLower}/; # doesn't match, lowercase char class
$x =~ /^\P{IsLower}/; # matches, char class sans lowercase
```
(The "`Is`" is optional.)
There are many, many Unicode character properties. For the full list see <perluniprops>. Most of them have synonyms with shorter names, also listed there. Some synonyms are a single character. For these, you can drop the braces. For instance, `\pM` is the same thing as `\p{Mark}`, meaning things like accent marks.
The Unicode `\p{Script}` and `\p{Script_Extensions}` properties are used to categorize every Unicode character into the language script it is written in. For example, English, French, and a bunch of other European languages are written in the Latin script. But there is also the Greek script, the Thai script, the Katakana script, *etc*. (`Script` is an older, less advanced, form of `Script_Extensions`, retained only for backwards compatibility.) You can test whether a character is in a particular script with, for example `\p{Latin}`, `\p{Greek}`, or `\p{Katakana}`. To test if it isn't in the Balinese script, you would use `\P{Balinese}`. (These all use `Script_Extensions` under the hood, as that gives better results.)
What we have described so far is the single form of the `\p{...}` character classes. There is also a compound form which you may run into. These look like `\p{*name*=*value*}` or `\p{*name*:*value*}` (the equals sign and colon can be used interchangeably). These are more general than the single form, and in fact most of the single forms are just Perl-defined shortcuts for common compound forms. For example, the script examples in the previous paragraph could be written equivalently as `\p{Script_Extensions=Latin}`, `\p{Script_Extensions:Greek}`, `\p{script_extensions=katakana}`, and `\P{script_extensions=balinese}` (case is irrelevant between the `{}` braces). You may never have to use the compound forms, but sometimes it is necessary, and their use can make your code easier to understand.
`\X` is an abbreviation for a character class that comprises a Unicode *extended grapheme cluster*. This represents a "logical character": what appears to be a single character, but may be represented internally by more than one. As an example, using the Unicode full names, *e.g.*, "A + COMBINING RING" is a grapheme cluster with base character "A" and combining character "COMBINING RING, which translates in Danish to "A" with the circle atop it, as in the word Ångstrom.
For the full and latest information about Unicode see the latest Unicode standard, or the Unicode Consortium's website <https://www.unicode.org>
As if all those classes weren't enough, Perl also defines POSIX-style character classes. These have the form `[:*name*:]`, with *name* the name of the POSIX class. The POSIX classes are `alpha`, `alnum`, `ascii`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`, `upper`, and `xdigit`, and two extensions, `word` (a Perl extension to match `\w`), and `blank` (a GNU extension). The `/a` modifier restricts these to matching just in the ASCII range; otherwise they can match the same as their corresponding Perl Unicode classes: `[:upper:]` is the same as `\p{IsUpper}`, *etc*. (There are some exceptions and gotchas with this; see <perlrecharclass> for a full discussion.) The `[:digit:]`, `[:word:]`, and `[:space:]` correspond to the familiar `\d`, `\w`, and `\s` character classes. To negate a POSIX class, put a `'^'` in front of the name, so that, *e.g.*, `[:^digit:]` corresponds to `\D` and, under Unicode, `\P{IsDigit}`. The Unicode and POSIX character classes can be used just like `\d`, with the exception that POSIX character classes can only be used inside of a character class:
```
/\s+[abc[:digit:]xyz]\s*/; # match a,b,c,x,y,z, or a digit
/^=item\s[[:digit:]]/; # match '=item',
# followed by a space and a digit
/\s+[abc\p{IsDigit}xyz]\s+/; # match a,b,c,x,y,z, or a digit
/^=item\s\p{IsDigit}/; # match '=item',
# followed by a space and a digit
```
Whew! That is all the rest of the characters and character classes.
###
Compiling and saving regular expressions
In Part 1 we mentioned that Perl compiles a regexp into a compact sequence of opcodes. Thus, a compiled regexp is a data structure that can be stored once and used again and again. The regexp quote `qr//` does exactly that: `qr/string/` compiles the `string` as a regexp and transforms the result into a form that can be assigned to a variable:
```
$reg = qr/foo+bar?/; # reg contains a compiled regexp
```
Then `$reg` can be used as a regexp:
```
$x = "fooooba";
$x =~ $reg; # matches, just like /foo+bar?/
$x =~ /$reg/; # same thing, alternate form
```
`$reg` can also be interpolated into a larger regexp:
```
$x =~ /(abc)?$reg/; # still matches
```
As with the matching operator, the regexp quote can use different delimiters, *e.g.*, `qr!!`, `qr{}` or `qr~~`. Apostrophes as delimiters (`qr''`) inhibit any interpolation.
Pre-compiled regexps are useful for creating dynamic matches that don't need to be recompiled each time they are encountered. Using pre-compiled regexps, we write a `grep_step` program which greps for a sequence of patterns, advancing to the next pattern as soon as one has been satisfied.
```
% cat > grep_step
#!/usr/bin/perl
# grep_step - match <number> regexps, one after the other
# usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
$number = shift;
$regexp[$_] = shift foreach (0..$number-1);
@compiled = map qr/$_/, @regexp;
while ($line = <>) {
if ($line =~ /$compiled[0]/) {
print $line;
shift @compiled;
last unless @compiled;
}
}
^D
% grep_step 3 shift print last grep_step
$number = shift;
print $line;
last unless @compiled;
```
Storing pre-compiled regexps in an array `@compiled` allows us to simply loop through the regexps without any recompilation, thus gaining flexibility without sacrificing speed.
###
Composing regular expressions at runtime
Backtracking is more efficient than repeated tries with different regular expressions. If there are several regular expressions and a match with any of them is acceptable, then it is possible to combine them into a set of alternatives. If the individual expressions are input data, this can be done by programming a join operation. We'll exploit this idea in an improved version of the `simple_grep` program: a program that matches multiple patterns:
```
% cat > multi_grep
#!/usr/bin/perl
# multi_grep - match any of <number> regexps
# usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
$number = shift;
$regexp[$_] = shift foreach (0..$number-1);
$pattern = join '|', @regexp;
while ($line = <>) {
print $line if $line =~ /$pattern/;
}
^D
% multi_grep 2 shift for multi_grep
$number = shift;
$regexp[$_] = shift foreach (0..$number-1);
```
Sometimes it is advantageous to construct a pattern from the *input* that is to be analyzed and use the permissible values on the left hand side of the matching operations. As an example for this somewhat paradoxical situation, let's assume that our input contains a command verb which should match one out of a set of available command verbs, with the additional twist that commands may be abbreviated as long as the given string is unique. The program below demonstrates the basic algorithm.
```
% cat > keymatch
#!/usr/bin/perl
$kwds = 'copy compare list print';
while( $cmd = <> ){
$cmd =~ s/^\s+|\s+$//g; # trim leading and trailing spaces
if( ( @matches = $kwds =~ /\b$cmd\w*/g ) == 1 ){
print "command: '@matches'\n";
} elsif( @matches == 0 ){
print "no such command: '$cmd'\n";
} else {
print "not unique: '$cmd' (could be one of: @matches)\n";
}
}
^D
% keymatch
li
command: 'list'
co
not unique: 'co' (could be one of: copy compare)
printer
no such command: 'printer'
```
Rather than trying to match the input against the keywords, we match the combined set of keywords against the input. The pattern matching operation `$kwds =~ /\b($cmd\w*)/g` does several things at the same time. It makes sure that the given command begins where a keyword begins (`\b`). It tolerates abbreviations due to the added `\w*`. It tells us the number of matches (`scalar @matches`) and all the keywords that were actually matched. You could hardly ask for more.
###
Embedding comments and modifiers in a regular expression
Starting with this section, we will be discussing Perl's set of *extended patterns*. These are extensions to the traditional regular expression syntax that provide powerful new tools for pattern matching. We have already seen extensions in the form of the minimal matching constructs `??`, `*?`, `+?`, `{n,m}?`, `{n,}?`, and `{,n}?`. Most of the extensions below have the form `(?char...)`, where the `char` is a character that determines the type of extension.
The first extension is an embedded comment `(?#text)`. This embeds a comment into the regular expression without affecting its meaning. The comment should not have any closing parentheses in the text. An example is
```
/(?# Match an integer:)[+-]?\d+/;
```
This style of commenting has been largely superseded by the raw, freeform commenting that is allowed with the `/x` modifier.
Most modifiers, such as `/i`, `/m`, `/s` and `/x` (or any combination thereof) can also be embedded in a regexp using `(?i)`, `(?m)`, `(?s)`, and `(?x)`. For instance,
```
/(?i)yes/; # match 'yes' case insensitively
/yes/i; # same thing
/(?x)( # freeform version of an integer regexp
[+-]? # match an optional sign
\d+ # match a sequence of digits
)
/x;
```
Embedded modifiers can have two important advantages over the usual modifiers. Embedded modifiers allow a custom set of modifiers for *each* regexp pattern. This is great for matching an array of regexps that must have different modifiers:
```
$pattern[0] = '(?i)doctor';
$pattern[1] = 'Johnson';
...
while (<>) {
foreach $patt (@pattern) {
print if /$patt/;
}
}
```
The second advantage is that embedded modifiers (except `/p`, which modifies the entire regexp) only affect the regexp inside the group the embedded modifier is contained in. So grouping can be used to localize the modifier's effects:
```
/Answer: ((?i)yes)/; # matches 'Answer: yes', 'Answer: YES', etc.
```
Embedded modifiers can also turn off any modifiers already present by using, *e.g.*, `(?-i)`. Modifiers can also be combined into a single expression, *e.g.*, `(?s-i)` turns on single line mode and turns off case insensitivity.
Embedded modifiers may also be added to a non-capturing grouping. `(?i-m:regexp)` is a non-capturing grouping that matches `regexp` case insensitively and turns off multi-line mode.
###
Looking ahead and looking behind
This section concerns the lookahead and lookbehind assertions. First, a little background.
In Perl regular expressions, most regexp elements "eat up" a certain amount of string when they match. For instance, the regexp element `[abc]` eats up one character of the string when it matches, in the sense that Perl moves to the next character position in the string after the match. There are some elements, however, that don't eat up characters (advance the character position) if they match. The examples we have seen so far are the anchors. The anchor `'^'` matches the beginning of the line, but doesn't eat any characters. Similarly, the word boundary anchor `\b` matches wherever a character matching `\w` is next to a character that doesn't, but it doesn't eat up any characters itself. Anchors are examples of *zero-width assertions*: zero-width, because they consume no characters, and assertions, because they test some property of the string. In the context of our walk in the woods analogy to regexp matching, most regexp elements move us along a trail, but anchors have us stop a moment and check our surroundings. If the local environment checks out, we can proceed forward. But if the local environment doesn't satisfy us, we must backtrack.
Checking the environment entails either looking ahead on the trail, looking behind, or both. `'^'` looks behind, to see that there are no characters before. `'$'` looks ahead, to see that there are no characters after. `\b` looks both ahead and behind, to see if the characters on either side differ in their "word-ness".
The lookahead and lookbehind assertions are generalizations of the anchor concept. Lookahead and lookbehind are zero-width assertions that let us specify which characters we want to test for. The lookahead assertion is denoted by `(?=regexp)` or (starting in 5.32, experimentally in 5.28) `(*pla:regexp)` or `(*positive_lookahead:regexp)`; and the lookbehind assertion is denoted by `(?<=fixed-regexp)` or (starting in 5.32, experimentally in 5.28) `(*plb:fixed-regexp)` or `(*positive_lookbehind:fixed-regexp)`. Some examples are
```
$x = "I catch the housecat 'Tom-cat' with catnip";
$x =~ /cat(*pla:\s)/; # matches 'cat' in 'housecat'
@catwords = ($x =~ /(?<=\s)cat\w+/g); # matches,
# $catwords[0] = 'catch'
# $catwords[1] = 'catnip'
$x =~ /\bcat\b/; # matches 'cat' in 'Tom-cat'
$x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
# middle of $x
```
Note that the parentheses in these are non-capturing, since these are zero-width assertions. Thus in the second regexp, the substrings captured are those of the whole regexp itself. Lookahead can match arbitrary regexps, but lookbehind prior to 5.30 `(?<=fixed-regexp)` only works for regexps of fixed width, *i.e.*, a fixed number of characters long. Thus `(?<=(ab|bc))` is fine, but `(?<=(ab)*)` prior to 5.30 is not.
The negated versions of the lookahead and lookbehind assertions are denoted by `(?!regexp)` and `(?<!fixed-regexp)` respectively. Or, starting in 5.32 (experimentally in 5.28), `(*nla:regexp)`, `(*negative_lookahead:regexp)`, `(*nlb:regexp)`, or `(*negative_lookbehind:regexp)`. They evaluate true if the regexps do *not* match:
```
$x = "foobar";
$x =~ /foo(?!bar)/; # doesn't match, 'bar' follows 'foo'
$x =~ /foo(?!baz)/; # matches, 'baz' doesn't follow 'foo'
$x =~ /(?<!\s)foo/; # matches, there is no \s before 'foo'
```
Here is an example where a string containing blank-separated words, numbers and single dashes is to be split into its components. Using `/\s+/` alone won't work, because spaces are not required between dashes, or a word or a dash. Additional places for a split are established by looking ahead and behind:
```
$str = "one two - --6-8";
@toks = split / \s+ # a run of spaces
| (?<=\S) (?=-) # any non-space followed by '-'
| (?<=-) (?=\S) # a '-' followed by any non-space
/x, $str; # @toks = qw(one two - - - 6 - 8)
```
###
Using independent subexpressions to prevent backtracking
*Independent subexpressions* (or atomic subexpressions) are regular expressions, in the context of a larger regular expression, that function independently of the larger regular expression. That is, they consume as much or as little of the string as they wish without regard for the ability of the larger regexp to match. Independent subexpressions are represented by `(?>regexp)` or (starting in 5.32, experimentally in 5.28) `(*atomic:regexp)`. We can illustrate their behavior by first considering an ordinary regexp:
```
$x = "ab";
$x =~ /a*ab/; # matches
```
This obviously matches, but in the process of matching, the subexpression `a*` first grabbed the `'a'`. Doing so, however, wouldn't allow the whole regexp to match, so after backtracking, `a*` eventually gave back the `'a'` and matched the empty string. Here, what `a*` matched was *dependent* on what the rest of the regexp matched.
Contrast that with an independent subexpression:
```
$x =~ /(?>a*)ab/; # doesn't match!
```
The independent subexpression `(?>a*)` doesn't care about the rest of the regexp, so it sees an `'a'` and grabs it. Then the rest of the regexp `ab` cannot match. Because `(?>a*)` is independent, there is no backtracking and the independent subexpression does not give up its `'a'`. Thus the match of the regexp as a whole fails. A similar behavior occurs with completely independent regexps:
```
$x = "ab";
$x =~ /a*/g; # matches, eats an 'a'
$x =~ /\Gab/g; # doesn't match, no 'a' available
```
Here `/g` and `\G` create a "tag team" handoff of the string from one regexp to the other. Regexps with an independent subexpression are much like this, with a handoff of the string to the independent subexpression, and a handoff of the string back to the enclosing regexp.
The ability of an independent subexpression to prevent backtracking can be quite useful. Suppose we want to match a non-empty string enclosed in parentheses up to two levels deep. Then the following regexp matches:
```
$x = "abc(de(fg)h"; # unbalanced parentheses
$x =~ /\( ( [ ^ () ]+ | \( [ ^ () ]* \) )+ \)/xx;
```
The regexp matches an open parenthesis, one or more copies of an alternation, and a close parenthesis. The alternation is two-way, with the first alternative `[^()]+` matching a substring with no parentheses and the second alternative `\([^()]*\)` matching a substring delimited by parentheses. The problem with this regexp is that it is pathological: it has nested indeterminate quantifiers of the form `(a+|b)+`. We discussed in Part 1 how nested quantifiers like this could take an exponentially long time to execute if no match were possible. To prevent the exponential blowup, we need to prevent useless backtracking at some point. This can be done by enclosing the inner quantifier as an independent subexpression:
```
$x =~ /\( ( (?> [ ^ () ]+ ) | \([ ^ () ]* \) )+ \)/xx;
```
Here, `(?>[^()]+)` breaks the degeneracy of string partitioning by gobbling up as much of the string as possible and keeping it. Then match failures fail much more quickly.
###
Conditional expressions
A *conditional expression* is a form of if-then-else statement that allows one to choose which patterns are to be matched, based on some condition. There are two types of conditional expression: `(?(*condition*)*yes-regexp*)` and `(?(condition)*yes-regexp*|*no-regexp*)`. `(?(*condition*)*yes-regexp*)` is like an `'if () {}'` statement in Perl. If the *condition* is true, the *yes-regexp* will be matched. If the *condition* is false, the *yes-regexp* will be skipped and Perl will move onto the next regexp element. The second form is like an `'if () {} else {}'` statement in Perl. If the *condition* is true, the *yes-regexp* will be matched, otherwise the *no-regexp* will be matched.
The *condition* can have several forms. The first form is simply an integer in parentheses `(*integer*)`. It is true if the corresponding backreference `\*integer*` matched earlier in the regexp. The same thing can be done with a name associated with a capture group, written as `(<*name*>)` or `('*name*')`. The second form is a bare zero-width assertion `(?...)`, either a lookahead, a lookbehind, or a code assertion (discussed in the next section). The third set of forms provides tests that return true if the expression is executed within a recursion (`(R)`) or is being called from some capturing group, referenced either by number (`(R1)`, `(R2)`,...) or by name (`(R&*name*)`).
The integer or name form of the `condition` allows us to choose, with more flexibility, what to match based on what matched earlier in the regexp. This searches for words of the form `"$x$x"` or `"$x$y$y$x"`:
```
% simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
beriberi
coco
couscous
deed
...
toot
toto
tutu
```
The lookbehind `condition` allows, along with backreferences, an earlier part of the match to influence a later part of the match. For instance,
```
/[ATGC]+(?(?<=AA)G|C)$/;
```
matches a DNA sequence such that it either ends in `AAG`, or some other base pair combination and `'C'`. Note that the form is `(?(?<=AA)G|C)` and not `(?((?<=AA))G|C)`; for the lookahead, lookbehind or code assertions, the parentheses around the conditional are not needed.
###
Defining named patterns
Some regular expressions use identical subpatterns in several places. Starting with Perl 5.10, it is possible to define named subpatterns in a section of the pattern so that they can be called up by name anywhere in the pattern. This syntactic pattern for this definition group is `(?(DEFINE)(?<*name*>*pattern*)...)`. An insertion of a named pattern is written as `(?&*name*)`.
The example below illustrates this feature using the pattern for floating point numbers that was presented earlier on. The three subpatterns that are used more than once are the optional sign, the digit sequence for an integer and the decimal fraction. The `DEFINE` group at the end of the pattern contains their definition. Notice that the decimal fraction pattern is the first place where we can reuse the integer pattern.
```
/^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
(?: [eE](?&osg)(?&int) )?
$
(?(DEFINE)
(?<osg>[-+]?) # optional sign
(?<int>\d++) # integer
(?<dec>\.(?&int)) # decimal fraction
)/x
```
###
Recursive patterns
This feature (introduced in Perl 5.10) significantly extends the power of Perl's pattern matching. By referring to some other capture group anywhere in the pattern with the construct `(?*group-ref*)`, the *pattern* within the referenced group is used as an independent subpattern in place of the group reference itself. Because the group reference may be contained *within* the group it refers to, it is now possible to apply pattern matching to tasks that hitherto required a recursive parser.
To illustrate this feature, we'll design a pattern that matches if a string contains a palindrome. (This is a word or a sentence that, while ignoring spaces, interpunctuation and case, reads the same backwards as forwards. We begin by observing that the empty string or a string containing just one word character is a palindrome. Otherwise it must have a word character up front and the same at its end, with another palindrome in between.
```
/(?: (\w) (?...Here be a palindrome...) \g{ -1 } | \w? )/x
```
Adding `\W*` at either end to eliminate what is to be ignored, we already have the full pattern:
```
my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
print "'$s' is a palindrome\n" if $s =~ /$pp/;
}
```
In `(?...)` both absolute and relative backreferences may be used. The entire pattern can be reinserted with `(?R)` or `(?0)`. If you prefer to name your groups, you can use `(?&*name*)` to recurse into that group.
###
A bit of magic: executing Perl code in a regular expression
Normally, regexps are a part of Perl expressions. *Code evaluation* expressions turn that around by allowing arbitrary Perl code to be a part of a regexp. A code evaluation expression is denoted `(?{*code*})`, with *code* a string of Perl statements.
Code expressions are zero-width assertions, and the value they return depends on their environment. There are two possibilities: either the code expression is used as a conditional in a conditional expression `(?(*condition*)...)`, or it is not. If the code expression is a conditional, the code is evaluated and the result (*i.e.*, the result of the last statement) is used to determine truth or falsehood. If the code expression is not used as a conditional, the assertion always evaluates true and the result is put into the special variable `$^R`. The variable `$^R` can then be used in code expressions later in the regexp. Here are some silly examples:
```
$x = "abcdef";
$x =~ /abc(?{print "Hi Mom!";})def/; # matches,
# prints 'Hi Mom!'
$x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
# no 'Hi Mom!'
```
Pay careful attention to the next example:
```
$x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
# no 'Hi Mom!'
# but why not?
```
At first glance, you'd think that it shouldn't print, because obviously the `ddd` isn't going to match the target string. But look at this example:
```
$x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
# but _does_ print
```
Hmm. What happened here? If you've been following along, you know that the above pattern should be effectively (almost) the same as the last one; enclosing the `'d'` in a character class isn't going to change what it matches. So why does the first not print while the second one does?
The answer lies in the optimizations the regexp engine makes. In the first case, all the engine sees are plain old characters (aside from the `?{}` construct). It's smart enough to realize that the string `'ddd'` doesn't occur in our target string before actually running the pattern through. But in the second case, we've tricked it into thinking that our pattern is more complicated. It takes a look, sees our character class, and decides that it will have to actually run the pattern to determine whether or not it matches, and in the process of running it hits the print statement before it discovers that we don't have a match.
To take a closer look at how the engine does optimizations, see the section ["Pragmas and debugging"](#Pragmas-and-debugging) below.
More fun with `?{}`:
```
$x =~ /(?{print "Hi Mom!";})/; # matches,
# prints 'Hi Mom!'
$x =~ /(?{$c = 1;})(?{print "$c";})/; # matches,
# prints '1'
$x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
# prints '1'
```
The bit of magic mentioned in the section title occurs when the regexp backtracks in the process of searching for a match. If the regexp backtracks over a code expression and if the variables used within are localized using `local`, the changes in the variables produced by the code expression are undone! Thus, if we wanted to count how many times a character got matched inside a group, we could use, *e.g.*,
```
$x = "aaaa";
$count = 0; # initialize 'a' count
$c = "bob"; # test if $c gets clobbered
$x =~ /(?{local $c = 0;}) # initialize count
( a # match 'a'
(?{local $c = $c + 1;}) # increment count
)* # do this any number of times,
aa # but match 'aa' at the end
(?{$count = $c;}) # copy local $c var into $count
/x;
print "'a' count is $count, \$c variable is '$c'\n";
```
This prints
```
'a' count is 2, $c variable is 'bob'
```
If we replace the `(?{local $c = $c + 1;})` with `(?{$c = $c + 1;})`, the variable changes are *not* undone during backtracking, and we get
```
'a' count is 4, $c variable is 'bob'
```
Note that only localized variable changes are undone. Other side effects of code expression execution are permanent. Thus
```
$x = "aaaa";
$x =~ /(a(?{print "Yow\n";}))*aa/;
```
produces
```
Yow
Yow
Yow
Yow
```
The result `$^R` is automatically localized, so that it will behave properly in the presence of backtracking.
This example uses a code expression in a conditional to match a definite article, either `'the'` in English or `'der|die|das'` in German:
```
$lang = 'DE'; # use German
...
$text = "das";
print "matched\n"
if $text =~ /(?(?{
$lang eq 'EN'; # is the language English?
})
the | # if so, then match 'the'
(der|die|das) # else, match 'der|die|das'
)
/xi;
```
Note that the syntax here is `(?(?{...})*yes-regexp*|*no-regexp*)`, not `(?((?{...}))*yes-regexp*|*no-regexp*)`. In other words, in the case of a code expression, we don't need the extra parentheses around the conditional.
If you try to use code expressions where the code text is contained within an interpolated variable, rather than appearing literally in the pattern, Perl may surprise you:
```
$bar = 5;
$pat = '(?{ 1 })';
/foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
/foo(?{ 1 })$bar/; # compiles ok, $bar interpolated
/foo${pat}bar/; # compile error!
$pat = qr/(?{ $foo = 1 })/; # precompile code regexp
/foo${pat}bar/; # compiles ok
```
If a regexp has a variable that interpolates a code expression, Perl treats the regexp as an error. If the code expression is precompiled into a variable, however, interpolating is ok. The question is, why is this an error?
The reason is that variable interpolation and code expressions together pose a security risk. The combination is dangerous because many programmers who write search engines often take user input and plug it directly into a regexp:
```
$regexp = <>; # read user-supplied regexp
$chomp $regexp; # get rid of possible newline
$text =~ /$regexp/; # search $text for the $regexp
```
If the `$regexp` variable contains a code expression, the user could then execute arbitrary Perl code. For instance, some joker could search for `system('rm -rf *');` to erase your files. In this sense, the combination of interpolation and code expressions *taints* your regexp. So by default, using both interpolation and code expressions in the same regexp is not allowed. If you're not concerned about malicious users, it is possible to bypass this security check by invoking `use re 'eval'`:
```
use re 'eval'; # throw caution out the door
$bar = 5;
$pat = '(?{ 1 })';
/foo${pat}bar/; # compiles ok
```
Another form of code expression is the *pattern code expression*. The pattern code expression is like a regular code expression, except that the result of the code evaluation is treated as a regular expression and matched immediately. A simple example is
```
$length = 5;
$char = 'a';
$x = 'aaaaabb';
$x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
```
This final example contains both ordinary and pattern code expressions. It detects whether a binary string `1101010010001...` has a Fibonacci spacing 0,1,1,2,3,5,... of the `'1'`'s:
```
$x = "1101010010001000001";
$z0 = ''; $z1 = '0'; # initial conditions
print "It is a Fibonacci sequence\n"
if $x =~ /^1 # match an initial '1'
(?:
((??{ $z0 })) # match some '0'
1 # and then a '1'
(?{ $z0 = $z1; $z1 .= $^N; })
)+ # repeat as needed
$ # that is all there is
/x;
printf "Largest sequence matched was %d\n", length($z1)-length($z0);
```
Remember that `$^N` is set to whatever was matched by the last completed capture group. This prints
```
It is a Fibonacci sequence
Largest sequence matched was 5
```
Ha! Try that with your garden variety regexp package...
Note that the variables `$z0` and `$z1` are not substituted when the regexp is compiled, as happens for ordinary variables outside a code expression. Rather, the whole code block is parsed as perl code at the same time as perl is compiling the code containing the literal regexp pattern.
This regexp without the `/x` modifier is
```
/^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
```
which shows that spaces are still possible in the code parts. Nevertheless, when working with code and conditional expressions, the extended form of regexps is almost necessary in creating and debugging regexps.
###
Backtracking control verbs
Perl 5.10 introduced a number of control verbs intended to provide detailed control over the backtracking process, by directly influencing the regexp engine and by providing monitoring techniques. See ["Special Backtracking Control Verbs" in perlre](perlre#Special-Backtracking-Control-Verbs) for a detailed description.
Below is just one example, illustrating the control verb `(*FAIL)`, which may be abbreviated as `(*F)`. If this is inserted in a regexp it will cause it to fail, just as it would at some mismatch between the pattern and the string. Processing of the regexp continues as it would after any "normal" failure, so that, for instance, the next position in the string or another alternative will be tried. As failing to match doesn't preserve capture groups or produce results, it may be necessary to use this in combination with embedded code.
```
%count = ();
"supercalifragilisticexpialidocious" =~
/([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
```
The pattern begins with a class matching a subset of letters. Whenever this matches, a statement like `$count{'a'}++;` is executed, incrementing the letter's counter. Then `(*FAIL)` does what it says, and the regexp engine proceeds according to the book: as long as the end of the string hasn't been reached, the position is advanced before looking for another vowel. Thus, match or no match makes no difference, and the regexp engine proceeds until the entire string has been inspected. (It's remarkable that an alternative solution using something like
```
$count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
```
is considerably slower.)
###
Pragmas and debugging
Speaking of debugging, there are several pragmas available to control and debug regexps in Perl. We have already encountered one pragma in the previous section, `use re 'eval';`, that allows variable interpolation and code expressions to coexist in a regexp. The other pragmas are
```
use re 'taint';
$tainted = <>;
@parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
```
The `taint` pragma causes any substrings from a match with a tainted variable to be tainted as well, if your perl supports tainting (see <perlsec>). This is not normally the case, as regexps are often used to extract the safe bits from a tainted variable. Use `taint` when you are not extracting safe bits, but are performing some other processing. Both `taint` and `eval` pragmas are lexically scoped, which means they are in effect only until the end of the block enclosing the pragmas.
```
use re '/m'; # or any other flags
$multiline_string =~ /^foo/; # /m is implied
```
The `re '/flags'` pragma (introduced in Perl 5.14) turns on the given regular expression flags until the end of the lexical scope. See ["'/flags' mode" in re](re#%27%2Fflags%27-mode) for more detail.
```
use re 'debug';
/^(.*)$/s; # output debugging info
use re 'debugcolor';
/^(.*)$/s; # output debugging info in living color
```
The global `debug` and `debugcolor` pragmas allow one to get detailed debugging info about regexp compilation and execution. `debugcolor` is the same as debug, except the debugging information is displayed in color on terminals that can display termcap color sequences. Here is example output:
```
% perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
Compiling REx 'a*b+c'
size 9 first at 1
1: STAR(4)
2: EXACT <a>(0)
4: PLUS(7)
5: EXACT <b>(0)
7: EXACT <c>(9)
9: END(0)
floating 'bc' at 0..2147483647 (checking floating) minlen 2
Guessing start of match, REx 'a*b+c' against 'abc'...
Found floating substr 'bc' at offset 1...
Guessed: match at offset 0
Matching REx 'a*b+c' against 'abc'
Setting an EVAL scope, savestack=3
0 <> <abc> | 1: STAR
EXACT <a> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
1 <a> <bc> | 4: PLUS
EXACT <b> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
2 <ab> <c> | 7: EXACT <c>
3 <abc> <> | 9: END
Match successful!
Freeing REx: 'a*b+c'
```
If you have gotten this far into the tutorial, you can probably guess what the different parts of the debugging output tell you. The first part
```
Compiling REx 'a*b+c'
size 9 first at 1
1: STAR(4)
2: EXACT <a>(0)
4: PLUS(7)
5: EXACT <b>(0)
7: EXACT <c>(9)
9: END(0)
```
describes the compilation stage. `STAR(4)` means that there is a starred object, in this case `'a'`, and if it matches, goto line 4, *i.e.*, `PLUS(7)`. The middle lines describe some heuristics and optimizations performed before a match:
```
floating 'bc' at 0..2147483647 (checking floating) minlen 2
Guessing start of match, REx 'a*b+c' against 'abc'...
Found floating substr 'bc' at offset 1...
Guessed: match at offset 0
```
Then the match is executed and the remaining lines describe the process:
```
Matching REx 'a*b+c' against 'abc'
Setting an EVAL scope, savestack=3
0 <> <abc> | 1: STAR
EXACT <a> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
1 <a> <bc> | 4: PLUS
EXACT <b> can match 1 times out of 32767...
Setting an EVAL scope, savestack=3
2 <ab> <c> | 7: EXACT <c>
3 <abc> <> | 9: END
Match successful!
Freeing REx: 'a*b+c'
```
Each step is of the form `n <x> <y>`, with `<x>` the part of the string matched and `<y>` the part not yet matched. The `| 1: STAR` says that Perl is at line number 1 in the compilation list above. See ["Debugging Regular Expressions" in perldebguts](perldebguts#Debugging-Regular-Expressions) for much more detail.
An alternative method of debugging regexps is to embed `print` statements within the regexp. This provides a blow-by-blow account of the backtracking in an alternation:
```
"that this" =~ m@(?{print "Start at position ", pos, "\n";})
t(?{print "t1\n";})
h(?{print "h1\n";})
i(?{print "i1\n";})
s(?{print "s1\n";})
|
t(?{print "t2\n";})
h(?{print "h2\n";})
a(?{print "a2\n";})
t(?{print "t2\n";})
(?{print "Done at position ", pos, "\n";})
@x;
```
prints
```
Start at position 0
t1
h1
t2
h2
a2
t2
Done at position 4
```
SEE ALSO
---------
This is just a tutorial. For the full story on Perl regular expressions, see the <perlre> regular expressions reference page.
For more information on the matching `m//` and substitution `s///` operators, see ["Regexp Quote-Like Operators" in perlop](perlop#Regexp-Quote-Like-Operators). For information on the `split` operation, see ["split" in perlfunc](perlfunc#split).
For an excellent all-around resource on the care and feeding of regular expressions, see the book *Mastering Regular Expressions* by Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
AUTHOR AND COPYRIGHT
---------------------
Copyright (c) 2000 Mark Kvale. All rights reserved. Now maintained by Perl porters.
This document may be distributed under the same terms as Perl itself.
### Acknowledgments
The inspiration for the stop codon DNA example came from the ZIP code example in chapter 7 of *Mastering Regular Expressions*.
The author would like to thank Jeff Pinyan, Andrew Johnson, Peter Haworth, Ronald J Kimball, and Joe Smith for all their helpful comments.
| programming_docs |
perl ODBM_File ODBM\_File
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
+ [odbm store returned -1, errno 22, key "..." at ...](#odbm-store-returned-1,-errno-22,-key-%22...%22-at-...)
* [SECURITY AND PORTABILITY](#SECURITY-AND-PORTABILITY)
* [BUGS AND WARNINGS](#BUGS-AND-WARNINGS)
NAME
----
ODBM\_File - Tied access to odbm files
SYNOPSIS
--------
```
use Fcntl; # For O_RDWR, O_CREAT, etc.
use ODBM_File;
# Now read and change the hash
$h{newkey} = newvalue;
print $h{oldkey};
...
untie %h;
```
DESCRIPTION
-----------
`ODBM_File` establishes a connection between a Perl hash variable and a file in ODBM\_File format;. You can manipulate the data in the file just as if it were in a Perl hash, but when your program exits, the data will remain in the file, to be used the next time your program runs.
Use `ODBM_File` with the Perl built-in `tie` function to establish the connection between the variable and the file. The arguments to `tie` should be:
1. The hash variable you want to tie.
2. The string `"ODBM_File"`. (Ths tells Perl to use the `ODBM_File` package to perform the functions of the hash.)
3. The name of the file you want to tie to the hash.
4. Flags. Use one of:
`O_RDONLY` Read-only access to the data in the file.
`O_WRONLY` Write-only access to the data in the file.
`O_RDWR` Both read and write access.
If you want to create the file if it does not exist, add `O_CREAT` to any of these, as in the example. If you omit `O_CREAT` and the file does not already exist, the `tie` call will fail.
5. The default permissions to use if a new file is created. The actual permissions will be modified by the user's umask, so you should probably use 0666 here. (See ["umask" in perlfunc](perlfunc#umask).)
DIAGNOSTICS
-----------
On failure, the `tie` call returns an undefined value and probably sets `$!` to contain the reason the file could not be tied.
###
`odbm store returned -1, errno 22, key "..." at ...`
This warning is emitted when you try to store a key or a value that is too long. It means that the change was not recorded in the database. See BUGS AND WARNINGS below.
SECURITY AND PORTABILITY
-------------------------
**Do not accept ODBM files from untrusted sources.**
On modern Linux systems these are typically GDBM files, which are not portable across platforms.
The GDBM documentation doesn't imply that files from untrusted sources can be safely used with `libgdbm`.
Systems that don't use GDBM compatibilty for old dbm support will be using a platform specific library, possibly inherited from BSD systems, where it may or may not be safe to use an untrusted file.
A maliciously crafted file might cause perl to crash or even expose a security vulnerability.
BUGS AND WARNINGS
------------------
There are a number of limits on the size of the data that you can store in the ODBM file. The most important is that the length of a key, plus the length of its associated value, may not exceed 1008 bytes.
See ["tie" in perlfunc](perlfunc#tie), <perldbmfilter>, [Fcntl](fcntl)
perl Unicode::Collate::CJK::Pinyin Unicode::Collate::CJK::Pinyin
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEAT](#CAVEAT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::Pinyin - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::Pinyin;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::Pinyin::weightPinyin
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::Pinyin` provides `weightPinyin()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's pinyin ordering.
CAVEAT
------
The pinyin ordering includes some characters that are not CJK Unified Ideographs and can't utilize `weightPinyin()` for collation. For them, use `entry` instead.
SEE ALSO
---------
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
<Unicode::Collate>
<Unicode::Collate::Locale>
perl CPAN::Meta CPAN::Meta
==========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [create](#create)
+ [load\_file](#load_file)
+ [load\_yaml\_string](#load_yaml_string)
+ [load\_json\_string](#load_json_string)
+ [load\_string](#load_string)
+ [save](#save)
+ [meta\_spec\_version](#meta_spec_version)
+ [effective\_prereqs](#effective_prereqs)
+ [should\_index\_file](#should_index_file)
+ [should\_index\_package](#should_index_package)
+ [features](#features)
+ [feature](#feature)
+ [as\_struct](#as_struct)
+ [as\_string](#as_string)
* [STRING DATA](#STRING-DATA)
* [LIST DATA](#LIST-DATA)
* [MAP DATA](#MAP-DATA)
* [CUSTOM DATA](#CUSTOM-DATA)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
+ [Bugs / Feature Requests](#Bugs-/-Feature-Requests)
+ [Source Code](#Source-Code)
* [AUTHORS](#AUTHORS)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta - the distribution metadata for a CPAN dist
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
use v5.10;
use strict;
use warnings;
use CPAN::Meta;
use Module::Load;
my $meta = CPAN::Meta->load_file('META.json');
printf "testing requirements for %s version %s\n",
$meta->name,
$meta->version;
my $prereqs = $meta->effective_prereqs;
for my $phase ( qw/configure runtime build test/ ) {
say "Requirements for $phase:";
my $reqs = $prereqs->requirements_for($phase, "requires");
for my $module ( sort $reqs->required_modules ) {
my $status;
if ( eval { load $module unless $module eq 'perl'; 1 } ) {
my $version = $module eq 'perl' ? $] : $module->VERSION;
$status = $reqs->accepts_module($module, $version)
? "$version ok" : "$version not ok";
} else {
$status = "missing"
};
say " $module ($status)";
}
}
```
DESCRIPTION
-----------
Software distributions released to the CPAN include a *META.json* or, for older distributions, *META.yml*, which describes the distribution, its contents, and the requirements for building and installing the distribution. The data structure stored in the *META.json* file is described in <CPAN::Meta::Spec>.
CPAN::Meta provides a simple class to represent this distribution metadata (or *distmeta*), along with some helpful methods for interrogating that data.
The documentation below is only for the methods of the CPAN::Meta object. For information on the meaning of individual fields, consult the spec.
METHODS
-------
### new
```
my $meta = CPAN::Meta->new($distmeta_struct, \%options);
```
Returns a valid CPAN::Meta object or dies if the supplied metadata hash reference fails to validate. Older-format metadata will be up-converted to version 2 if they validate against the original stated specification.
It takes an optional hashref of options. Valid options include:
* lazy\_validation -- if true, new will attempt to convert the given metadata to version 2 before attempting to validate it. This means than any fixable errors will be handled by CPAN::Meta::Converter before validation. (Note that this might result in invalid optional data being silently dropped.) The default is false.
### create
```
my $meta = CPAN::Meta->create($distmeta_struct, \%options);
```
This is same as `new()`, except that `generated_by` and `meta-spec` fields will be generated if not provided. This means the metadata structure is assumed to otherwise follow the latest <CPAN::Meta::Spec>.
### load\_file
```
my $meta = CPAN::Meta->load_file($distmeta_file, \%options);
```
Given a pathname to a file containing metadata, this deserializes the file according to its file suffix and constructs a new `CPAN::Meta` object, just like `new()`. It will die if the deserialized version fails to validate against its stated specification version.
It takes the same options as `new()` but `lazy_validation` defaults to true.
### load\_yaml\_string
```
my $meta = CPAN::Meta->load_yaml_string($yaml, \%options);
```
This method returns a new CPAN::Meta object using the first document in the given YAML string. In other respects it is identical to `load_file()`.
### load\_json\_string
```
my $meta = CPAN::Meta->load_json_string($json, \%options);
```
This method returns a new CPAN::Meta object using the structure represented by the given JSON string. In other respects it is identical to `load_file()`.
### load\_string
```
my $meta = CPAN::Meta->load_string($string, \%options);
```
If you don't know if a string contains YAML or JSON, this method will use <Parse::CPAN::Meta> to guess. In other respects it is identical to `load_file()`.
### save
```
$meta->save($distmeta_file, \%options);
```
Serializes the object as JSON and writes it to the given file. The only valid option is `version`, which defaults to '2'. On Perl 5.8.1 or later, the file is saved with UTF-8 encoding.
For `version` 2 (or higher), the filename should end in '.json'. <JSON::PP> is the default JSON backend. Using another JSON backend requires [JSON](json) 2.5 or later and you must set the `$ENV{PERL_JSON_BACKEND}` to a supported alternate backend like <JSON::XS>.
For `version` less than 2, the filename should end in '.yml'. <CPAN::Meta::Converter> is used to generate an older metadata structure, which is serialized to YAML. CPAN::Meta::YAML is the default YAML backend. You may set the `$ENV{PERL_YAML_BACKEND}` to a supported alternative backend, though this is not recommended due to subtle incompatibilities between YAML parsers on CPAN.
### meta\_spec\_version
This method returns the version part of the `meta_spec` entry in the distmeta structure. It is equivalent to:
```
$meta->meta_spec->{version};
```
### effective\_prereqs
```
my $prereqs = $meta->effective_prereqs;
my $prereqs = $meta->effective_prereqs( \@feature_identifiers );
```
This method returns a <CPAN::Meta::Prereqs> object describing all the prereqs for the distribution. If an arrayref of feature identifiers is given, the prereqs for the identified features are merged together with the distribution's core prereqs before the CPAN::Meta::Prereqs object is returned.
### should\_index\_file
```
... if $meta->should_index_file( $filename );
```
This method returns true if the given file should be indexed. It decides this by checking the `file` and `directory` keys in the `no_index` property of the distmeta structure. Note that neither the version format nor `release_status` are considered.
`$filename` should be given in unix format.
### should\_index\_package
```
... if $meta->should_index_package( $package );
```
This method returns true if the given package should be indexed. It decides this by checking the `package` and `namespace` keys in the `no_index` property of the distmeta structure. Note that neither the version format nor `release_status` are considered.
### features
```
my @feature_objects = $meta->features;
```
This method returns a list of <CPAN::Meta::Feature> objects, one for each optional feature described by the distribution's metadata.
### feature
```
my $feature_object = $meta->feature( $identifier );
```
This method returns a <CPAN::Meta::Feature> object for the optional feature with the given identifier. If no feature with that identifier exists, an exception will be raised.
### as\_struct
```
my $copy = $meta->as_struct( \%options );
```
This method returns a deep copy of the object's metadata as an unblessed hash reference. It takes an optional hashref of options. If the hashref contains a `version` argument, the copied metadata will be converted to the version of the specification and returned. For example:
```
my $old_spec = $meta->as_struct( {version => "1.4"} );
```
### as\_string
```
my $string = $meta->as_string( \%options );
```
This method returns a serialized copy of the object's metadata as a character string. (The strings are **not** UTF-8 encoded.) It takes an optional hashref of options. If the hashref contains a `version` argument, the copied metadata will be converted to the version of the specification and returned. For example:
```
my $string = $meta->as_string( {version => "1.4"} );
```
For `version` greater than or equal to 2, the string will be serialized as JSON. For `version` less than 2, the string will be serialized as YAML. In both cases, the same rules are followed as in the `save()` method for choosing a serialization backend.
The serialized structure will include a `x_serialization_backend` entry giving the package and version used to serialize. Any existing key in the given `$meta` object will be clobbered.
STRING DATA
------------
The following methods return a single value, which is the value for the corresponding entry in the distmeta structure. Values should be either undef or strings.
* abstract
* description
* dynamic\_config
* generated\_by
* name
* release\_status
* version
LIST DATA
----------
These methods return lists of string values, which might be represented in the distmeta structure as arrayrefs or scalars:
* authors
* keywords
* licenses
The `authors` and `licenses` methods may also be called as `author` and `license`, respectively, to match the field name in the distmeta structure.
MAP DATA
---------
These readers return hashrefs of arbitrary unblessed data structures, each described more fully in the specification:
* meta\_spec
* resources
* provides
* no\_index
* prereqs
* optional\_features
CUSTOM DATA
------------
A list of custom keys are available from the `custom_keys` method and particular keys may be retrieved with the `custom` method.
```
say $meta->custom($_) for $meta->custom_keys;
```
If a custom key refers to a data structure, a deep clone is returned.
BUGS
----
Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at <http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Meta>
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
SEE ALSO
---------
* <CPAN::Meta::Converter>
* <CPAN::Meta::Validator>
SUPPORT
-------
###
Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker at <https://github.com/Perl-Toolchain-Gang/CPAN-Meta/issues>. You will be notified automatically of any progress on your issue.
###
Source Code
This is open source software. The code repository is available for public review and contribution under the terms of the license.
<https://github.com/Perl-Toolchain-Gang/CPAN-Meta>
```
git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta.git
```
AUTHORS
-------
* David Golden <[email protected]>
* Ricardo Signes <[email protected]>
* Adam Kennedy <[email protected]>
CONTRIBUTORS
------------
* Ansgar Burchardt <[email protected]>
* Avar Arnfjord Bjarmason <[email protected]>
* Benjamin Noggle <[email protected]>
* Christopher J. Madsen <[email protected]>
* Chuck Adams <[email protected]>
* Cory G Watson <[email protected]>
* Damyan Ivanov <[email protected]>
* David Golden <[email protected]>
* Eric Wilhelm <[email protected]>
* Graham Knop <[email protected]>
* Gregor Hermann <[email protected]>
* Karen Etheridge <[email protected]>
* Kenichi Ishigaki <[email protected]>
* Kent Fredric <[email protected]>
* Ken Williams <[email protected]>
* Lars Dieckow <[email protected]>
* Leon Timmermans <[email protected]>
* majensen <[email protected]>
* Mark Fowler <[email protected]>
* Matt S Trout <[email protected]>
* Michael G. Schwern <[email protected]>
* Mohammad S Anwar <[email protected]>
* mohawk2 <[email protected]>
* moznion <[email protected]>
* Niko Tyni <[email protected]>
* Olaf Alders <[email protected]>
* Olivier Mengué <[email protected]>
* Randy Sims <[email protected]>
* Tomohiro Hosaka <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by David Golden, Ricardo Signes, Adam Kennedy and Contributors.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl B::Xref B::Xref
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
B::Xref - Generates cross reference reports for Perl programs
SYNOPSIS
--------
perl -MO=Xref[,OPTIONS] foo.pl
DESCRIPTION
-----------
The B::Xref module is used to generate a cross reference listing of all definitions and uses of variables, subroutines and formats in a Perl program. It is implemented as a backend for the Perl compiler.
The report generated is in the following format:
```
File filename1
Subroutine subname1
Package package1
object1 line numbers
object2 line numbers
...
Package package2
...
```
Each **File** section reports on a single file. Each **Subroutine** section reports on a single subroutine apart from the special cases "(definitions)" and "(main)". These report, respectively, on subroutine definitions found by the initial symbol table walk and on the main part of the program or module external to all subroutines.
The report is then grouped by the **Package** of each variable, subroutine or format with the special case "(lexicals)" meaning lexical variables. Each **object** name (implicitly qualified by its containing **Package**) includes its type character(s) at the beginning where possible. Lexical variables are easier to track and even included dereferencing information where possible.
The `line numbers` are a comma separated list of line numbers (some preceded by code letters) where that object is used in some way. Simple uses aren't preceded by a code letter. Introductions (such as where a lexical is first defined with `my`) are indicated with the letter "i". Subroutine and method calls are indicated by the character "&". Subroutine definitions are indicated by "s" and format definitions by "f".
For instance, here's part of the report from the *pod2man* program that comes with Perl:
```
Subroutine clear_noremap
Package (lexical)
$ready_to_print i1069, 1079
Package main
$& 1086
$. 1086
$0 1086
$1 1087
$2 1085, 1085
$3 1085, 1085
$ARGV 1086
%HTML_Escapes 1085, 1085
```
This shows the variables used in the subroutine `clear_noremap`. The variable `$ready_to_print` is a my() (lexical) variable, **i**ntroduced (first declared with my()) on line 1069, and used on line 1079. The variable `$&` from the main package is used on 1086, and so on.
A line number may be prefixed by a single letter:
i Lexical variable introduced (declared with my()) for the first time.
& Subroutine or method call.
s Subroutine defined.
r Format defined.
The most useful option the cross referencer has is to save the report to a separate file. For instance, to save the report on *myperlprogram* to the file *report*:
```
$ perl -MO=Xref,-oreport myperlprogram
```
OPTIONS
-------
Option words are separated by commas (not whitespace) and follow the usual conventions of compiler backend options.
`-oFILENAME`
Directs output to `FILENAME` instead of standard output.
`-r`
Raw output. Instead of producing a human-readable report, outputs a line in machine-readable form for each definition/use of a variable/sub/format.
`-d`
Don't output the "(definitions)" sections.
`-D[tO]`
(Internal) debug options, probably only useful if `-r` included. The `t` option prints the object on the top of the stack as it's being tracked. The `O` option prints each operator as it's being processed in the execution order of the program.
BUGS
----
Non-lexical variables are quite difficult to track through a program. Sometimes the type of a non-lexical variable's use is impossible to determine. Introductions of non-lexical non-scalars don't seem to be reported properly.
AUTHOR
------
Malcolm Beattie, [email protected].
| programming_docs |
perl DynaLoader DynaLoader
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
NAME
----
DynaLoader - Dynamically load C libraries into Perl code
SYNOPSIS
--------
```
package YourPackage;
require DynaLoader;
@ISA = qw(... DynaLoader ...);
__PACKAGE__->bootstrap;
# optional method for 'global' loading
sub dl_load_flags { 0x01 }
```
DESCRIPTION
-----------
This document defines a standard generic interface to the dynamic linking mechanisms available on many platforms. Its primary purpose is to implement automatic dynamic loading of Perl modules.
This document serves as both a specification for anyone wishing to implement the DynaLoader for a new platform and as a guide for anyone wishing to use the DynaLoader directly in an application.
The DynaLoader is designed to be a very simple high-level interface that is sufficiently general to cover the requirements of SunOS, HP-UX, Linux, VMS and other platforms.
It is also hoped that the interface will cover the needs of OS/2, NT etc and also allow pseudo-dynamic linking (using `ld -A` at runtime).
It must be stressed that the DynaLoader, by itself, is practically useless for accessing non-Perl libraries because it provides almost no Perl-to-C 'glue'. There is, for example, no mechanism for calling a C library function or supplying arguments. A C::DynaLib module is available from CPAN sites which performs that function for some common system types. And since the year 2000, there's also Inline::C, a module that allows you to write Perl subroutines in C. Also available from your local CPAN site.
DynaLoader Interface Summary
```
@dl_library_path
@dl_resolve_using
@dl_require_symbols
$dl_debug
$dl_dlext
@dl_librefs
@dl_modules
@dl_shared_objects
Implemented in:
bootstrap($modulename) Perl
@filepaths = dl_findfile(@names) Perl
$flags = $modulename->dl_load_flags Perl
$symref = dl_find_symbol_anywhere($symbol) Perl
$libref = dl_load_file($filename, $flags) C
$status = dl_unload_file($libref) C
$symref = dl_find_symbol($libref, $symbol) C
@symbols = dl_undef_symbols() C
dl_install_xsub($name, $symref [, $filename]) C
$message = dl_error C
```
@dl\_library\_path The standard/default list of directories in which dl\_findfile() will search for libraries etc. Directories are searched in order: $dl\_library\_path[0], [1], ... etc
@dl\_library\_path is initialised to hold the list of 'normal' directories (*/usr/lib*, etc) determined by **Configure** (`$Config{'libpth'}`). This should ensure portability across a wide range of platforms.
@dl\_library\_path should also be initialised with any other directories that can be determined from the environment at runtime (such as LD\_LIBRARY\_PATH for SunOS).
After initialisation @dl\_library\_path can be manipulated by an application using push and unshift before calling dl\_findfile(). Unshift can be used to add directories to the front of the search order either to save search time or to override libraries with the same name in the 'normal' directories.
The load function that dl\_load\_file() calls may require an absolute pathname. The dl\_findfile() function and @dl\_library\_path can be used to search for and return the absolute pathname for the library/object that you wish to load.
@dl\_resolve\_using A list of additional libraries or other shared objects which can be used to resolve any undefined symbols that might be generated by a later call to load\_file().
This is only required on some platforms which do not handle dependent libraries automatically. For example the Socket Perl extension library (*auto/Socket/Socket.so*) contains references to many socket functions which need to be resolved when it's loaded. Most platforms will automatically know where to find the 'dependent' library (e.g., */usr/lib/libsocket.so*). A few platforms need to be told the location of the dependent library explicitly. Use @dl\_resolve\_using for this.
Example usage:
```
@dl_resolve_using = dl_findfile('-lsocket');
```
@dl\_require\_symbols A list of one or more symbol names that are in the library/object file to be dynamically loaded. This is only required on some platforms.
@dl\_librefs An array of the handles returned by successful calls to dl\_load\_file(), made by bootstrap, in the order in which they were loaded. Can be used with dl\_find\_symbol() to look for a symbol in any of the loaded files.
@dl\_modules An array of module (package) names that have been bootstrap'ed.
@dl\_shared\_objects An array of file names for the shared objects that were loaded.
dl\_error() Syntax:
```
$message = dl_error();
```
Error message text from the last failed DynaLoader function. Note that, similar to errno in unix, a successful function call does not reset this message.
Implementations should detect the error as soon as it occurs in any of the other functions and save the corresponding message for later retrieval. This will avoid problems on some platforms (such as SunOS) where the error message is very temporary (e.g., dlerror()).
$dl\_debug Internal debugging messages are enabled when $dl\_debug is set true. Currently setting $dl\_debug only affects the Perl side of the DynaLoader. These messages should help an application developer to resolve any DynaLoader usage problems.
$dl\_debug is set to `$ENV{'PERL_DL_DEBUG'}` if defined.
For the DynaLoader developer/porter there is a similar debugging variable added to the C code (see dlutils.c) and enabled if Perl was built with the **-DDEBUGGING** flag. This can also be set via the PERL\_DL\_DEBUG environment variable. Set to 1 for minimal information or higher for more.
$dl\_dlext When specified (localised) in a module's *.pm* file, indicates the extension which the module's loadable object will have. For example:
```
local $DynaLoader::dl_dlext = 'unusual_ext';
```
would indicate that the module's loadable object has an extension of `unusual_ext` instead of the more usual `$Config{dlext}`. NOTE: This also requires that the module's *Makefile.PL* specify (in `WriteMakefile()`):
```
DLEXT => 'unusual_ext',
```
dl\_findfile() Syntax:
```
@filepaths = dl_findfile(@names)
```
Determine the full paths (including file suffix) of one or more loadable files given their generic names and optionally one or more directories. Searches directories in @dl\_library\_path by default and returns an empty list if no files were found.
Names can be specified in a variety of platform independent forms. Any names in the form **-lname** are converted into *libname.\**, where *.\** is an appropriate suffix for the platform.
If a name does not already have a suitable prefix and/or suffix then the corresponding file will be searched for by trying combinations of prefix and suffix appropriate to the platform: "$name.o", "lib$name.\*" and "$name".
If any directories are included in @names they are searched before @dl\_library\_path. Directories may be specified as **-Ldir**. Any other names are treated as filenames to be searched for.
Using arguments of the form `-Ldir` and `-lname` is recommended.
Example:
```
@dl_resolve_using = dl_findfile(qw(-L/usr/5lib -lposix));
```
dl\_expandspec() Syntax:
```
$filepath = dl_expandspec($spec)
```
Some unusual systems, such as VMS, require special filename handling in order to deal with symbolic names for files (i.e., VMS's Logical Names).
To support these systems a dl\_expandspec() function can be implemented either in the *dl\_\*.xs* file or code can be added to the dl\_expandspec() function in *DynaLoader.pm*. See *DynaLoader\_pm.PL* for more information.
dl\_load\_file() Syntax:
```
$libref = dl_load_file($filename, $flags)
```
Dynamically load $filename, which must be the path to a shared object or library. An opaque 'library reference' is returned as a handle for the loaded object. Returns undef on error.
The $flags argument to alters dl\_load\_file behaviour. Assigned bits:
```
0x01 make symbols available for linking later dl_load_file's.
(only known to work on Solaris 2 using dlopen(RTLD_GLOBAL))
(ignored under VMS; this is a normal part of image linking)
```
(On systems that provide a handle for the loaded object such as SunOS and HPUX, $libref will be that handle. On other systems $libref will typically be $filename or a pointer to a buffer containing $filename. The application should not examine or alter $libref in any way.)
This is the function that does the real work. It should use the current values of @dl\_require\_symbols and @dl\_resolve\_using if required.
```
SunOS: dlopen($filename)
HP-UX: shl_load($filename)
Linux: dld_create_reference(@dl_require_symbols); dld_link($filename)
VMS: lib$find_image_symbol($filename,$dl_require_symbols[0])
```
(The dlopen() function is also used by Solaris and some versions of Linux, and is a common choice when providing a "wrapper" on other mechanisms as is done in the OS/2 port.)
dl\_unload\_file() Syntax:
```
$status = dl_unload_file($libref)
```
Dynamically unload $libref, which must be an opaque 'library reference' as returned from dl\_load\_file. Returns one on success and zero on failure. This function is optional and may not necessarily be provided on all platforms.
If it is defined and perl is compiled with the C macro `DL_UNLOAD_ALL_AT_EXIT` defined, then it is called automatically when the interpreter exits for every shared object or library loaded by DynaLoader::bootstrap. All such library references are stored in @dl\_librefs by DynaLoader::Bootstrap as it loads the libraries. The files are unloaded in last-in, first-out order.
This unloading is usually necessary when embedding a shared-object perl (e.g. one configured with -Duseshrplib) within a larger application, and the perl interpreter is created and destroyed several times within the lifetime of the application. In this case it is possible that the system dynamic linker will unload and then subsequently reload the shared libperl without relocating any references to it from any files DynaLoaded by the previous incarnation of the interpreter. As a result, any shared objects opened by DynaLoader may point to a now invalid 'ghost' of the libperl shared object, causing apparently random memory corruption and crashes. This behaviour is most commonly seen when using Apache and mod\_perl built with the APXS mechanism.
```
SunOS: dlclose($libref)
HP-UX: ???
Linux: ???
VMS: ???
```
(The dlclose() function is also used by Solaris and some versions of Linux, and is a common choice when providing a "wrapper" on other mechanisms as is done in the OS/2 port.)
dl\_load\_flags() Syntax:
```
$flags = dl_load_flags $modulename;
```
Designed to be a method call, and to be overridden by a derived class (i.e. a class which has DynaLoader in its @ISA). The definition in DynaLoader itself returns 0, which produces standard behavior from dl\_load\_file().
dl\_find\_symbol() Syntax:
```
$symref = dl_find_symbol($libref, $symbol)
```
Return the address of the symbol $symbol or `undef` if not found. If the target system has separate functions to search for symbols of different types then dl\_find\_symbol() should search for function symbols first and then other types.
The exact manner in which the address is returned in $symref is not currently defined. The only initial requirement is that $symref can be passed to, and understood by, dl\_install\_xsub().
```
SunOS: dlsym($libref, $symbol)
HP-UX: shl_findsym($libref, $symbol)
Linux: dld_get_func($symbol) and/or dld_get_symbol($symbol)
VMS: lib$find_image_symbol($libref,$symbol)
```
dl\_find\_symbol\_anywhere() Syntax:
```
$symref = dl_find_symbol_anywhere($symbol)
```
Applies dl\_find\_symbol() to the members of @dl\_librefs and returns the first match found.
dl\_undef\_symbols() Example
```
@symbols = dl_undef_symbols()
```
Return a list of symbol names which remain undefined after load\_file(). Returns `()` if not known. Don't worry if your platform does not provide a mechanism for this. Most do not need it and hence do not provide it, they just return an empty list.
dl\_install\_xsub() Syntax:
```
dl_install_xsub($perl_name, $symref [, $filename])
```
Create a new Perl external subroutine named $perl\_name using $symref as a pointer to the function which implements the routine. This is simply a direct call to newXS()/newXS\_flags(). Returns a reference to the installed function.
The $filename parameter is used by Perl to identify the source file for the function if required by die(), caller() or the debugger. If $filename is not defined then "DynaLoader" will be used.
bootstrap() Syntax:
bootstrap($module [...])
This is the normal entry point for automatic dynamic loading in Perl.
It performs the following actions:
* locates an auto/$module directory by searching @INC
* uses dl\_findfile() to determine the filename to load
* sets @dl\_require\_symbols to `("boot_$module")`
* executes an *auto/$module/$module.bs* file if it exists (typically used to add to @dl\_resolve\_using any files which are required to load the module on the current platform)
* calls dl\_load\_flags() to determine how to load the file.
* calls dl\_load\_file() to load the file
* calls dl\_undef\_symbols() and warns if any symbols are undefined
* calls dl\_find\_symbol() for "boot\_$module"
* calls dl\_install\_xsub() to install it as "${module}::bootstrap"
* calls &{"${module}::bootstrap"} to bootstrap the module (actually it uses the function reference returned by dl\_install\_xsub for speed)
All arguments to bootstrap() are passed to the module's bootstrap function. The default code generated by *xsubpp* expects $module [, $version] If the optional $version argument is not given, it defaults to `$XS_VERSION // $VERSION` in the module's symbol table. The default code compares the Perl-space version with the version of the compiled XS code, and croaks with an error if they do not match.
AUTHOR
------
Tim Bunce, 11 August 1994.
This interface is based on the work and comments of (in no particular order): Larry Wall, Robert Sanders, Dean Roehrich, Jeff Okamoto, Anno Siegel, Thomas Neumann, Paul Marquess, Charles Bailey, myself and others.
Larry Wall designed the elegant inherited bootstrap mechanism and implemented the first Perl 5 dynamic loader using it.
Solaris global loading added by Nick Ing-Simmons with design/coding assistance from Tim Bunce, January 1996.
perl bytes bytes
=====
CONTENTS
--------
* [NAME](#NAME)
* [NOTICE](#NOTICE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [LIMITATIONS](#LIMITATIONS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
bytes - Perl pragma to expose the individual bytes of characters
NOTICE
------
Because the bytes pragma breaks encapsulation (i.e. it exposes the innards of how the perl executable currently happens to store a string), the byte values that result are in an unspecified encoding.
**Use of this module for anything other than debugging purposes is strongly discouraged.** If you feel that the functions here within might be useful for your application, this possibly indicates a mismatch between your mental model of Perl Unicode and the current reality. In that case, you may wish to read some of the perl Unicode documentation: <perluniintro>, <perlunitut>, <perlunifaq> and <perlunicode>.
SYNOPSIS
--------
```
use bytes;
... chr(...); # or bytes::chr
... index(...); # or bytes::index
... length(...); # or bytes::length
... ord(...); # or bytes::ord
... rindex(...); # or bytes::rindex
... substr(...); # or bytes::substr
no bytes;
```
DESCRIPTION
-----------
Perl's characters are stored internally as sequences of one or more bytes. This pragma allows for the examination of the individual bytes that together comprise a character.
Originally the pragma was designed for the loftier goal of helping incorporate Unicode into Perl, but the approach that used it was found to be defective, and the one remaining legitimate use is for debugging when you need to non-destructively examine characters' individual bytes. Just insert this pragma temporarily, and remove it after the debugging is finished.
The original usage can be accomplished by explicit (rather than this pragma's implicit) encoding using the [Encode](encode) module:
```
use Encode qw/encode/;
my $utf8_byte_string = encode "UTF8", $string;
my $latin1_byte_string = encode "Latin1", $string;
```
Or, if performance is needed and you are only interested in the UTF-8 representation:
```
utf8::encode(my $utf8_byte_string = $string);
```
`no bytes` can be used to reverse the effect of `use bytes` within the current lexical scope.
As an example, when Perl sees `$x = chr(400)`, it encodes the character in UTF-8 and stores it in `$x`. Then it is marked as character data, so, for instance, `length $x` returns `1`. However, in the scope of the `bytes` pragma, `$x` is treated as a series of bytes - the bytes that make up the UTF8 encoding - and `length $x` returns `2`:
```
$x = chr(400);
print "Length is ", length $x, "\n"; # "Length is 1"
printf "Contents are %vd\n", $x; # "Contents are 400"
{
use bytes; # or "require bytes; bytes::length()"
print "Length is ", length $x, "\n"; # "Length is 2"
printf "Contents are %vd\n", $x; # "Contents are 198.144 (on
# ASCII platforms)"
}
```
`chr()`, `ord()`, `substr()`, `index()` and `rindex()` behave similarly.
For more on the implications, see <perluniintro> and <perlunicode>.
`bytes::length()` is admittedly handy if you need to know the **byte length** of a Perl scalar. But a more modern way is:
```
use Encode 'encode';
length(encode('UTF-8', $scalar))
```
LIMITATIONS
-----------
`bytes::substr()` does not work as an *lvalue()*.
SEE ALSO
---------
<perluniintro>, <perlunicode>, <utf8>, [Encode](encode)
perl perlapi perlapi
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [AV Handling](#AV-Handling1)
* [Callback Functions](#Callback-Functions1)
* [Casting](#Casting1)
* [Character case changing](#Character-case-changing1)
* [Character classification](#Character-classification1)
* [Compiler and Preprocessor information](#Compiler-and-Preprocessor-information1)
* [Compiler directives](#Compiler-directives1)
* [Compile-time scope hooks](#Compile-time-scope-hooks1)
* [Concurrency](#Concurrency1)
* [COPs and Hint Hashes](#COPs-and-Hint-Hashes1)
* [Custom Operators](#Custom-Operators1)
* [CV Handling](#CV-Handling1)
* [Debugging](#Debugging1)
* [Display functions](#Display-functions1)
* [Embedding, Threads, and Interpreter Cloning](#Embedding,-Threads,-and-Interpreter-Cloning)
* [Errno](#Errno1)
* [Exception Handling (simple) Macros](#Exception-Handling-(simple)-Macros)
* [Filesystem configuration values](#Filesystem-configuration-values1)
* [Floating point](#Floating-point1)
* [General Configuration](#General-Configuration1)
+ [List of capability HAS\_foo symbols](#List-of-capability-HAS_foo-symbols)
+ [List of #include needed symbols](#List-of-%23include-needed-symbols)
* [Global Variables](#Global-Variables1)
* [GV Handling and Stashes](#GV-Handling-and-Stashes1)
* [Hook manipulation](#Hook-manipulation1)
* [HV Handling](#HV-Handling1)
* [Input/Output](#Input/Output)
* [Integer](#Integer1)
* [I/O Formats](#I/O-Formats)
* [Lexer interface](#Lexer-interface1)
* [Locales](#Locales1)
* [Magic](#Magic1)
* [Memory Management](#Memory-Management1)
* [MRO](#MRO1)
* [Multicall Functions](#Multicall-Functions1)
* [Numeric Functions](#Numeric-Functions1)
* [Optrees](#Optrees1)
* [Pack and Unpack](#Pack-and-Unpack1)
* [Pad Data Structures](#Pad-Data-Structures1)
* [Password and Group access](#Password-and-Group-access1)
* [Paths to system commands](#Paths-to-system-commands1)
* [Prototype information](#Prototype-information1)
* [REGEXP Functions](#REGEXP-Functions1)
* [Reports and Formats](#Reports-and-Formats1)
* [Signals](#Signals1)
* [Site configuration](#Site-configuration1)
* [Sockets configuration values](#Sockets-configuration-values1)
* [Source Filters](#Source-Filters1)
* [Stack Manipulation Macros](#Stack-Manipulation-Macros1)
* [String Handling](#String-Handling1)
* [SV Flags](#SV-Flags1)
* [SV Handling](#SV-Handling1)
* [Tainting](#Tainting1)
* [Time](#Time1)
* [Typedef names](#Typedef-names1)
* [Unicode Support](#Unicode-Support1)
* [Utility Functions](#Utility-Functions1)
* [Versioning](#Versioning1)
* [Warning and Dieing](#Warning-and-Dieing1)
* [XS](#XS1)
* [Undocumented elements](#Undocumented-elements1)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlapi - autogenerated documentation for the perl public API
DESCRIPTION
-----------
This file contains most of the documentation of the perl public API, as generated by *embed.pl*. Specifically, it is a listing of functions, macros, flags, and variables that may be used by extension writers. Besides <perlintern> and *config.h*, some items are listed here as being actually documented in another pod.
[At the end](#Undocumented-elements) is a list of functions which have yet to be documented. Patches welcome! The interfaces of these are subject to change without notice.
Some of the functions documented here are consolidated so that a single entry serves for multiple functions which all do basically the same thing, but have some slight differences. For example, one form might process magic, while another doesn't. The name of each variation is listed at the top of the single entry. But if all have the same signature (arguments and return type) except for their names, only the usage for the base form is shown. If any one of the forms has a different signature (such as returning `const` or not) every function's signature is explicitly displayed.
Anything not listed here or in the other mentioned pods is not part of the public API, and should not be used by extension writers at all. For these reasons, blindly using functions listed in *proto.h* is to be avoided when writing extensions.
In Perl, unlike C, a string of characters may generally contain embedded `NUL` characters. Sometimes in the documentation a Perl string is referred to as a "buffer" to distinguish it from a C string, but sometimes they are both just referred to as strings.
Note that all Perl API global variables must be referenced with the `PL_` prefix. Again, those not listed here are not to be used by extension writers, and can be changed or removed without notice; same with macros. Some macros are provided for compatibility with the older, unadorned names, but this support may be disabled in a future release.
Perl was originally written to handle US-ASCII only (that is characters whose ordinal numbers are in the range 0 - 127). And documentation and comments may still use the term ASCII, when sometimes in fact the entire range from 0 - 255 is meant.
The non-ASCII characters below 256 can have various meanings, depending on various things. (See, most notably, <perllocale>.) But usually the whole range can be referred to as ISO-8859-1. Often, the term "Latin-1" (or "Latin1") is used as an equivalent for ISO-8859-1. But some people treat "Latin1" as referring just to the characters in the range 128 through 255, or sometimes from 160 through 255. This documentation uses "Latin1" and "Latin-1" to refer to all 256 characters.
Note that Perl can be compiled and run under either ASCII or EBCDIC (See <perlebcdic>). Most of the documentation (and even comments in the code) ignore the EBCDIC possibility. For almost all purposes the differences are transparent. As an example, under EBCDIC, instead of UTF-8, UTF-EBCDIC is used to encode Unicode strings, and so whenever this documentation refers to `utf8` (and variants of that name, including in function names), it also (essentially transparently) means `UTF-EBCDIC`. But the ordinals of characters differ between ASCII, EBCDIC, and the UTF- encodings, and a string encoded in UTF-EBCDIC may occupy a different number of bytes than in UTF-8.
The organization of this document is tentative and subject to change. Suggestions and patches welcome [[email protected]](mailto:[email protected]).
The sections in this document currently are
["AV Handling"](#AV-Handling)
["Callback Functions"](#Callback-Functions)
["Casting"](#Casting)
["Character case changing"](#Character-case-changing)
["Character classification"](#Character-classification)
["Compiler and Preprocessor information"](#Compiler-and-Preprocessor-information)
["Compiler directives"](#Compiler-directives)
["Compile-time scope hooks"](#Compile-time-scope-hooks)
["Concurrency"](#Concurrency)
["COPs and Hint Hashes"](#COPs-and-Hint-Hashes)
["Custom Operators"](#Custom-Operators)
["CV Handling"](#CV-Handling)
["Debugging"](#Debugging)
["Display functions"](#Display-functions)
["Embedding, Threads, and Interpreter Cloning"](#Embedding%2C-Threads%2C-and-Interpreter-Cloning)
["Errno"](#Errno)
["Exception Handling (simple) Macros"](#Exception-Handling-%28simple%29-Macros)
["Filesystem configuration values"](#Filesystem-configuration-values)
["Floating point"](#Floating-point)
["General Configuration"](#General-Configuration)
["Global Variables"](#Global-Variables)
["GV Handling and Stashes"](#GV-Handling-and-Stashes)
["Hook manipulation"](#Hook-manipulation)
["HV Handling"](#HV-Handling)
["Input/Output"](#Input%2FOutput)
["Integer"](#Integer)
["I/O Formats"](#I%2FO-Formats)
["Lexer interface"](#Lexer-interface)
["Locales"](#Locales)
["Magic"](#Magic)
["Memory Management"](#Memory-Management)
["MRO"](#MRO)
["Multicall Functions"](#Multicall-Functions)
["Numeric Functions"](#Numeric-Functions)
["Optrees"](#Optrees)
["Pack and Unpack"](#Pack-and-Unpack)
["Pad Data Structures"](#Pad-Data-Structures)
["Password and Group access"](#Password-and-Group-access)
["Paths to system commands"](#Paths-to-system-commands)
["Prototype information"](#Prototype-information)
["REGEXP Functions"](#REGEXP-Functions)
["Reports and Formats"](#Reports-and-Formats)
["Signals"](#Signals)
["Site configuration"](#Site-configuration)
["Sockets configuration values"](#Sockets-configuration-values)
["Source Filters"](#Source-Filters)
["Stack Manipulation Macros"](#Stack-Manipulation-Macros)
["String Handling"](#String-Handling)
["SV Flags"](#SV-Flags)
["SV Handling"](#SV-Handling)
["Tainting"](#Tainting)
["Time"](#Time)
["Typedef names"](#Typedef-names)
["Unicode Support"](#Unicode-Support)
["Utility Functions"](#Utility-Functions)
["Versioning"](#Versioning)
["Warning and Dieing"](#Warning-and-Dieing)
["XS"](#XS)
["Undocumented elements"](#Undocumented-elements)
The listing below is alphabetical, case insensitive.
AV Handling
------------
`AV` Described in <perlguts>.
`AvALLOC` Described in <perlguts>.
```
AvALLOC(AV* av)
```
`AvARRAY` Returns a pointer to the AV's internal SV\* array.
This is useful for doing pointer arithmetic on the array. If all you need is to look up an array element, then prefer `av_fetch`.
```
SV** AvARRAY(AV* av)
```
`av_clear` Frees all the elements of an array, leaving it empty. The XS equivalent of `@array = ()`. See also ["av\_undef"](#av_undef).
Note that it is possible that the actions of a destructor called directly or indirectly by freeing an element of the array could cause the reference count of the array itself to be reduced (e.g. by deleting an entry in the symbol table). So it is a possibility that the AV could have been freed (or even reallocated) on return from the call unless you hold a reference to it.
```
void av_clear(AV *av)
```
`av_count` Returns the number of elements in the array `av`. This is the true length of the array, including any undefined elements. It is always the same as `av_top_index(av) + 1`.
```
Size_t av_count(AV *av)
```
`av_create_and_push` Push an SV onto the end of the array, creating the array if necessary. A small internal helper function to remove a commonly duplicated idiom.
NOTE: `av_create_and_push` must be explicitly called as `Perl_av_create_and_push` with an `aTHX_` parameter.
```
void Perl_av_create_and_push(pTHX_ AV **const avp,
SV *const val)
```
`av_create_and_unshift_one` Unshifts an SV onto the beginning of the array, creating the array if necessary. A small internal helper function to remove a commonly duplicated idiom.
NOTE: `av_create_and_unshift_one` must be explicitly called as `Perl_av_create_and_unshift_one` with an `aTHX_` parameter.
```
SV** Perl_av_create_and_unshift_one(pTHX_ AV **const avp,
SV *const val)
```
`av_delete` Deletes the element indexed by `key` from the array, makes the element mortal, and returns it. If `flags` equals `G_DISCARD`, the element is freed and NULL is returned. NULL is also returned if `key` is out of range.
Perl equivalent: `splice(@myarray, $key, 1, undef)` (with the `splice` in void context if `G_DISCARD` is present).
```
SV* av_delete(AV *av, SSize_t key, I32 flags)
```
`av_exists` Returns true if the element indexed by `key` has been initialized.
This relies on the fact that uninitialized array elements are set to `NULL`.
Perl equivalent: `exists($myarray[$key])`.
```
bool av_exists(AV *av, SSize_t key)
```
`av_extend` Pre-extend an array so that it is capable of storing values at indexes `0..key`. Thus `av_extend(av,99)` guarantees that the array can store 100 elements, i.e. that `av_store(av, 0, sv)` through `av_store(av, 99, sv)` on a plain array will work without any further memory allocation.
If the av argument is a tied array then will call the `EXTEND` tied array method with an argument of `(key+1)`.
```
void av_extend(AV *av, SSize_t key)
```
`av_fetch` Returns the SV at the specified index in the array. The `key` is the index. If `lval` is true, you are guaranteed to get a real SV back (in case it wasn't real before), which you can then modify. Check that the return value is non-NULL before dereferencing it to a `SV*`.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied arrays.
The rough perl equivalent is `$myarray[$key]`.
```
SV** av_fetch(AV *av, SSize_t key, I32 lval)
```
`AvFILL` Same as `["av\_top\_index"](#av_top_index)` or `["av\_tindex"](#av_tindex)`.
```
SSize_t AvFILL(AV* av)
```
`av_fill` Set the highest index in the array to the given number, equivalent to Perl's `$#array = $fill;`.
The number of elements in the array will be `fill + 1` after `av_fill()` returns. If the array was previously shorter, then the additional elements appended are set to NULL. If the array was longer, then the excess elements are freed. `av_fill(av, -1)` is the same as `av_clear(av)`.
```
void av_fill(AV *av, SSize_t fill)
```
`av_len` Same as ["av\_top\_index"](#av_top_index). Note that, unlike what the name implies, it returns the maximum index in the array. This is unlike ["sv\_len"](#sv_len), which returns what you would expect.
**To get the true number of elements in the array, instead use `["av\_count"](#av_count)`**.
```
SSize_t av_len(AV *av)
```
`av_make` Creates a new AV and populates it with a list (`**strp`, length `size`) of SVs. A copy is made of each SV, so their refcounts are not changed. The new AV will have a reference count of 1.
Perl equivalent: `my @new_array = ($scalar1, $scalar2, $scalar3...);`
```
AV* av_make(SSize_t size, SV **strp)
```
`av_pop` Removes one SV from the end of the array, reducing its size by one and returning the SV (transferring control of one reference count) to the caller. Returns `&PL_sv_undef` if the array is empty.
Perl equivalent: `pop(@myarray);`
```
SV* av_pop(AV *av)
```
`av_push` Pushes an SV (transferring control of one reference count) onto the end of the array. The array will grow automatically to accommodate the addition.
Perl equivalent: `push @myarray, $val;`.
```
void av_push(AV *av, SV *val)
```
`av_shift` Removes one SV from the start of the array, reducing its size by one and returning the SV (transferring control of one reference count) to the caller. Returns `&PL_sv_undef` if the array is empty.
Perl equivalent: `shift(@myarray);`
```
SV* av_shift(AV *av)
```
`av_store` Stores an SV in an array. The array index is specified as `key`. The return value will be `NULL` if the operation failed or if the value did not need to be actually stored within the array (as in the case of tied arrays). Otherwise, it can be dereferenced to get the `SV*` that was stored there (= `val`)).
Note that the caller is responsible for suitably incrementing the reference count of `val` before the call, and decrementing it if the function returned `NULL`.
Approximate Perl equivalent: `splice(@myarray, $key, 1, $val)`.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied arrays.
```
SV** av_store(AV *av, SSize_t key, SV *val)
```
`av_tindex`
`av_top_index` These behave identically. If the array `av` is empty, these return -1; otherwise they return the maximum value of the indices of all the array elements which are currently defined in `av`.
They process 'get' magic.
The Perl equivalent for these is `$#av`.
Use `["av\_count"](#av_count)` to get the number of elements in an array.
```
SSize_t av_tindex(AV *av)
```
`av_undef` Undefines the array. The XS equivalent of `undef(@array)`.
As well as freeing all the elements of the array (like `av_clear()`), this also frees the memory used by the av to store its list of scalars.
See ["av\_clear"](#av_clear) for a note about the array possibly being invalid on return.
```
void av_undef(AV *av)
```
`av_unshift` Unshift the given number of `undef` values onto the beginning of the array. The array will grow automatically to accommodate the addition.
Perl equivalent: `unshift @myarray, ((undef) x $num);`
```
void av_unshift(AV *av, SSize_t num)
```
`get_av` Returns the AV of the specified Perl global or package array with the given name (so it won't work on lexical variables). `flags` are passed to `gv_fetchpv`. If `GV_ADD` is set and the Perl variable does not exist then it will be created. If `flags` is zero and the variable does not exist then NULL is returned.
Perl equivalent: `@{"$name"}`.
NOTE: the `perl_get_av()` form is **deprecated**.
```
AV* get_av(const char *name, I32 flags)
```
`newAV` `newAV_alloc_x`
`newAV_alloc_xz` These all create a new AV, setting the reference count to 1. If you also know the initial elements of the array with, see ["`av_make`"](#av_make).
As background, an array consists of three things:
1. A data structure containing information about the array as a whole, such as its size and reference count.
2. A C language array of pointers to the individual elements. These are treated as pointers to SVs, so all must be castable to SV\*.
3. The individual elements themselves. These could be, for instance, SVs and/or AVs and/or HVs, etc.
An empty array need only have the first data structure, and all these functions create that. They differ in what else they do, as follows:
`newAV` form This does nothing beyond creating the whole-array data structure. The Perl equivalent is approximately `my @array;`
This is useful when the minimum size of the array could be zero (perhaps there are likely code paths that will entirely skip using it).
If the array does get used, the pointers data structure will need to be allocated at that time. This will end up being done by ["av\_extend"](#av_extend)>, either explicitly:
```
av_extend(av, len);
```
or implicitly when the first element is stored:
```
(void)av_store(av, 0, sv);
```
Unused array elements are typically initialized by `av_extend`.
`newAV_alloc_x` form This effectively does a `newAV` followed by also allocating (uninitialized) space for the pointers array. This is used when you know ahead of time the likely minimum size of the array. It is more efficient to do this than doing a plain `newAV` followed by an `av_extend`.
Of course the array can be extended later should it become necessary.
`size` must be at least 1.
`newAV_alloc_xz` form This is `newAV_alloc_x`, but initializes each pointer in it to NULL. This gives added safety to guard against them being read before being set.
`size` must be at least 1.
The following examples all result in an array that can fit four elements (indexes 0 .. 3):
```
AV *av = newAV();
av_extend(av, 3);
AV *av = newAV_alloc_x(4);
AV *av = newAV_alloc_xz(4);
```
In contrast, the following examples allocate an array that is only guaranteed to fit one element without extending:
```
AV *av = newAV_alloc_x(1);
AV *av = newAV_alloc_xz(1);
```
```
AV* newAV ()
AV* newAV_alloc_x (SSize_t size)
AV* newAV_alloc_xz(SSize_t size)
```
`Nullav` `**DEPRECATED!**` It is planned to remove `Nullav` from a future release of Perl. Do not use it for new code; remove it from existing code.
Null AV pointer.
(deprecated - use `(AV *)NULL` instead)
Callback Functions
-------------------
`call_argv` Performs a callback to the specified named and package-scoped Perl subroutine with `argv` (a `NULL`-terminated array of strings) as arguments. See <perlcall>.
Approximate Perl equivalent: `&{"$sub_name"}(@$argv)`.
NOTE: the `perl_call_argv()` form is **deprecated**.
```
I32 call_argv(const char* sub_name, I32 flags, char** argv)
```
`call_method` Performs a callback to the specified Perl method. The blessed object must be on the stack. See <perlcall>.
NOTE: the `perl_call_method()` form is **deprecated**.
```
I32 call_method(const char* methname, I32 flags)
```
`call_pv` Performs a callback to the specified Perl sub. See <perlcall>.
NOTE: the `perl_call_pv()` form is **deprecated**.
```
I32 call_pv(const char* sub_name, I32 flags)
```
`call_sv` Performs a callback to the Perl sub specified by the SV.
If neither the `G_METHOD` nor `G_METHOD_NAMED` flag is supplied, the SV may be any of a CV, a GV, a reference to a CV, a reference to a GV or `SvPV(sv)` will be used as the name of the sub to call.
If the `G_METHOD` flag is supplied, the SV may be a reference to a CV or `SvPV(sv)` will be used as the name of the method to call.
If the `G_METHOD_NAMED` flag is supplied, `SvPV(sv)` will be used as the name of the method to call.
Some other values are treated specially for internal use and should not be depended on.
See <perlcall>.
NOTE: the `perl_call_sv()` form is **deprecated**.
```
I32 call_sv(SV* sv, volatile I32 flags)
```
`DESTRUCTORFUNC_NOCONTEXT_t` Described in <perlguts>.
`DESTRUCTORFUNC_t` Described in <perlguts>.
`ENTER` Opening bracket on a callback. See `["LEAVE"](#LEAVE)` and <perlcall>.
```
ENTER;
```
`ENTER_with_name` Same as `["ENTER"](#ENTER)`, but when debugging is enabled it also associates the given literal string with the new scope.
```
ENTER_with_name("name");
```
`eval_pv` Tells Perl to `eval` the given string in scalar context and return an SV\* result.
NOTE: the `perl_eval_pv()` form is **deprecated**.
```
SV* eval_pv(const char* p, I32 croak_on_error)
```
`eval_sv` Tells Perl to `eval` the string in the SV. It supports the same flags as `call_sv`, with the obvious exception of `G_EVAL`. See <perlcall>.
The `G_RETHROW` flag can be used if you only need eval\_sv() to execute code specified by a string, but not catch any errors.
NOTE: the `perl_eval_sv()` form is **deprecated**.
```
I32 eval_sv(SV* sv, I32 flags)
```
`FREETMPS` Closing bracket for temporaries on a callback. See `["SAVETMPS"](#SAVETMPS)` and <perlcall>.
```
FREETMPS;
```
`G_DISCARD` Described in <perlcall>.
`G_EVAL` Described in <perlcall>.
`GIMME` `**DEPRECATED!**` It is planned to remove `GIMME` from a future release of Perl. Do not use it for new code; remove it from existing code.
A backward-compatible version of `GIMME_V` which can only return `G_SCALAR` or `G_LIST`; in a void context, it returns `G_SCALAR`. Deprecated. Use `GIMME_V` instead.
```
U32 GIMME
```
`GIMME_V` The XSUB-writer's equivalent to Perl's `wantarray`. Returns `G_VOID`, `G_SCALAR` or `G_LIST` for void, scalar or list context, respectively. See <perlcall> for a usage example.
```
U32 GIMME_V
```
`G_KEEPERR` Described in <perlcall>.
`G_LIST` Described in <perlcall>.
`G_NOARGS` Described in <perlcall>.
`G_SCALAR` Described in <perlcall>.
`G_VOID` Described in <perlcall>.
`is_lvalue_sub` Returns non-zero if the sub calling this function is being called in an lvalue context. Returns 0 otherwise.
```
I32 is_lvalue_sub()
```
`LEAVE` Closing bracket on a callback. See `["ENTER"](#ENTER)` and <perlcall>.
```
LEAVE;
```
`LEAVE_with_name` Same as `["LEAVE"](#LEAVE)`, but when debugging is enabled it first checks that the scope has the given name. `name` must be a literal string.
```
LEAVE_with_name("name");
```
`PL_errgv` Described in <perlcall>.
`save_aptr` Described in <perlguts>.
```
void save_aptr(AV** aptr)
```
`save_ary` Described in <perlguts>.
```
AV* save_ary(GV* gv)
```
`SAVEBOOL` Described in <perlguts>.
```
SAVEBOOL(bool i)
```
`SAVEDELETE` Described in <perlguts>.
```
SAVEDELETE(HV * hv, char * key, I32 length)
```
`SAVEDESTRUCTOR` Described in <perlguts>.
```
SAVEDESTRUCTOR(DESTRUCTORFUNC_NOCONTEXT_t f, void *p)
```
`SAVEDESTRUCTOR_X` Described in <perlguts>.
```
SAVEDESTRUCTOR_X(DESTRUCTORFUNC_t f, void *p)
```
`SAVEFREEOP` Described in <perlguts>.
```
SAVEFREEOP(OP *op)
```
`SAVEFREEPV` Described in <perlguts>.
```
SAVEFREEPV(void * p)
```
`SAVEFREESV` Described in <perlguts>.
```
SAVEFREESV(SV* sv)
```
`save_hash` Described in <perlguts>.
```
HV* save_hash(GV* gv)
```
`save_hptr` Described in <perlguts>.
```
void save_hptr(HV** hptr)
```
`SAVEI8` Described in <perlguts>.
```
SAVEI8(I8 i)
```
`SAVEI32` Described in <perlguts>.
```
SAVEI32(I32 i)
```
`SAVEI16` Described in <perlguts>.
```
SAVEI16(I16 i)
```
`SAVEINT` Described in <perlguts>.
```
SAVEINT(int i)
```
`save_item` Described in <perlguts>.
```
void save_item(SV* item)
```
`SAVEIV` Described in <perlguts>.
```
SAVEIV(IV i)
```
`save_list` `**DEPRECATED!**` It is planned to remove `save_list` from a future release of Perl. Do not use it for new code; remove it from existing code.
Described in <perlguts>.
```
void save_list(SV** sarg, I32 maxsarg)
```
`SAVELONG` Described in <perlguts>.
```
SAVELONG(long i)
```
`SAVEMORTALIZESV` Described in <perlguts>.
```
SAVEMORTALIZESV(SV* sv)
```
`SAVEPPTR` Described in <perlguts>.
```
SAVEPPTR(char * p)
```
`save_scalar` Described in <perlguts>.
```
SV* save_scalar(GV* gv)
```
`SAVESPTR` Described in <perlguts>.
```
SAVESPTR(SV * s)
```
`SAVESTACK_POS` Described in <perlguts>.
```
SAVESTACK_POS()
```
`SAVESTRLEN` Described in <perlguts>.
```
SAVESTRLEN(STRLEN i)
```
`save_svref` Described in <perlguts>.
```
SV* save_svref(SV** sptr)
```
`SAVETMPS` Opening bracket for temporaries on a callback. See `["FREETMPS"](#FREETMPS)` and <perlcall>.
```
SAVETMPS;
```
Casting
-------
`cBOOL` Cast-to-bool. When Perl was able to be compiled on pre-C99 compilers, a `(bool)` cast didn't necessarily do the right thing, so this macro was created (and made somewhat complicated to work around bugs in old compilers). Now, many years later, and C99 is used, this is no longer required, but is kept for backwards compatibility.
```
bool cBOOL(bool expr)
```
`I_32` Cast an NV to I32 while avoiding undefined C behavior
```
I32 I_32(NV what)
```
`INT2PTR` Described in <perlguts>.
```
type INT2PTR(type, int value)
```
`I_V` Cast an NV to IV while avoiding undefined C behavior
```
IV I_V(NV what)
```
`PTR2IV` Described in <perlguts>.
```
IV PTR2IV(void * ptr)
```
`PTR2nat` Described in <perlguts>.
```
IV PTR2nat(void *)
```
`PTR2NV` Described in <perlguts>.
```
NV PTR2NV(void * ptr)
```
`PTR2ul` Described in <perlguts>.
```
unsigned long PTR2ul(void *)
```
`PTR2UV` Described in <perlguts>.
```
UV PTR2UV(void * ptr)
```
`PTRV` Described in <perlguts>.
`U_32` Cast an NV to U32 while avoiding undefined C behavior
```
U32 U_32(NV what)
```
`U_V` Cast an NV to UV while avoiding undefined C behavior
```
UV U_V(NV what)
```
Character case changing
------------------------
Perl uses "full" Unicode case mappings. This means that converting a single character to another case may result in a sequence of more than one character. For example, the uppercase of `ß` (LATIN SMALL LETTER SHARP S) is the two character sequence `SS`. This presents some complications The lowercase of all characters in the range 0..255 is a single character, and thus `["toLOWER\_L1"](#toLOWER_L1)` is furnished. But, `toUPPER_L1` can't exist, as it couldn't return a valid result for all legal inputs. Instead `["toUPPER\_uvchr"](#toUPPER_uvchr)` has an API that does allow every possible legal result to be returned.) Likewise no other function that is crippled by not being able to give the correct results for the full range of possible inputs has been implemented here.
`toFOLD` `toFOLD_A` `toFOLD_uvchr` `toFOLD_utf8`
`toFOLD_utf8_safe` These all return the foldcase of a character. "foldcase" is an internal case for `/i` pattern matching. If the foldcase of character A and the foldcase of character B are the same, they match caselessly; otherwise they don't.
The differences in the forms are what domain they operate on, and whether the input is specified as a code point (those forms with a `cp` parameter) or as a UTF-8 string (the others). In the latter case, the code point to use is the first one in the buffer of UTF-8 encoded code points, delineated by the arguments `p .. e - 1`.
`toFOLD` and `toFOLD_A` are synonyms of each other. They return the foldcase of any ASCII-range code point. In this range, the foldcase is identical to the lowercase. All other inputs are returned unchanged. Since these are macros, the input type may be any integral one, and the output will occupy the same number of bits as the input.
There is no `toFOLD_L1` nor `toFOLD_LATIN1` as the foldcase of some code points in the 0..255 range is above that range or consists of multiple characters. Instead use `toFOLD_uvchr`.
`toFOLD_uvchr` returns the foldcase of any Unicode code point. The return value is identical to that of `toFOLD_A` for input code points in the ASCII range. The foldcase of the vast majority of Unicode code points is the same as the code point itself. For these, and for code points above the legal Unicode maximum, this returns the input code point unchanged. It additionally stores the UTF-8 of the result into the buffer beginning at `s`, and its length in bytes into `*lenp`. The caller must have made `s` large enough to contain at least `UTF8_MAXBYTES_CASE+1` bytes to avoid possible overflow.
NOTE: the foldcase of a code point may be more than one code point. The return value of this function is only the first of these. The entire foldcase is returned in `s`. To determine if the result is more than a single code point, you can do something like this:
```
uc = toFOLD_uvchr(cp, s, &len);
if (len > UTF8SKIP(s)) { is multiple code points }
else { is a single code point }
```
`toFOLD_utf8` and `toFOLD_utf8_safe` are synonyms of each other. The only difference between these and `toFOLD_uvchr` is that the source for these is encoded in UTF-8, instead of being a code point. It is passed as a buffer starting at `p`, with `e` pointing to one byte beyond its end. The `p` buffer may certainly contain more than one code point; but only the first one (up through `e - 1`) is examined. If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return the REPLACEMENT CHARACTER, at the discretion of the implementation, and subject to change in future releases.
```
UV toFOLD (UV cp)
UV toFOLD_A (UV cp)
UV toFOLD_uvchr (UV cp, U8* s, STRLEN* lenp)
UV toFOLD_utf8 (U8* p, U8* e, U8* s, STRLEN* lenp)
UV toFOLD_utf8_safe(U8* p, U8* e, U8* s, STRLEN* lenp)
```
`toLOWER` `toLOWER_A` `toLOWER_L1` `toLOWER_LATIN1` `toLOWER_LC` `toLOWER_uvchr` `toLOWER_utf8`
`toLOWER_utf8_safe` These all return the lowercase of a character. The differences are what domain they operate on, and whether the input is specified as a code point (those forms with a `cp` parameter) or as a UTF-8 string (the others). In the latter case, the code point to use is the first one in the buffer of UTF-8 encoded code points, delineated by the arguments `p .. e - 1`.
`toLOWER` and `toLOWER_A` are synonyms of each other. They return the lowercase of any uppercase ASCII-range code point. All other inputs are returned unchanged. Since these are macros, the input type may be any integral one, and the output will occupy the same number of bits as the input.
`toLOWER_L1` and `toLOWER_LATIN1` are synonyms of each other. They behave identically as `toLOWER` for ASCII-range input. But additionally will return the lowercase of any uppercase code point in the entire 0..255 range, assuming a Latin-1 encoding (or the EBCDIC equivalent on such platforms).
`toLOWER_LC` returns the lowercase of the input code point according to the rules of the current POSIX locale. Input code points outside the range 0..255 are returned unchanged.
`toLOWER_uvchr` returns the lowercase of any Unicode code point. The return value is identical to that of `toLOWER_L1` for input code points in the 0..255 range. The lowercase of the vast majority of Unicode code points is the same as the code point itself. For these, and for code points above the legal Unicode maximum, this returns the input code point unchanged. It additionally stores the UTF-8 of the result into the buffer beginning at `s`, and its length in bytes into `*lenp`. The caller must have made `s` large enough to contain at least `UTF8_MAXBYTES_CASE+1` bytes to avoid possible overflow.
NOTE: the lowercase of a code point may be more than one code point. The return value of this function is only the first of these. The entire lowercase is returned in `s`. To determine if the result is more than a single code point, you can do something like this:
```
uc = toLOWER_uvchr(cp, s, &len);
if (len > UTF8SKIP(s)) { is multiple code points }
else { is a single code point }
```
`toLOWER_utf8` and `toLOWER_utf8_safe` are synonyms of each other. The only difference between these and `toLOWER_uvchr` is that the source for these is encoded in UTF-8, instead of being a code point. It is passed as a buffer starting at `p`, with `e` pointing to one byte beyond its end. The `p` buffer may certainly contain more than one code point; but only the first one (up through `e - 1`) is examined. If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return the REPLACEMENT CHARACTER, at the discretion of the implementation, and subject to change in future releases.
```
UV toLOWER (UV cp)
UV toLOWER_A (UV cp)
UV toLOWER_L1 (UV cp)
UV toLOWER_LATIN1 (UV cp)
UV toLOWER_LC (UV cp)
UV toLOWER_uvchr (UV cp, U8* s, STRLEN* lenp)
UV toLOWER_utf8 (U8* p, U8* e, U8* s, STRLEN* lenp)
UV toLOWER_utf8_safe(U8* p, U8* e, U8* s, STRLEN* lenp)
```
`toTITLE` `toTITLE_A` `toTITLE_uvchr` `toTITLE_utf8`
`toTITLE_utf8_safe` These all return the titlecase of a character. The differences are what domain they operate on, and whether the input is specified as a code point (those forms with a `cp` parameter) or as a UTF-8 string (the others). In the latter case, the code point to use is the first one in the buffer of UTF-8 encoded code points, delineated by the arguments `p .. e - 1`.
`toTITLE` and `toTITLE_A` are synonyms of each other. They return the titlecase of any lowercase ASCII-range code point. In this range, the titlecase is identical to the uppercase. All other inputs are returned unchanged. Since these are macros, the input type may be any integral one, and the output will occupy the same number of bits as the input.
There is no `toTITLE_L1` nor `toTITLE_LATIN1` as the titlecase of some code points in the 0..255 range is above that range or consists of multiple characters. Instead use `toTITLE_uvchr`.
`toTITLE_uvchr` returns the titlecase of any Unicode code point. The return value is identical to that of `toTITLE_A` for input code points in the ASCII range. The titlecase of the vast majority of Unicode code points is the same as the code point itself. For these, and for code points above the legal Unicode maximum, this returns the input code point unchanged. It additionally stores the UTF-8 of the result into the buffer beginning at `s`, and its length in bytes into `*lenp`. The caller must have made `s` large enough to contain at least `UTF8_MAXBYTES_CASE+1` bytes to avoid possible overflow.
NOTE: the titlecase of a code point may be more than one code point. The return value of this function is only the first of these. The entire titlecase is returned in `s`. To determine if the result is more than a single code point, you can do something like this:
```
uc = toTITLE_uvchr(cp, s, &len);
if (len > UTF8SKIP(s)) { is multiple code points }
else { is a single code point }
```
`toTITLE_utf8` and `toTITLE_utf8_safe` are synonyms of each other. The only difference between these and `toTITLE_uvchr` is that the source for these is encoded in UTF-8, instead of being a code point. It is passed as a buffer starting at `p`, with `e` pointing to one byte beyond its end. The `p` buffer may certainly contain more than one code point; but only the first one (up through `e - 1`) is examined. If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return the REPLACEMENT CHARACTER, at the discretion of the implementation, and subject to change in future releases.
```
UV toTITLE (UV cp)
UV toTITLE_A (UV cp)
UV toTITLE_uvchr (UV cp, U8* s, STRLEN* lenp)
UV toTITLE_utf8 (U8* p, U8* e, U8* s, STRLEN* lenp)
UV toTITLE_utf8_safe(U8* p, U8* e, U8* s, STRLEN* lenp)
```
`toUPPER` `toUPPER_A` `toUPPER_uvchr` `toUPPER_utf8`
`toUPPER_utf8_safe` These all return the uppercase of a character. The differences are what domain they operate on, and whether the input is specified as a code point (those forms with a `cp` parameter) or as a UTF-8 string (the others). In the latter case, the code point to use is the first one in the buffer of UTF-8 encoded code points, delineated by the arguments `p .. e - 1`.
`toUPPER` and `toUPPER_A` are synonyms of each other. They return the uppercase of any lowercase ASCII-range code point. All other inputs are returned unchanged. Since these are macros, the input type may be any integral one, and the output will occupy the same number of bits as the input.
There is no `toUPPER_L1` nor `toUPPER_LATIN1` as the uppercase of some code points in the 0..255 range is above that range or consists of multiple characters. Instead use `toUPPER_uvchr`.
`toUPPER_uvchr` returns the uppercase of any Unicode code point. The return value is identical to that of `toUPPER_A` for input code points in the ASCII range. The uppercase of the vast majority of Unicode code points is the same as the code point itself. For these, and for code points above the legal Unicode maximum, this returns the input code point unchanged. It additionally stores the UTF-8 of the result into the buffer beginning at `s`, and its length in bytes into `*lenp`. The caller must have made `s` large enough to contain at least `UTF8_MAXBYTES_CASE+1` bytes to avoid possible overflow.
NOTE: the uppercase of a code point may be more than one code point. The return value of this function is only the first of these. The entire uppercase is returned in `s`. To determine if the result is more than a single code point, you can do something like this:
```
uc = toUPPER_uvchr(cp, s, &len);
if (len > UTF8SKIP(s)) { is multiple code points }
else { is a single code point }
```
`toUPPER_utf8` and `toUPPER_utf8_safe` are synonyms of each other. The only difference between these and `toUPPER_uvchr` is that the source for these is encoded in UTF-8, instead of being a code point. It is passed as a buffer starting at `p`, with `e` pointing to one byte beyond its end. The `p` buffer may certainly contain more than one code point; but only the first one (up through `e - 1`) is examined. If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return the REPLACEMENT CHARACTER, at the discretion of the implementation, and subject to change in future releases.
```
UV toUPPER (UV cp)
UV toUPPER_A (UV cp)
UV toUPPER_uvchr (UV cp, U8* s, STRLEN* lenp)
UV toUPPER_utf8 (U8* p, U8* e, U8* s, STRLEN* lenp)
UV toUPPER_utf8_safe(U8* p, U8* e, U8* s, STRLEN* lenp)
```
Character classification
-------------------------
This section is about functions (really macros) that classify characters into types, such as punctuation versus alphabetic, etc. Most of these are analogous to regular expression character classes. (See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).) There are several variants for each class. (Not all macros have all variants; each item below lists the ones valid for it.) None are affected by `use bytes`, and only the ones with `LC` in the name are affected by the current locale.
The base function, e.g., `isALPHA()`, takes any signed or unsigned value, treating it as a code point, and returns a boolean as to whether or not the character represented by it is (or on non-ASCII platforms, corresponds to) an ASCII character in the named class based on platform, Unicode, and Perl rules. If the input is a number that doesn't fit in an octet, FALSE is returned.
Variant `is*FOO*_A` (e.g., `isALPHA_A()`) is identical to the base function with no suffix `"_A"`. This variant is used to emphasize by its name that only ASCII-range characters can return TRUE.
Variant `is*FOO*_L1` imposes the Latin-1 (or EBCDIC equivalent) character set onto the platform. That is, the code points that are ASCII are unaffected, since ASCII is a subset of Latin-1. But the non-ASCII code points are treated as if they are Latin-1 characters. For example, `isWORDCHAR_L1()` will return true when called with the code point 0xDF, which is a word character in both ASCII and EBCDIC (though it represents different characters in each). If the input is a number that doesn't fit in an octet, FALSE is returned. (Perl's documentation uses a colloquial definition of Latin-1, to include all code points below 256.)
Variant `is*FOO*_uvchr` is exactly like the `is*FOO*_L1` variant, for inputs below 256, but if the code point is larger than 255, Unicode rules are used to determine if it is in the character class. For example, `isWORDCHAR_uvchr(0x100)` returns TRUE, since 0x100 is LATIN CAPITAL LETTER A WITH MACRON in Unicode, and is a word character.
Variants `is*FOO*_utf8` and `is*FOO*_utf8_safe` are like `is*FOO*_uvchr`, but are used for UTF-8 encoded strings. The two forms are different names for the same thing. Each call to one of these classifies the first character of the string starting at `p`. The second parameter, `e`, points to anywhere in the string beyond the first character, up to one byte past the end of the entire string. Although both variants are identical, the suffix `_safe` in one name emphasizes that it will not attempt to read beyond `e - 1`, provided that the constraint `s < e` is true (this is asserted for in `-DDEBUGGING` builds). If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return FALSE, at the discretion of the implementation, and subject to change in future releases.
Variant `is*FOO*_LC` is like the `is*FOO*_A` and `is*FOO*_L1` variants, but the result is based on the current locale, which is what `LC` in the name stands for. If Perl can determine that the current locale is a UTF-8 locale, it uses the published Unicode rules; otherwise, it uses the C library function that gives the named classification. For example, `isDIGIT_LC()` when not in a UTF-8 locale returns the result of calling `isdigit()`. FALSE is always returned if the input won't fit into an octet. On some platforms where the C library function is known to be defective, Perl changes its result to follow the POSIX standard's rules.
Variant `is*FOO*_LC_uvchr` acts exactly like `is*FOO*_LC` for inputs less than 256, but for larger ones it returns the Unicode classification of the code point.
Variants `is*FOO*_LC_utf8` and `is*FOO*_LC_utf8_safe` are like `is*FOO*_LC_uvchr`, but are used for UTF-8 encoded strings. The two forms are different names for the same thing. Each call to one of these classifies the first character of the string starting at `p`. The second parameter, `e`, points to anywhere in the string beyond the first character, up to one byte past the end of the entire string. Although both variants are identical, the suffix `_safe` in one name emphasizes that it will not attempt to read beyond `e - 1`, provided that the constraint `s < e` is true (this is asserted for in `-DDEBUGGING` builds). If the UTF-8 for the input character is malformed in some way, the program may croak, or the function may return FALSE, at the discretion of the implementation, and subject to change in future releases.
`isALPHA` `isALPHA_A` `isALPHA_L1` `isALPHA_uvchr` `isALPHA_utf8_safe` `isALPHA_utf8` `isALPHA_LC` `isALPHA_LC_uvchr`
`isALPHA_LC_utf8_safe` Returns a boolean indicating whether the specified input is one of `[A-Za-z]`, analogous to `m/[[:alpha:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isALPHA (UV ch)
bool isALPHA_A (UV ch)
bool isALPHA_L1 (UV ch)
bool isALPHA_uvchr (UV ch)
bool isALPHA_utf8_safe (U8 * s, U8 * end)
bool isALPHA_utf8 (U8 * s, U8 * end)
bool isALPHA_LC (UV ch)
bool isALPHA_LC_uvchr (UV ch)
bool isALPHA_LC_utf8_safe(U8 * s, U8 *end)
```
`isALPHANUMERIC` `isALPHANUMERIC_A` `isALPHANUMERIC_L1` `isALPHANUMERIC_uvchr` `isALPHANUMERIC_utf8_safe` `isALPHANUMERIC_utf8` `isALPHANUMERIC_LC` `isALPHANUMERIC_LC_uvchr` `isALPHANUMERIC_LC_utf8_safe` `isALNUMC` `isALNUMC_A` `isALNUMC_L1` `isALNUMC_LC`
`isALNUMC_LC_uvchr` Returns a boolean indicating whether the specified character is one of `[A-Za-z0-9]`, analogous to `m/[[:alnum:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants.
A (discouraged from use) synonym is `isALNUMC` (where the `C` suffix means this corresponds to the C language alphanumeric definition). Also there are the variants `isALNUMC_A`, `isALNUMC_L1` `isALNUMC_LC`, and `isALNUMC_LC_uvchr`.
```
bool isALPHANUMERIC (UV ch)
bool isALPHANUMERIC_A (UV ch)
bool isALPHANUMERIC_L1 (UV ch)
bool isALPHANUMERIC_uvchr (UV ch)
bool isALPHANUMERIC_utf8_safe (U8 * s, U8 * end)
bool isALPHANUMERIC_utf8 (U8 * s, U8 * end)
bool isALPHANUMERIC_LC (UV ch)
bool isALPHANUMERIC_LC_uvchr (UV ch)
bool isALPHANUMERIC_LC_utf8_safe(U8 * s, U8 *end)
bool isALNUMC (UV ch)
bool isALNUMC_A (UV ch)
bool isALNUMC_L1 (UV ch)
bool isALNUMC_LC (UV ch)
bool isALNUMC_LC_uvchr (UV ch)
```
`isASCII` `isASCII_A` `isASCII_L1` `isASCII_uvchr` `isASCII_utf8_safe` `isASCII_utf8` `isASCII_LC` `isASCII_LC_uvchr`
`isASCII_LC_utf8_safe` Returns a boolean indicating whether the specified character is one of the 128 characters in the ASCII character set, analogous to `m/[[:ascii:]]/`. On non-ASCII platforms, it returns TRUE iff this character corresponds to an ASCII character. Variants `isASCII_A()` and `isASCII_L1()` are identical to `isASCII()`. See the [top of this section](#Character-classification) for an explanation of the variants. Note, however, that some platforms do not have the C library routine `isascii()`. In these cases, the variants whose names contain `LC` are the same as the corresponding ones without.
Also note, that because all ASCII characters are UTF-8 invariant (meaning they have the exact same representation (always a single byte) whether encoded in UTF-8 or not), `isASCII` will give the correct results when called with any byte in any string encoded or not in UTF-8. And similarly `isASCII_utf8` and `isASCII_utf8_safe` will work properly on any string encoded or not in UTF-8.
```
bool isASCII (UV ch)
bool isASCII_A (UV ch)
bool isASCII_L1 (UV ch)
bool isASCII_uvchr (UV ch)
bool isASCII_utf8_safe (U8 * s, U8 * end)
bool isASCII_utf8 (U8 * s, U8 * end)
bool isASCII_LC (UV ch)
bool isASCII_LC_uvchr (UV ch)
bool isASCII_LC_utf8_safe(U8 * s, U8 *end)
```
`isBLANK` `isBLANK_A` `isBLANK_L1` `isBLANK_uvchr` `isBLANK_utf8_safe` `isBLANK_utf8` `isBLANK_LC` `isBLANK_LC_uvchr`
`isBLANK_LC_utf8_safe` Returns a boolean indicating whether the specified character is a character considered to be a blank, analogous to `m/[[:blank:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants. Note, however, that some platforms do not have the C library routine `isblank()`. In these cases, the variants whose names contain `LC` are the same as the corresponding ones without.
```
bool isBLANK (UV ch)
bool isBLANK_A (UV ch)
bool isBLANK_L1 (UV ch)
bool isBLANK_uvchr (UV ch)
bool isBLANK_utf8_safe (U8 * s, U8 * end)
bool isBLANK_utf8 (U8 * s, U8 * end)
bool isBLANK_LC (UV ch)
bool isBLANK_LC_uvchr (UV ch)
bool isBLANK_LC_utf8_safe(U8 * s, U8 *end)
```
`isCNTRL` `isCNTRL_A` `isCNTRL_L1` `isCNTRL_uvchr` `isCNTRL_utf8_safe` `isCNTRL_utf8` `isCNTRL_LC` `isCNTRL_LC_uvchr`
`isCNTRL_LC_utf8_safe` Returns a boolean indicating whether the specified character is a control character, analogous to `m/[[:cntrl:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants. On EBCDIC platforms, you almost always want to use the `isCNTRL_L1` variant.
```
bool isCNTRL (UV ch)
bool isCNTRL_A (UV ch)
bool isCNTRL_L1 (UV ch)
bool isCNTRL_uvchr (UV ch)
bool isCNTRL_utf8_safe (U8 * s, U8 * end)
bool isCNTRL_utf8 (U8 * s, U8 * end)
bool isCNTRL_LC (UV ch)
bool isCNTRL_LC_uvchr (UV ch)
bool isCNTRL_LC_utf8_safe(U8 * s, U8 *end)
```
`isDIGIT` `isDIGIT_A` `isDIGIT_L1` `isDIGIT_uvchr` `isDIGIT_utf8_safe` `isDIGIT_utf8` `isDIGIT_LC` `isDIGIT_LC_uvchr`
`isDIGIT_LC_utf8_safe` Returns a boolean indicating whether the specified character is a digit, analogous to `m/[[:digit:]]/`. Variants `isDIGIT_A` and `isDIGIT_L1` are identical to `isDIGIT`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isDIGIT (UV ch)
bool isDIGIT_A (UV ch)
bool isDIGIT_L1 (UV ch)
bool isDIGIT_uvchr (UV ch)
bool isDIGIT_utf8_safe (U8 * s, U8 * end)
bool isDIGIT_utf8 (U8 * s, U8 * end)
bool isDIGIT_LC (UV ch)
bool isDIGIT_LC_uvchr (UV ch)
bool isDIGIT_LC_utf8_safe(U8 * s, U8 *end)
```
`isGRAPH` `isGRAPH_A` `isGRAPH_L1` `isGRAPH_uvchr` `isGRAPH_utf8_safe` `isGRAPH_utf8` `isGRAPH_LC` `isGRAPH_LC_uvchr`
`isGRAPH_LC_utf8_safe` Returns a boolean indicating whether the specified character is a graphic character, analogous to `m/[[:graph:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isGRAPH (UV ch)
bool isGRAPH_A (UV ch)
bool isGRAPH_L1 (UV ch)
bool isGRAPH_uvchr (UV ch)
bool isGRAPH_utf8_safe (U8 * s, U8 * end)
bool isGRAPH_utf8 (U8 * s, U8 * end)
bool isGRAPH_LC (UV ch)
bool isGRAPH_LC_uvchr (UV ch)
bool isGRAPH_LC_utf8_safe(U8 * s, U8 *end)
```
`isIDCONT` `isIDCONT_A` `isIDCONT_L1` `isIDCONT_uvchr` `isIDCONT_utf8_safe` `isIDCONT_utf8` `isIDCONT_LC` `isIDCONT_LC_uvchr`
`isIDCONT_LC_utf8_safe` Returns a boolean indicating whether the specified character can be the second or succeeding character of an identifier. This is very close to, but not quite the same as the official Unicode property `XID_Continue`. The difference is that this returns true only if the input character also matches ["isWORDCHAR"](#isWORDCHAR). See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isIDCONT (UV ch)
bool isIDCONT_A (UV ch)
bool isIDCONT_L1 (UV ch)
bool isIDCONT_uvchr (UV ch)
bool isIDCONT_utf8_safe (U8 * s, U8 * end)
bool isIDCONT_utf8 (U8 * s, U8 * end)
bool isIDCONT_LC (UV ch)
bool isIDCONT_LC_uvchr (UV ch)
bool isIDCONT_LC_utf8_safe(U8 * s, U8 *end)
```
`isIDFIRST` `isIDFIRST_A` `isIDFIRST_L1` `isIDFIRST_uvchr` `isIDFIRST_utf8_safe` `isIDFIRST_utf8` `isIDFIRST_LC` `isIDFIRST_LC_uvchr`
`isIDFIRST_LC_utf8_safe` Returns a boolean indicating whether the specified character can be the first character of an identifier. This is very close to, but not quite the same as the official Unicode property `XID_Start`. The difference is that this returns true only if the input character also matches ["isWORDCHAR"](#isWORDCHAR). See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isIDFIRST (UV ch)
bool isIDFIRST_A (UV ch)
bool isIDFIRST_L1 (UV ch)
bool isIDFIRST_uvchr (UV ch)
bool isIDFIRST_utf8_safe (U8 * s, U8 * end)
bool isIDFIRST_utf8 (U8 * s, U8 * end)
bool isIDFIRST_LC (UV ch)
bool isIDFIRST_LC_uvchr (UV ch)
bool isIDFIRST_LC_utf8_safe(U8 * s, U8 *end)
```
`isLOWER` `isLOWER_A` `isLOWER_L1` `isLOWER_uvchr` `isLOWER_utf8_safe` `isLOWER_utf8` `isLOWER_LC` `isLOWER_LC_uvchr`
`isLOWER_LC_utf8_safe` Returns a boolean indicating whether the specified character is a lowercase character, analogous to `m/[[:lower:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants
```
bool isLOWER (UV ch)
bool isLOWER_A (UV ch)
bool isLOWER_L1 (UV ch)
bool isLOWER_uvchr (UV ch)
bool isLOWER_utf8_safe (U8 * s, U8 * end)
bool isLOWER_utf8 (U8 * s, U8 * end)
bool isLOWER_LC (UV ch)
bool isLOWER_LC_uvchr (UV ch)
bool isLOWER_LC_utf8_safe(U8 * s, U8 *end)
```
`isOCTAL` `isOCTAL_A`
`isOCTAL_L1` Returns a boolean indicating whether the specified character is an octal digit, [0-7]. The only two variants are `isOCTAL_A` and `isOCTAL_L1`; each is identical to `isOCTAL`.
```
bool isOCTAL(UV ch)
```
`isPRINT` `isPRINT_A` `isPRINT_L1` `isPRINT_uvchr` `isPRINT_utf8_safe` `isPRINT_utf8` `isPRINT_LC` `isPRINT_LC_uvchr`
`isPRINT_LC_utf8_safe` Returns a boolean indicating whether the specified character is a printable character, analogous to `m/[[:print:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isPRINT (UV ch)
bool isPRINT_A (UV ch)
bool isPRINT_L1 (UV ch)
bool isPRINT_uvchr (UV ch)
bool isPRINT_utf8_safe (U8 * s, U8 * end)
bool isPRINT_utf8 (U8 * s, U8 * end)
bool isPRINT_LC (UV ch)
bool isPRINT_LC_uvchr (UV ch)
bool isPRINT_LC_utf8_safe(U8 * s, U8 *end)
```
`isPSXSPC` `isPSXSPC_A` `isPSXSPC_L1` `isPSXSPC_uvchr` `isPSXSPC_utf8_safe` `isPSXSPC_utf8` `isPSXSPC_LC` `isPSXSPC_LC_uvchr`
`isPSXSPC_LC_utf8_safe` (short for Posix Space) Starting in 5.18, this is identical in all its forms to the corresponding `isSPACE()` macros. The locale forms of this macro are identical to their corresponding `isSPACE()` forms in all Perl releases. In releases prior to 5.18, the non-locale forms differ from their `isSPACE()` forms only in that the `isSPACE()` forms don't match a Vertical Tab, and the `isPSXSPC()` forms do. Otherwise they are identical. Thus this macro is analogous to what `m/[[:space:]]/` matches in a regular expression. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isPSXSPC (UV ch)
bool isPSXSPC_A (UV ch)
bool isPSXSPC_L1 (UV ch)
bool isPSXSPC_uvchr (UV ch)
bool isPSXSPC_utf8_safe (U8 * s, U8 * end)
bool isPSXSPC_utf8 (U8 * s, U8 * end)
bool isPSXSPC_LC (UV ch)
bool isPSXSPC_LC_uvchr (UV ch)
bool isPSXSPC_LC_utf8_safe(U8 * s, U8 *end)
```
`isPUNCT` `isPUNCT_A` `isPUNCT_L1` `isPUNCT_uvchr` `isPUNCT_utf8_safe` `isPUNCT_utf8` `isPUNCT_LC` `isPUNCT_LC_uvchr`
`isPUNCT_LC_utf8_safe` Returns a boolean indicating whether the specified character is a punctuation character, analogous to `m/[[:punct:]]/`. Note that the definition of what is punctuation isn't as straightforward as one might desire. See ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes) for details. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isPUNCT (UV ch)
bool isPUNCT_A (UV ch)
bool isPUNCT_L1 (UV ch)
bool isPUNCT_uvchr (UV ch)
bool isPUNCT_utf8_safe (U8 * s, U8 * end)
bool isPUNCT_utf8 (U8 * s, U8 * end)
bool isPUNCT_LC (UV ch)
bool isPUNCT_LC_uvchr (UV ch)
bool isPUNCT_LC_utf8_safe(U8 * s, U8 *end)
```
`isSPACE` `isSPACE_A` `isSPACE_L1` `isSPACE_uvchr` `isSPACE_utf8_safe` `isSPACE_utf8` `isSPACE_LC` `isSPACE_LC_uvchr`
`isSPACE_LC_utf8_safe` Returns a boolean indicating whether the specified character is a whitespace character. This is analogous to what `m/\s/` matches in a regular expression. Starting in Perl 5.18 this also matches what `m/[[:space:]]/` does. Prior to 5.18, only the locale forms of this macro (the ones with `LC` in their names) matched precisely what `m/[[:space:]]/` does. In those releases, the only difference, in the non-locale variants, was that `isSPACE()` did not match a vertical tab. (See ["isPSXSPC"](#isPSXSPC) for a macro that matches a vertical tab in all releases.) See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isSPACE (UV ch)
bool isSPACE_A (UV ch)
bool isSPACE_L1 (UV ch)
bool isSPACE_uvchr (UV ch)
bool isSPACE_utf8_safe (U8 * s, U8 * end)
bool isSPACE_utf8 (U8 * s, U8 * end)
bool isSPACE_LC (UV ch)
bool isSPACE_LC_uvchr (UV ch)
bool isSPACE_LC_utf8_safe(U8 * s, U8 *end)
```
`isUPPER` `isUPPER_A` `isUPPER_L1` `isUPPER_uvchr` `isUPPER_utf8_safe` `isUPPER_utf8` `isUPPER_LC` `isUPPER_LC_uvchr`
`isUPPER_LC_utf8_safe` Returns a boolean indicating whether the specified character is an uppercase character, analogous to `m/[[:upper:]]/`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isUPPER (UV ch)
bool isUPPER_A (UV ch)
bool isUPPER_L1 (UV ch)
bool isUPPER_uvchr (UV ch)
bool isUPPER_utf8_safe (U8 * s, U8 * end)
bool isUPPER_utf8 (U8 * s, U8 * end)
bool isUPPER_LC (UV ch)
bool isUPPER_LC_uvchr (UV ch)
bool isUPPER_LC_utf8_safe(U8 * s, U8 *end)
```
`isWORDCHAR` `isWORDCHAR_A` `isWORDCHAR_L1` `isWORDCHAR_uvchr` `isWORDCHAR_utf8_safe` `isWORDCHAR_utf8` `isWORDCHAR_LC` `isWORDCHAR_LC_uvchr` `isWORDCHAR_LC_utf8_safe` `isALNUM` `isALNUM_A` `isALNUM_LC`
`isALNUM_LC_uvchr` Returns a boolean indicating whether the specified character is a character that is a word character, analogous to what `m/\w/` and `m/[[:word:]]/` match in a regular expression. A word character is an alphabetic character, a decimal digit, a connecting punctuation character (such as an underscore), or a "mark" character that attaches to one of those (like some sort of accent). `isALNUM()` is a synonym provided for backward compatibility, even though a word character includes more than the standard C language meaning of alphanumeric. See the [top of this section](#Character-classification) for an explanation of the variants. `isWORDCHAR_A`, `isWORDCHAR_L1`, `isWORDCHAR_uvchr`, `isWORDCHAR_LC`, `isWORDCHAR_LC_uvchr`, `isWORDCHAR_LC_utf8`, and `isWORDCHAR_LC_utf8_safe` are also as described there, but additionally include the platform's native underscore.
```
bool isWORDCHAR (UV ch)
bool isWORDCHAR_A (UV ch)
bool isWORDCHAR_L1 (UV ch)
bool isWORDCHAR_uvchr (UV ch)
bool isWORDCHAR_utf8_safe (U8 * s, U8 * end)
bool isWORDCHAR_utf8 (U8 * s, U8 * end)
bool isWORDCHAR_LC (UV ch)
bool isWORDCHAR_LC_uvchr (UV ch)
bool isWORDCHAR_LC_utf8_safe(U8 * s, U8 *end)
bool isALNUM (UV ch)
bool isALNUM_A (UV ch)
bool isALNUM_LC (UV ch)
bool isALNUM_LC_uvchr (UV ch)
```
`isXDIGIT` `isXDIGIT_A` `isXDIGIT_L1` `isXDIGIT_uvchr` `isXDIGIT_utf8_safe` `isXDIGIT_utf8` `isXDIGIT_LC` `isXDIGIT_LC_uvchr`
`isXDIGIT_LC_utf8_safe` Returns a boolean indicating whether the specified character is a hexadecimal digit. In the ASCII range these are `[0-9A-Fa-f]`. Variants `isXDIGIT_A()` and `isXDIGIT_L1()` are identical to `isXDIGIT()`. See the [top of this section](#Character-classification) for an explanation of the variants.
```
bool isXDIGIT (UV ch)
bool isXDIGIT_A (UV ch)
bool isXDIGIT_L1 (UV ch)
bool isXDIGIT_uvchr (UV ch)
bool isXDIGIT_utf8_safe (U8 * s, U8 * end)
bool isXDIGIT_utf8 (U8 * s, U8 * end)
bool isXDIGIT_LC (UV ch)
bool isXDIGIT_LC_uvchr (UV ch)
bool isXDIGIT_LC_utf8_safe(U8 * s, U8 *end)
```
Compiler and Preprocessor information
--------------------------------------
`CPPLAST` This symbol is intended to be used along with `CPPRUN` in the same manner symbol `CPPMINUS` is used with `CPPSTDIN`. It contains either "-" or "".
`CPPMINUS` This symbol contains the second part of the string which will invoke the C preprocessor on the standard input and produce to standard output. This symbol will have the value "-" if `CPPSTDIN` needs a minus to specify standard input, otherwise the value is "".
`CPPRUN` This symbol contains the string which will invoke a C preprocessor on the standard input and produce to standard output. It needs to end with `CPPLAST`, after all other preprocessor flags have been specified. The main difference with `CPPSTDIN` is that this program will never be a pointer to a shell wrapper, i.e. it will be empty if no preprocessor is available directly to the user. Note that it may well be different from the preprocessor used to compile the C program.
`CPPSTDIN` This symbol contains the first part of the string which will invoke the C preprocessor on the standard input and produce to standard output. Typical value of "cc -E" or "*/lib/cpp*", but it can also call a wrapper. See `["CPPRUN"](#CPPRUN)`.
`HASATTRIBUTE_ALWAYS_INLINE` Can we handle `GCC` attribute for functions that should always be inlined.
`HASATTRIBUTE_DEPRECATED` Can we handle `GCC` attribute for marking deprecated `APIs`
`HASATTRIBUTE_FORMAT` Can we handle `GCC` attribute for checking printf-style formats
`HASATTRIBUTE_NONNULL` Can we handle `GCC` attribute for nonnull function parms.
`HASATTRIBUTE_NORETURN` Can we handle `GCC` attribute for functions that do not return
`HASATTRIBUTE_PURE` Can we handle `GCC` attribute for pure functions
`HASATTRIBUTE_UNUSED` Can we handle `GCC` attribute for unused variables and arguments
`HASATTRIBUTE_WARN_UNUSED_RESULT` Can we handle `GCC` attribute for warning on unused results
`HAS_BUILTIN_ADD_OVERFLOW` This symbol, if defined, indicates that the compiler supports `__builtin_add_overflow` for adding integers with overflow checks.
`HAS_BUILTIN_CHOOSE_EXPR` Can we handle `GCC` builtin for compile-time ternary-like expressions
`HAS_BUILTIN_EXPECT` Can we handle `GCC` builtin for telling that certain values are more likely
`HAS_BUILTIN_MUL_OVERFLOW` This symbol, if defined, indicates that the compiler supports `__builtin_mul_overflow` for multiplying integers with overflow checks.
`HAS_BUILTIN_SUB_OVERFLOW` This symbol, if defined, indicates that the compiler supports `__builtin_sub_overflow` for subtracting integers with overflow checks.
`HAS_C99_VARIADIC_MACROS` If defined, the compiler supports C99 variadic macros.
`HAS_STATIC_INLINE` This symbol, if defined, indicates that the C compiler supports C99-style static inline. That is, the function can't be called from another translation unit.
`MEM_ALIGNBYTES` This symbol contains the number of bytes required to align a double, or a long double when applicable. Usual values are 2, 4 and 8. The default is eight, for safety. For cross-compiling or multiarch support, Configure will set a minimum of 8.
`PERL_STATIC_INLINE` This symbol gives the best-guess incantation to use for static inline functions. If `HAS_STATIC_INLINE` is defined, this will give C99-style inline. If `HAS_STATIC_INLINE` is not defined, this will give a plain 'static'. It will always be defined to something that gives static linkage. Possibilities include
```
static inline (c99)
static __inline__ (gcc -ansi)
static __inline (MSVC)
static _inline (older MSVC)
static (c89 compilers)
```
`PERL_THREAD_LOCAL` This symbol, if defined, gives a linkage specification for thread-local storage. For example, for a C11 compiler this will be `_Thread_local`. Beware, some compilers are sensitive to the C language standard they are told to parse. For example, suncc defaults to C11, so our probe will report that `_Thread_local` can be used. However, if the -std=c99 is later added to the compiler flags, then `_Thread_local` will become a syntax error. Hence it is important for these flags to be consistent between probing and use.
`U32_ALIGNMENT_REQUIRED` This symbol, if defined, indicates that you must access character data through U32-aligned pointers.
Compiler directives
--------------------
`ASSUME` `ASSUME` is like `assert()`, but it has a benefit in a release build. It is a hint to a compiler about a statement of fact in a function call free expression, which allows the compiler to generate better machine code. In a debug build, `ASSUME(x)` is a synonym for `assert(x)`. `ASSUME(0)` means the control path is unreachable. In a for loop, `ASSUME` can be used to hint that a loop will run at least X times. `ASSUME` is based off MSVC's `__assume` intrinsic function, see its documents for more details.
```
ASSUME(bool expr)
```
`dNOOP` Declare nothing; typically used as a placeholder to replace something that used to declare something. Works on compilers that require declarations before any code.
```
dNOOP;
```
`END_EXTERN_C` When not compiling using C++, expands to nothing. Otherwise ends a section of code already begun by a `["START\_EXTERN\_C"](#START_EXTERN_C)`.
```
END_EXTERN_C
```
`EXTERN_C` When not compiling using C++, expands to nothing. Otherwise is used in a declaration of a function to indicate the function should have external C linkage. This is required for things to work for just about all functions with external linkage compiled into perl. Often, you can use `["START\_EXTERN\_C"](#START_EXTERN_C)` ... `["END\_EXTERN\_C"](#END_EXTERN_C)` blocks surrounding all your code that you need to have this linkage.
Example usage:
```
EXTERN_C int flock(int fd, int op);
```
`LIKELY` Returns the input unchanged, but at the same time it gives a branch prediction hint to the compiler that this condition is likely to be true.
```
LIKELY(bool expr)
```
`NOOP` Do nothing; typically used as a placeholder to replace something that used to do something.
```
NOOP;
```
`PERL_UNUSED_ARG` This is used to suppress compiler warnings that a parameter to a function is not used. This situation can arise, for example, when a parameter is needed under some configuration conditions, but not others, so that C preprocessor conditional compilation causes it be used just some times.
```
PERL_UNUSED_ARG(void x);
```
`PERL_UNUSED_CONTEXT` This is used to suppress compiler warnings that the thread context parameter to a function is not used. This situation can arise, for example, when a C preprocessor conditional compilation causes it be used just some times.
```
PERL_UNUSED_CONTEXT;
```
`PERL_UNUSED_DECL` Tells the compiler that the parameter in the function prototype just before it is not necessarily expected to be used in the function. Not that many compilers understand this, so this should only be used in cases where `["PERL\_UNUSED\_ARG"](#PERL_UNUSED_ARG)` can't conveniently be used.
Example usage:
```
Signal_t
Perl_perly_sighandler(int sig, Siginfo_t *sip PERL_UNUSED_DECL,
void *uap PERL_UNUSED_DECL, bool safe)
```
`PERL_UNUSED_RESULT` This macro indicates to discard the return value of the function call inside it, *e.g.*,
```
PERL_UNUSED_RESULT(foo(a, b))
```
The main reason for this is that the combination of `gcc -Wunused-result` (part of `-Wall`) and the `__attribute__((warn_unused_result))` cannot be silenced with casting to `void`. This causes trouble when the system header files use the attribute.
Use `PERL_UNUSED_RESULT` sparingly, though, since usually the warning is there for a good reason: you might lose success/failure information, or leak resources, or changes in resources.
But sometimes you just want to ignore the return value, *e.g.*, on codepaths soon ending up in abort, or in "best effort" attempts, or in situations where there is no good way to handle failures.
Sometimes `PERL_UNUSED_RESULT` might not be the most natural way: another possibility is that you can capture the return value and use `["PERL\_UNUSED\_VAR"](#PERL_UNUSED_VAR)` on that.
```
PERL_UNUSED_RESULT(void x)
```
`PERL_UNUSED_VAR` This is used to suppress compiler warnings that the variable *x* is not used. This situation can arise, for example, when a C preprocessor conditional compilation causes it be used just some times.
```
PERL_UNUSED_VAR(void x);
```
`PERL_USE_GCC_BRACE_GROUPS` This C pre-processor value, if defined, indicates that it is permissible to use the GCC brace groups extension. This extension, of the form
```
({ statement ... })
```
turns the block consisting of *statements ...* into an expression with a value, unlike plain C language blocks. This can present optimization possibilities, **BUT** you generally need to specify an alternative in case this ability doesn't exist or has otherwise been forbidden.
Example usage:
```
#ifdef PERL_USE_GCC_BRACE_GROUPS
...
#else
...
#endif
```
`START_EXTERN_C` When not compiling using C++, expands to nothing. Otherwise begins a section of code in which every function will effectively have `["EXTERN\_C"](#EXTERN_C)` applied to it, that is to have external C linkage. The section is ended by a `["END\_EXTERN\_C"](#END_EXTERN_C)`.
```
START_EXTERN_C
```
`STATIC` Described in <perlguts>.
`STMT_START`
`STMT_END` This allows a series of statements in a macro to be used as a single statement, as in
```
if (x) STMT_START { ... } STMT_END else ...
```
Note that you can't return a value out of them, which limits their utility. But see `["PERL\_USE\_GCC\_BRACE\_GROUPS"](#PERL_USE_GCC_BRACE_GROUPS)`.
`UNLIKELY` Returns the input unchanged, but at the same time it gives a branch prediction hint to the compiler that this condition is likely to be false.
```
UNLIKELY(bool expr)
```
`__ASSERT_` This is a helper macro to avoid preprocessor issues, replaced by nothing unless under DEBUGGING, where it expands to an assert of its argument, followed by a comma (hence the comma operator). If we just used a straight assert(), we would get a comma with nothing before it when not DEBUGGING.
```
__ASSERT_(bool expr)
```
Compile-time scope hooks
-------------------------
`BhkDISABLE` NOTE: `BhkDISABLE` is **experimental** and may change or be removed without notice.
Temporarily disable an entry in this BHK structure, by clearing the appropriate flag. `which` is a preprocessor token indicating which entry to disable.
```
void BhkDISABLE(BHK *hk, which)
```
`BhkENABLE` NOTE: `BhkENABLE` is **experimental** and may change or be removed without notice.
Re-enable an entry in this BHK structure, by setting the appropriate flag. `which` is a preprocessor token indicating which entry to enable. This will assert (under -DDEBUGGING) if the entry doesn't contain a valid pointer.
```
void BhkENABLE(BHK *hk, which)
```
`BhkENTRY_set` NOTE: `BhkENTRY_set` is **experimental** and may change or be removed without notice.
Set an entry in the BHK structure, and set the flags to indicate it is valid. `which` is a preprocessing token indicating which entry to set. The type of `ptr` depends on the entry.
```
void BhkENTRY_set(BHK *hk, which, void *ptr)
```
`blockhook_register` NOTE: `blockhook_register` is **experimental** and may change or be removed without notice.
Register a set of hooks to be called when the Perl lexical scope changes at compile time. See ["Compile-time scope hooks" in perlguts](perlguts#Compile-time-scope-hooks).
NOTE: `blockhook_register` must be explicitly called as `Perl_blockhook_register` with an `aTHX_` parameter.
```
void Perl_blockhook_register(pTHX_ BHK *hk)
```
Concurrency
-----------
`aTHX` Described in <perlguts>.
`aTHX_` Described in <perlguts>.
`CPERLscope` `**DEPRECATED!**` It is planned to remove `CPERLscope` from a future release of Perl. Do not use it for new code; remove it from existing code.
Now a no-op.
```
void CPERLscope(void x)
```
`dTHR` Described in <perlguts>.
`dTHX` Described in <perlguts>.
`dTHXa` On threaded perls, set `pTHX` to `a`; on unthreaded perls, do nothing
`dTHXoa` Now a synonym for `["dTHXa"](#dTHXa)`.
`dVAR` This is now a synonym for dNOOP: declare nothing
`GETENV_PRESERVES_OTHER_THREAD` This symbol, if defined, indicates that the getenv system call doesn't zap the static buffer of `getenv()` in a different thread. The typical `getenv()` implementation will return a pointer to the proper position in \*\*environ. But some may instead copy them to a static buffer in `getenv()`. If there is a per-thread instance of that buffer, or the return points to \*\*environ, then a many-reader/1-writer mutex will work; otherwise an exclusive locking mutex is required to prevent races.
`HAS_PTHREAD_ATFORK` This symbol, if defined, indicates that the `pthread_atfork` routine is available to setup fork handlers.
`HAS_PTHREAD_ATTR_SETSCOPE` This symbol, if defined, indicates that the `pthread_attr_setscope` system call is available to set the contention scope attribute of a thread attribute object.
`HAS_PTHREAD_YIELD` This symbol, if defined, indicates that the `pthread_yield` routine is available to yield the execution of the current thread. `sched_yield` is preferable to `pthread_yield`.
`HAS_SCHED_YIELD` This symbol, if defined, indicates that the `sched_yield` routine is available to yield the execution of the current thread. `sched_yield` is preferable to `pthread_yield`.
`I_MACH_CTHREADS` This symbol, if defined, indicates to the C program that it should include *mach/cthreads.h*.
```
#ifdef I_MACH_CTHREADS
#include <mach_cthreads.h>
#endif
```
`I_PTHREAD` This symbol, if defined, indicates to the C program that it should include *pthread.h*.
```
#ifdef I_PTHREAD
#include <pthread.h>
#endif
```
`MULTIPLICITY` This symbol, if defined, indicates that Perl should be built to use multiplicity.
`OLD_PTHREADS_API` This symbol, if defined, indicates that Perl should be built to use the old draft `POSIX` threads `API`.
`OLD_PTHREAD_CREATE_JOINABLE` This symbol, if defined, indicates how to create pthread in joinable (aka undetached) state. `NOTE`: not defined if *pthread.h* already has defined `PTHREAD_CREATE_JOINABLE` (the new version of the constant). If defined, known values are `PTHREAD_CREATE_UNDETACHED` and `__UNDETACHED`.
`PERL_IMPLICIT_CONTEXT` Described in <perlguts>.
`pTHX` Described in <perlguts>.
`pTHX_` Described in <perlguts>.
`SCHED_YIELD` This symbol defines the way to yield the execution of the current thread. Known ways are `sched_yield`, `pthread_yield`, and `pthread_yield` with `NULL`.
COPs and Hint Hashes
---------------------
`cop_fetch_label` NOTE: `cop_fetch_label` is **experimental** and may change or be removed without notice.
Returns the label attached to a cop, and stores its length in bytes into `*len`. Upon return, `*flags` will be set to either `SVf_UTF8` or 0.
Alternatively, use the macro `["CopLABEL\_len\_flags"](#CopLABEL_len_flags)`; or if you don't need to know if the label is UTF-8 or not, the macro `["CopLABEL\_len"](#CopLABEL_len)`; or if you additionally dont need to know the length, `["CopLABEL"](#CopLABEL)`.
```
const char * cop_fetch_label(COP *const cop, STRLEN *len,
U32 *flags)
```
`CopFILE` Returns the name of the file associated with the `COP` `c`
```
const char * CopFILE(const COP * c)
```
`CopFILEAV` Returns the AV associated with the `COP` `c`, creating it if necessary.
```
AV * CopFILEAV(const COP * c)
```
`CopFILEAVn` Returns the AV associated with the `COP` `c`, returning NULL if it doesn't already exist.
```
AV * CopFILEAVn(const COP * c)
```
`CopFILEGV` Returns the GV associated with the `COP` `c`
```
GV * CopFILEGV(const COP * c)
```
`CopFILEGV_set` Available only on unthreaded perls. Makes `pv` the name of the file associated with the `COP` `c`
```
void CopFILEGV_set(COP * c, GV * gv)
```
`CopFILE_set` Makes `pv` the name of the file associated with the `COP` `c`
```
void CopFILE_set(COP * c, const char * pv)
```
`CopFILESV` Returns the SV associated with the `COP` `c`
```
SV * CopFILESV(const COP * c)
```
`cophh_2hv` NOTE: `cophh_2hv` is **experimental** and may change or be removed without notice.
Generates and returns a standard Perl hash representing the full set of key/value pairs in the cop hints hash `cophh`. `flags` is currently unused and must be zero.
```
HV * cophh_2hv(const COPHH *cophh, U32 flags)
```
`cophh_copy` NOTE: `cophh_copy` is **experimental** and may change or be removed without notice.
Make and return a complete copy of the cop hints hash `cophh`.
```
COPHH * cophh_copy(COPHH *cophh)
```
`cophh_delete_pvn` `cophh_delete_pv` `cophh_delete_pvs`
`cophh_delete_sv` NOTE: all these forms are **experimental** and may change or be removed without notice.
These delete a key and its associated value from the cop hints hash `cophh`, and return the modified hash. The returned hash pointer is in general not the same as the hash pointer that was passed in. The input hash is consumed by the function, and the pointer to it must not be subsequently used. Use ["cophh\_copy"](#cophh_copy) if you need both hashes.
The forms differ in how the key is specified. In all forms, the key is pointed to by `key`. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
COPHH * cophh_delete_pvn(COPHH *cophh, const char *key,
STRLEN keylen, U32 hash, U32 flags)
COPHH * cophh_delete_pv (COPHH *cophh, const char *key, U32 hash,
U32 flags)
COPHH * cophh_delete_pvs(COPHH *cophh, "key", U32 flags)
COPHH * cophh_delete_sv (COPHH *cophh, SV *key, U32 hash,
U32 flags)
```
`cophh_exists_pvn` NOTE: `cophh_exists_pvn` is **experimental** and may change or be removed without notice.
These look up the hint entry in the cop `cop` with the key specified by `key` (and `keylen` in the `pvn` form), returning true if a value exists, and false otherwise.
The forms differ in how the key is specified. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
bool cophh_exists_pvn(const COPHH *cophh, const char *key,
STRLEN keylen, U32 hash, U32 flags)
```
`cophh_fetch_pvn` `cophh_fetch_pv` `cophh_fetch_pvs`
`cophh_fetch_sv` NOTE: all these forms are **experimental** and may change or be removed without notice.
These look up the entry in the cop hints hash `cophh` with the key specified by `key` (and `keylen` in the `pvn` form), returning that value as a mortal scalar copy, or `&PL_sv_placeholder` if there is no value associated with the key.
The forms differ in how the key is specified. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
SV * cophh_fetch_pvn(const COPHH *cophh, const char *key,
STRLEN keylen, U32 hash, U32 flags)
SV * cophh_fetch_pv (const COPHH *cophh, const char *key,
U32 hash, U32 flags)
SV * cophh_fetch_pvs(const COPHH *cophh, "key", U32 flags)
SV * cophh_fetch_sv (const COPHH *cophh, SV *key, U32 hash,
U32 flags)
```
`cophh_free` NOTE: `cophh_free` is **experimental** and may change or be removed without notice.
Discard the cop hints hash `cophh`, freeing all resources associated with it.
```
void cophh_free(COPHH *cophh)
```
`cophh_new_empty` NOTE: `cophh_new_empty` is **experimental** and may change or be removed without notice.
Generate and return a fresh cop hints hash containing no entries.
```
COPHH * cophh_new_empty()
```
`cophh_store_pvn` `cophh_store_pv` `cophh_store_pvs`
`cophh_store_sv` NOTE: all these forms are **experimental** and may change or be removed without notice.
These store a value, associated with a key, in the cop hints hash `cophh`, and return the modified hash. The returned hash pointer is in general not the same as the hash pointer that was passed in. The input hash is consumed by the function, and the pointer to it must not be subsequently used. Use ["cophh\_copy"](#cophh_copy) if you need both hashes.
`value` is the scalar value to store for this key. `value` is copied by these functions, which thus do not take ownership of any reference to it, and hence later changes to the scalar will not be reflected in the value visible in the cop hints hash. Complex types of scalar will not be stored with referential integrity, but will be coerced to strings.
The forms differ in how the key is specified. In all forms, the key is pointed to by `key`. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
COPHH * cophh_store_pvn(COPHH *cophh, const char *key,
STRLEN keylen, U32 hash, SV *value,
U32 flags)
COPHH * cophh_store_pv (COPHH *cophh, const char *key, U32 hash,
SV *value, U32 flags)
COPHH * cophh_store_pvs(COPHH *cophh, "key", SV *value,
U32 flags)
COPHH * cophh_store_sv (COPHH *cophh, SV *key, U32 hash,
SV *value, U32 flags)
```
`cop_hints_2hv` Generates and returns a standard Perl hash representing the full set of hint entries in the cop `cop`. `flags` is currently unused and must be zero.
```
HV * cop_hints_2hv(const COP *cop, U32 flags)
```
`cop_hints_exists_pvn` `cop_hints_exists_pv` `cop_hints_exists_pvs`
`cop_hints_exists_sv` These look up the hint entry in the cop `cop` with the key specified by `key` (and `keylen` in the `pvn` form), returning true if a value exists, and false otherwise.
The forms differ in how the key is specified. In all forms, the key is pointed to by `key`. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
bool cop_hints_exists_pvn(const COP *cop, const char *key,
STRLEN keylen, U32 hash, U32 flags)
bool cop_hints_exists_pv (const COP *cop, const char *key,
U32 hash, U32 flags)
bool cop_hints_exists_pvs(const COP *cop, "key", U32 flags)
bool cop_hints_exists_sv (const COP *cop, SV *key, U32 hash,
U32 flags)
```
`cop_hints_fetch_pvn` `cop_hints_fetch_pv` `cop_hints_fetch_pvs`
`cop_hints_fetch_sv` These look up the hint entry in the cop `cop` with the key specified by `key` (and `keylen` in the `pvn` form), returning that value as a mortal scalar copy, or `&PL_sv_placeholder` if there is no value associated with the key.
The forms differ in how the key is specified. In the plain `pv` form, the key is a C language NUL-terminated string. In the `pvs` form, the key is a C language string literal. In the `pvn` form, an additional parameter, `keylen`, specifies the length of the string, which hence, may contain embedded-NUL characters. In the `sv` form, `*key` is an SV, and the key is the PV extracted from that. using `["SvPV\_const"](#SvPV_const)`.
`hash` is a precomputed hash of the key string, or zero if it has not been precomputed. This parameter is omitted from the `pvs` form, as it is computed automatically at compile time.
The only flag currently used from the `flags` parameter is `COPHH_KEY_UTF8`. It is illegal to set this in the `sv` form. In the `pv*` forms, it specifies whether the key octets are interpreted as UTF-8 (if set) or as Latin-1 (if cleared). The `sv` form uses the underlying SV to determine the UTF-8ness of the octets.
```
SV * cop_hints_fetch_pvn(const COP *cop, const char *key,
STRLEN keylen, U32 hash, U32 flags)
SV * cop_hints_fetch_pv (const COP *cop, const char *key,
U32 hash, U32 flags)
SV * cop_hints_fetch_pvs(const COP *cop, "key", U32 flags)
SV * cop_hints_fetch_sv (const COP *cop, SV *key, U32 hash,
U32 flags)
```
`CopLABEL` `CopLABEL_len`
`CopLABEL_len_flags` These return the label attached to a cop.
`CopLABEL_len` and `CopLABEL_len_flags` additionally store the number of bytes comprising the returned label into `*len`.
`CopLABEL_len_flags` additionally returns the UTF-8ness of the returned label, by setting `*flags` to 0 or `SVf_UTF8`.
```
const char * CopLABEL (COP *const cop)
const char * CopLABEL_len (COP *const cop, STRLEN *len)
const char * CopLABEL_len_flags(COP *const cop, STRLEN *len,
U32 *flags)
```
`CopLINE` Returns the line number in the source code associated with the `COP` `c`
```
STRLEN CopLINE(const COP * c)
```
`CopSTASH` Returns the stash associated with `c`.
```
HV * CopSTASH(const COP * c)
```
`CopSTASH_eq` Returns a boolean as to whether or not `hv` is the stash associated with `c`.
```
bool CopSTASH_eq(const COP * c, const HV * hv)
```
`CopSTASHPV` Returns the package name of the stash associated with `c`, or `NULL` if no associated stash
```
char * CopSTASHPV(const COP * c)
```
`CopSTASHPV_set` Set the package name of the stash associated with `c`, to the NUL-terminated C string `p`, creating the package if necessary.
```
void CopSTASHPV_set(COP * c, const char * pv)
```
`CopSTASH_set` Set the stash associated with `c` to `hv`.
```
bool CopSTASH_set(COP * c, HV * hv)
```
`cop_store_label` NOTE: `cop_store_label` is **experimental** and may change or be removed without notice.
Save a label into a `cop_hints_hash`. You need to set flags to `SVf_UTF8` for a UTF-8 label. Any other flag is ignored.
```
void cop_store_label(COP *const cop, const char *label,
STRLEN len, U32 flags)
```
`PERL_SI` Use this typedef to declare variables that are to hold `struct stackinfo`.
`PL_curcop` The currently active COP (control op) roughly representing the current statement in the source.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
COP* PL_curcop
```
Custom Operators
-----------------
`custom_op_desc` `**DEPRECATED!**` It is planned to remove `custom_op_desc` from a future release of Perl. Do not use it for new code; remove it from existing code.
Return the description of a given custom op. This was once used by the `OP_DESC` macro, but is no longer: it has only been kept for compatibility, and should not be used.
```
const char * custom_op_desc(const OP *o)
```
`custom_op_name` `**DEPRECATED!**` It is planned to remove `custom_op_name` from a future release of Perl. Do not use it for new code; remove it from existing code.
Return the name for a given custom op. This was once used by the `OP_NAME` macro, but is no longer: it has only been kept for compatibility, and should not be used.
```
const char * custom_op_name(const OP *o)
```
`custom_op_register` Register a custom op. See ["Custom Operators" in perlguts](perlguts#Custom-Operators).
NOTE: `custom_op_register` must be explicitly called as `Perl_custom_op_register` with an `aTHX_` parameter.
```
void Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr,
const XOP *xop)
```
`Perl_custom_op_xop` Return the XOP structure for a given custom op. This macro should be considered internal to `OP_NAME` and the other access macros: use them instead. This macro does call a function. Prior to 5.19.6, this was implemented as a function.
```
const XOP * Perl_custom_op_xop(pTHX_ const OP *o)
```
`XopDISABLE` Temporarily disable a member of the XOP, by clearing the appropriate flag.
```
void XopDISABLE(XOP *xop, which)
```
`XopENABLE` Reenable a member of the XOP which has been disabled.
```
void XopENABLE(XOP *xop, which)
```
`XopENTRY` Return a member of the XOP structure. `which` is a cpp token indicating which entry to return. If the member is not set this will return a default value. The return type depends on `which`. This macro evaluates its arguments more than once. If you are using `Perl_custom_op_xop` to retrieve a `XOP *` from a `OP *`, use the more efficient ["XopENTRYCUSTOM"](#XopENTRYCUSTOM) instead.
```
XopENTRY(XOP *xop, which)
```
`XopENTRYCUSTOM` Exactly like `XopENTRY(XopENTRY(Perl_custom_op_xop(aTHX_ o), which)` but more efficient. The `which` parameter is identical to ["XopENTRY"](#XopENTRY).
```
XopENTRYCUSTOM(const OP *o, which)
```
`XopENTRY_set` Set a member of the XOP structure. `which` is a cpp token indicating which entry to set. See ["Custom Operators" in perlguts](perlguts#Custom-Operators) for details about the available members and how they are used. This macro evaluates its argument more than once.
```
void XopENTRY_set(XOP *xop, which, value)
```
`XopFLAGS` Return the XOP's flags.
```
U32 XopFLAGS(XOP *xop)
```
CV Handling
------------
This section documents functions to manipulate CVs which are code-values, meaning subroutines. For more information, see <perlguts>.
`caller_cx` The XSUB-writer's equivalent of [caller()](perlfunc#caller). The returned `PERL_CONTEXT` structure can be interrogated to find all the information returned to Perl by `caller`. Note that XSUBs don't get a stack frame, so `caller_cx(0, NULL)` will return information for the immediately-surrounding Perl code.
This function skips over the automatic calls to `&DB::sub` made on the behalf of the debugger. If the stack frame requested was a sub called by `DB::sub`, the return value will be the frame for the call to `DB::sub`, since that has the correct line number/etc. for the call site. If *dbcxp* is non-`NULL`, it will be set to a pointer to the frame for the sub call itself.
```
const PERL_CONTEXT * caller_cx(I32 level,
const PERL_CONTEXT **dbcxp)
```
`CvDEPTH` Returns the recursion level of the CV `sv`. Hence >= 2 indicates we are in a recursive call.
```
I32 * CvDEPTH(const CV * const sv)
```
`CvGV` Returns the GV associated with the CV `sv`, reifying it if necessary.
```
GV * CvGV(CV *sv)
```
`CvSTASH` Returns the stash of the CV. A stash is the symbol table hash, containing the package-scoped variables in the package where the subroutine was defined. For more information, see <perlguts>.
This also has a special use with XS AUTOLOAD subs. See ["Autoloading with XSUBs" in perlguts](perlguts#Autoloading-with-XSUBs).
```
HV* CvSTASH(CV* cv)
```
`find_runcv` Locate the CV corresponding to the currently executing sub or eval. If `db_seqp` is non\_null, skip CVs that are in the DB package and populate `*db_seqp` with the cop sequence number at the point that the DB:: code was entered. (This allows debuggers to eval in the scope of the breakpoint rather than in the scope of the debugger itself.)
```
CV* find_runcv(U32 *db_seqp)
```
`get_cv` `get_cvs`
`get_cvn_flags` These return the CV of the specified Perl subroutine. `flags` are passed to `gv_fetchpvn_flags`. If `GV_ADD` is set and the Perl subroutine does not exist then it will be declared (which has the same effect as saying `sub name;`). If `GV_ADD` is not set and the subroutine does not exist, then NULL is returned.
The forms differ only in how the subroutine is specified.. With `get_cvs`, the name is a literal C string, enclosed in double quotes. With `get_cv`, the name is given by the `name` parameter, which must be a NUL-terminated C string. With `get_cvn_flags`, the name is also given by the `name` parameter, but it is a Perl string (possibly containing embedded NUL bytes), and its length in bytes is contained in the `len` parameter.
NOTE: the `perl_get_cv()` form is **deprecated**.
NOTE: the `perl_get_cvs()` form is **deprecated**.
NOTE: the `perl_get_cvn_flags()` form is **deprecated**.
```
CV* get_cv (const char* name, I32 flags)
CV * get_cvs ("string", I32 flags)
CV* get_cvn_flags(const char* name, STRLEN len, I32 flags)
```
`Nullcv` `**DEPRECATED!**` It is planned to remove `Nullcv` from a future release of Perl. Do not use it for new code; remove it from existing code.
Null CV pointer.
(deprecated - use `(CV *)NULL` instead)
`SvAMAGIC_off` Indicate that `sv` has overloading (active magic) disabled.
```
void SvAMAGIC_off(SV *sv)
```
`SvAMAGIC_on` Indicate that `sv` has overloading (active magic) enabled.
```
void SvAMAGIC_on(SV *sv)
```
Debugging
---------
`deb`
`deb_nocontext` When perl is compiled with `-DDEBUGGING`, this prints to STDERR the information given by the arguments, prefaced by the name of the file containing the script causing the call, and the line number within that file.
If the `v` (verbose) debugging option is in effect, the process id is also printed.
The two forms differ only in that `deb_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
NOTE: `deb` must be explicitly called as `Perl_deb` with an `aTHX_` parameter.
```
void Perl_deb (pTHX_ const char* pat, ...)
void deb_nocontext(const char* pat, ...)
```
`debstack` Dump the current stack
```
I32 debstack()
```
`dump_all` Dumps the entire optree of the current program starting at `PL_main_root` to `STDERR`. Also dumps the optrees for all visible subroutines in `PL_defstash`.
```
void dump_all()
```
`dump_c_backtrace` Dumps the C backtrace to the given `fp`.
Returns true if a backtrace could be retrieved, false if not.
```
bool dump_c_backtrace(PerlIO* fp, int max_depth, int skip)
```
`dump_eval` Described in <perlguts>.
```
void dump_eval()
```
`dump_form` Dumps the contents of the format contained in the GV `gv` to `STDERR`, or a message that one doesn't exist.
```
void dump_form(const GV* gv)
```
`dump_packsubs` Dumps the optrees for all visible subroutines in `stash`.
```
void dump_packsubs(const HV* stash)
```
`dump_sub` Described in <perlguts>.
```
void dump_sub(const GV* gv)
```
`get_c_backtrace_dump` Returns a SV containing a dump of `depth` frames of the call stack, skipping the `skip` innermost ones. `depth` of 20 is usually enough.
The appended output looks like:
```
...
1 10e004812:0082 Perl_croak util.c:1716 /usr/bin/perl
2 10df8d6d2:1d72 perl_parse perl.c:3975 /usr/bin/perl
...
```
The fields are tab-separated. The first column is the depth (zero being the innermost non-skipped frame). In the hex:offset, the hex is where the program counter was in `S_parse_body`, and the :offset (might be missing) tells how much inside the `S_parse_body` the program counter was.
The `util.c:1716` is the source code file and line number.
The */usr/bin/perl* is obvious (hopefully).
Unknowns are `"-"`. Unknowns can happen unfortunately quite easily: if the platform doesn't support retrieving the information; if the binary is missing the debug information; if the optimizer has transformed the code by for example inlining.
```
SV* get_c_backtrace_dump(int max_depth, int skip)
```
`gv_dump` Dump the name and, if they differ, the effective name of the GV `gv` to `STDERR`.
```
void gv_dump(GV* gv)
```
`HAS_BACKTRACE` This symbol, if defined, indicates that the `backtrace()` routine is available to get a stack trace. The *execinfo.h* header must be included to use this routine.
`magic_dump` Dumps the contents of the MAGIC `mg` to `STDERR`.
```
void magic_dump(const MAGIC *mg)
```
`op_class` Given an op, determine what type of struct it has been allocated as. Returns one of the OPclass enums, such as OPclass\_LISTOP.
```
OPclass op_class(const OP *o)
```
`op_dump` Dumps the optree starting at OP `o` to `STDERR`.
```
void op_dump(const OP *o)
```
`PL_op` Described in <perlhacktips>.
`PL_runops` Described in <perlguts>.
`PL_sv_serial` Described in <perlhacktips>.
`pmop_dump` Dump an OP that is related to Pattern Matching, such as `s/foo/bar/`; these require special handling.
```
void pmop_dump(PMOP* pm)
```
`sv_dump` Dumps the contents of an SV to the `STDERR` filehandle.
For an example of its output, see <Devel::Peek>.
```
void sv_dump(SV* sv)
```
`vdeb` This is like `["deb"](#deb)`, but `args` are an encapsulated argument list.
```
void vdeb(const char* pat, va_list* args)
```
Display functions
------------------
`form`
`form_nocontext` These take a sprintf-style format pattern and conventional (non-SV) arguments and return the formatted string.
```
(char *) Perl_form(pTHX_ const char* pat, ...)
```
can be used any place a string (char \*) is required:
```
char * s = Perl_form("%d.%d",major,minor);
```
They use a single (per-thread) private buffer so if you want to format several strings you must explicitly copy the earlier strings away (and free the copies when you are done).
The two forms differ only in that `form_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
NOTE: `form` must be explicitly called as `Perl_form` with an `aTHX_` parameter.
```
char* Perl_form (pTHX_ const char* pat, ...)
char* form_nocontext(const char* pat, ...)
```
`mess`
`mess_nocontext` These take a sprintf-style format pattern and argument list, which are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for `["mess\_sv"](#mess_sv)`.
Normally, the resulting message is returned in a new mortal SV. But during global destruction a single SV may be shared between uses of this function.
The two forms differ only in that `mess_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
NOTE: `mess` must be explicitly called as `Perl_mess` with an `aTHX_` parameter.
```
SV* Perl_mess (pTHX_ const char* pat, ...)
SV* mess_nocontext(const char* pat, ...)
```
`mess_sv` Expands a message, intended for the user, to include an indication of the current location in the code, if the message does not already appear to be complete.
`basemsg` is the initial message or object. If it is a reference, it will be used as-is and will be the result of this function. Otherwise it is used as a string, and if it already ends with a newline, it is taken to be complete, and the result of this function will be the same string. If the message does not end with a newline, then a segment such as `at foo.pl line 37` will be appended, and possibly other clauses indicating the current state of execution. The resulting message will end with a dot and a newline.
Normally, the resulting message is returned in a new mortal SV. During global destruction a single SV may be shared between uses of this function. If `consume` is true, then the function is permitted (but not required) to modify and return `basemsg` instead of allocating a new SV.
```
SV* mess_sv(SV* basemsg, bool consume)
```
`pv_display` Similar to
```
pv_escape(dsv,pv,cur,pvlim,PERL_PV_ESCAPE_QUOTE);
```
except that an additional "\0" will be appended to the string when len > cur and pv[cur] is "\0".
Note that the final string may be up to 7 chars longer than pvlim.
```
char* pv_display(SV *dsv, const char *pv, STRLEN cur, STRLEN len,
STRLEN pvlim)
```
`pv_escape` Escapes at most the first `count` chars of `pv` and puts the results into `dsv` such that the size of the escaped string will not exceed `max` chars and will not contain any incomplete escape sequences. The number of bytes escaped will be returned in the `STRLEN *escaped` parameter if it is not null. When the `dsv` parameter is null no escaping actually occurs, but the number of bytes that would be escaped were it not null will be calculated.
If flags contains `PERL_PV_ESCAPE_QUOTE` then any double quotes in the string will also be escaped.
Normally the SV will be cleared before the escaped string is prepared, but when `PERL_PV_ESCAPE_NOCLEAR` is set this will not occur.
If `PERL_PV_ESCAPE_UNI` is set then the input string is treated as UTF-8 if `PERL_PV_ESCAPE_UNI_DETECT` is set then the input string is scanned using `is_utf8_string()` to determine if it is UTF-8.
If `PERL_PV_ESCAPE_ALL` is set then all input chars will be output using `\x01F1` style escapes, otherwise if `PERL_PV_ESCAPE_NONASCII` is set, only non-ASCII chars will be escaped using this style; otherwise, only chars above 255 will be so escaped; other non printable chars will use octal or common escaped patterns like `\n`. Otherwise, if `PERL_PV_ESCAPE_NOBACKSLASH` then all chars below 255 will be treated as printable and will be output as literals.
If `PERL_PV_ESCAPE_FIRSTCHAR` is set then only the first char of the string will be escaped, regardless of max. If the output is to be in hex, then it will be returned as a plain hex sequence. Thus the output will either be a single char, an octal escape sequence, a special escape like `\n` or a hex value.
If `PERL_PV_ESCAPE_RE` is set then the escape char used will be a `"%"` and not a `"\\"`. This is because regexes very often contain backslashed sequences, whereas `"%"` is not a particularly common character in patterns.
Returns a pointer to the escaped text as held by `dsv`.
```
char* pv_escape(SV *dsv, char const * const str,
const STRLEN count, const STRLEN max,
STRLEN * const escaped, const U32 flags)
```
`pv_pretty` Converts a string into something presentable, handling escaping via `pv_escape()` and supporting quoting and ellipses.
If the `PERL_PV_PRETTY_QUOTE` flag is set then the result will be double quoted with any double quotes in the string escaped. Otherwise if the `PERL_PV_PRETTY_LTGT` flag is set then the result be wrapped in angle brackets.
If the `PERL_PV_PRETTY_ELLIPSES` flag is set and not all characters in string were output then an ellipsis `...` will be appended to the string. Note that this happens AFTER it has been quoted.
If `start_color` is non-null then it will be inserted after the opening quote (if there is one) but before the escaped text. If `end_color` is non-null then it will be inserted after the escaped text but before any quotes or ellipses.
Returns a pointer to the prettified text as held by `dsv`.
```
char* pv_pretty(SV *dsv, char const * const str,
const STRLEN count, const STRLEN max,
char const * const start_color,
char const * const end_color, const U32 flags)
```
`vform` Like `["form"](#form)` but but the arguments are an encapsulated argument list.
```
char* vform(const char* pat, va_list* args)
```
`vmess` `pat` and `args` are a sprintf-style format pattern and encapsulated argument list, respectively. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for ["mess\_sv"](#mess_sv).
Normally, the resulting message is returned in a new mortal SV. During global destruction a single SV may be shared between uses of this function.
```
SV* vmess(const char* pat, va_list* args)
```
Embedding, Threads, and Interpreter Cloning
--------------------------------------------
`call_atexit` Add a function `fn` to the list of functions to be called at global destruction. `ptr` will be passed as an argument to `fn`; it can point to a `struct` so that you can pass anything you want.
Note that under threads, `fn` may run multiple times. This is because the list is executed each time the current or any descendent thread terminates.
```
void call_atexit(ATEXIT_t fn, void *ptr)
```
`cv_clone` Clone a CV, making a lexical closure. `proto` supplies the prototype of the function: its code, pad structure, and other attributes. The prototype is combined with a capture of outer lexicals to which the code refers, which are taken from the currently-executing instance of the immediately surrounding code.
```
CV* cv_clone(CV* proto)
```
`cv_name` Returns an SV containing the name of the CV, mainly for use in error reporting. The CV may actually be a GV instead, in which case the returned SV holds the GV's name. Anything other than a GV or CV is treated as a string already holding the sub name, but this could change in the future.
An SV may be passed as a second argument. If so, the name will be assigned to it and it will be returned. Otherwise the returned SV will be a new mortal.
If `flags` has the `CV_NAME_NOTQUAL` bit set, then the package name will not be included. If the first argument is neither a CV nor a GV, this flag is ignored (subject to change).
```
SV * cv_name(CV *cv, SV *sv, U32 flags)
```
`cv_undef` Clear out all the active components of a CV. This can happen either by an explicit `undef &foo`, or by the reference count going to zero. In the former case, we keep the `CvOUTSIDE` pointer, so that any anonymous children can still follow the full lexical scope chain.
```
void cv_undef(CV* cv)
```
`find_rundefsv` Returns the global variable `$_`.
```
SV* find_rundefsv()
```
`find_rundefsvoffset` `**DEPRECATED!**` It is planned to remove `find_rundefsvoffset` from a future release of Perl. Do not use it for new code; remove it from existing code.
Until the lexical `$_` feature was removed, this function would find the position of the lexical `$_` in the pad of the currently-executing function and return the offset in the current pad, or `NOT_IN_PAD`.
Now it always returns `NOT_IN_PAD`.
```
PADOFFSET find_rundefsvoffset()
```
`HAS_SKIP_LOCALE_INIT` Described in <perlembed>.
`intro_my` "Introduce" `my` variables to visible status. This is called during parsing at the end of each statement to make lexical variables visible to subsequent statements.
```
U32 intro_my()
```
`load_module`
`load_module_nocontext` These load the module whose name is pointed to by the string part of `name`. Note that the actual module name, not its filename, should be given. Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL, provides version semantics similar to `use Foo::Bar VERSION`. The optional trailing arguments can be used to specify arguments to the module's `import()` method, similar to `use Foo::Bar VERSION LIST`; their precise handling depends on the flags. The flags argument is a bitwise-ORed collection of any of `PERL_LOADMOD_DENY`, `PERL_LOADMOD_NOIMPORT`, or `PERL_LOADMOD_IMPORT_OPS` (or 0 for no flags).
If `PERL_LOADMOD_NOIMPORT` is set, the module is loaded as if with an empty import list, as in `use Foo::Bar ()`; this is the only circumstance in which the trailing optional arguments may be omitted entirely. Otherwise, if `PERL_LOADMOD_IMPORT_OPS` is set, the trailing arguments must consist of exactly one `OP*`, containing the op tree that produces the relevant import arguments. Otherwise, the trailing arguments must all be `SV*` values that will be used as import arguments; and the list must be terminated with `(SV*) NULL`. If neither `PERL_LOADMOD_NOIMPORT` nor `PERL_LOADMOD_IMPORT_OPS` is set, the trailing `NULL` pointer is needed even if no import arguments are desired. The reference count for each specified `SV*` argument is decremented. In addition, the `name` argument is modified.
If `PERL_LOADMOD_DENY` is set, the module is loaded as if with `no` rather than `use`.
`load_module` and `load_module_nocontext` have the same apparent signature, but the former hides the fact that it is accessing a thread context parameter. So use the latter when you get a compilation error about `pTHX`.
```
void load_module (U32 flags, SV* name, SV* ver, ...)
void load_module_nocontext(U32 flags, SV* name, SV* ver, ...)
```
`my_exit` A wrapper for the C library [exit(3)](http://man.he.net/man3/exit), honoring what ["PL\_exit\_flags" in perlapi](perlapi#PL_exit_flags) say to do.
```
void my_exit(U32 status)
```
`newPADNAMELIST` NOTE: `newPADNAMELIST` is **experimental** and may change or be removed without notice.
Creates a new pad name list. `max` is the highest index for which space is allocated.
```
PADNAMELIST * newPADNAMELIST(size_t max)
```
`newPADNAMEouter` NOTE: `newPADNAMEouter` is **experimental** and may change or be removed without notice.
Constructs and returns a new pad name. Only use this function for names that refer to outer lexicals. (See also ["newPADNAMEpvn"](#newPADNAMEpvn).) `outer` is the outer pad name that this one mirrors. The returned pad name has the `PADNAMEt_OUTER` flag already set.
```
PADNAME * newPADNAMEouter(PADNAME *outer)
```
`newPADNAMEpvn` NOTE: `newPADNAMEpvn` is **experimental** and may change or be removed without notice.
Constructs and returns a new pad name. `s` must be a UTF-8 string. Do not use this for pad names that point to outer lexicals. See `["newPADNAMEouter"](#newPADNAMEouter)`.
```
PADNAME * newPADNAMEpvn(const char *s, STRLEN len)
```
`nothreadhook` Stub that provides thread hook for perl\_destruct when there are no threads.
```
int nothreadhook()
```
`pad_add_anon` Allocates a place in the currently-compiling pad (via ["pad\_alloc"](#pad_alloc)) for an anonymous function that is lexically scoped inside the currently-compiling function. The function `func` is linked into the pad, and its `CvOUTSIDE` link to the outer scope is weakened to avoid a reference loop.
One reference count is stolen, so you may need to do `SvREFCNT_inc(func)`.
`optype` should be an opcode indicating the type of operation that the pad entry is to support. This doesn't affect operational semantics, but is used for debugging.
```
PADOFFSET pad_add_anon(CV* func, I32 optype)
```
`pad_add_name_pv` Exactly like ["pad\_add\_name\_pvn"](#pad_add_name_pvn), but takes a nul-terminated string instead of a string/length pair.
```
PADOFFSET pad_add_name_pv(const char *name, const U32 flags,
HV *typestash, HV *ourstash)
```
`pad_add_name_pvn` Allocates a place in the currently-compiling pad for a named lexical variable. Stores the name and other metadata in the name part of the pad, and makes preparations to manage the variable's lexical scoping. Returns the offset of the allocated pad slot.
`namepv`/`namelen` specify the variable's name, including leading sigil. If `typestash` is non-null, the name is for a typed lexical, and this identifies the type. If `ourstash` is non-null, it's a lexical reference to a package variable, and this identifies the package. The following flags can be OR'ed together:
```
padadd_OUR redundantly specifies if it's a package var
padadd_STATE variable will retain value persistently
padadd_NO_DUP_CHECK skip check for lexical shadowing
```
```
PADOFFSET pad_add_name_pvn(const char *namepv, STRLEN namelen,
U32 flags, HV *typestash,
HV *ourstash)
```
`pad_add_name_sv` Exactly like ["pad\_add\_name\_pvn"](#pad_add_name_pvn), but takes the name string in the form of an SV instead of a string/length pair.
```
PADOFFSET pad_add_name_sv(SV *name, U32 flags, HV *typestash,
HV *ourstash)
```
`pad_alloc` NOTE: `pad_alloc` is **experimental** and may change or be removed without notice.
Allocates a place in the currently-compiling pad, returning the offset of the allocated pad slot. No name is initially attached to the pad slot. `tmptype` is a set of flags indicating the kind of pad entry required, which will be set in the value SV for the allocated pad entry:
```
SVs_PADMY named lexical variable ("my", "our", "state")
SVs_PADTMP unnamed temporary store
SVf_READONLY constant shared between recursion levels
```
`SVf_READONLY` has been supported here only since perl 5.20. To work with earlier versions as well, use `SVf_READONLY|SVs_PADTMP`. `SVf_READONLY` does not cause the SV in the pad slot to be marked read-only, but simply tells `pad_alloc` that it *will* be made read-only (by the caller), or at least should be treated as such.
`optype` should be an opcode indicating the type of operation that the pad entry is to support. This doesn't affect operational semantics, but is used for debugging.
```
PADOFFSET pad_alloc(I32 optype, U32 tmptype)
```
`pad_findmy_pv` Exactly like ["pad\_findmy\_pvn"](#pad_findmy_pvn), but takes a nul-terminated string instead of a string/length pair.
```
PADOFFSET pad_findmy_pv(const char* name, U32 flags)
```
`pad_findmy_pvn` Given the name of a lexical variable, find its position in the currently-compiling pad. `namepv`/`namelen` specify the variable's name, including leading sigil. `flags` is reserved and must be zero. If it is not in the current pad but appears in the pad of any lexically enclosing scope, then a pseudo-entry for it is added in the current pad. Returns the offset in the current pad, or `NOT_IN_PAD` if no such lexical is in scope.
```
PADOFFSET pad_findmy_pvn(const char* namepv, STRLEN namelen,
U32 flags)
```
`pad_findmy_sv` Exactly like ["pad\_findmy\_pvn"](#pad_findmy_pvn), but takes the name string in the form of an SV instead of a string/length pair.
```
PADOFFSET pad_findmy_sv(SV* name, U32 flags)
```
`padnamelist_fetch` NOTE: `padnamelist_fetch` is **experimental** and may change or be removed without notice.
Fetches the pad name from the given index.
```
PADNAME * padnamelist_fetch(PADNAMELIST *pnl, SSize_t key)
```
`padnamelist_store` NOTE: `padnamelist_store` is **experimental** and may change or be removed without notice.
Stores the pad name (which may be null) at the given index, freeing any existing pad name in that slot.
```
PADNAME ** padnamelist_store(PADNAMELIST *pnl, SSize_t key,
PADNAME *val)
```
`pad_tidy` NOTE: `pad_tidy` is **experimental** and may change or be removed without notice.
Tidy up a pad at the end of compilation of the code to which it belongs. Jobs performed here are: remove most stuff from the pads of anonsub prototypes; give it a `@_`; mark temporaries as such. `type` indicates the kind of subroutine:
```
padtidy_SUB ordinary subroutine
padtidy_SUBCLONE prototype for lexical closure
padtidy_FORMAT format
```
```
void pad_tidy(padtidy_type type)
```
`perl_alloc` Allocates a new Perl interpreter. See <perlembed>.
```
PerlInterpreter* perl_alloc()
```
`PERL_ASYNC_CHECK` Described in <perlinterp>.
```
void PERL_ASYNC_CHECK()
```
`perl_construct` Initializes a new Perl interpreter. See <perlembed>.
```
void perl_construct(PerlInterpreter *my_perl)
```
`perl_destruct` Shuts down a Perl interpreter. See <perlembed> for a tutorial.
`my_perl` points to the Perl interpreter. It must have been previously created through the use of ["perl\_alloc"](#perl_alloc) and ["perl\_construct"](#perl_construct). It may have been initialised through ["perl\_parse"](#perl_parse), and may have been used through ["perl\_run"](#perl_run) and other means. This function should be called for any Perl interpreter that has been constructed with ["perl\_construct"](#perl_construct), even if subsequent operations on it failed, for example if ["perl\_parse"](#perl_parse) returned a non-zero value.
If the interpreter's `PL_exit_flags` word has the `PERL_EXIT_DESTRUCT_END` flag set, then this function will execute code in `END` blocks before performing the rest of destruction. If it is desired to make any use of the interpreter between ["perl\_parse"](#perl_parse) and ["perl\_destruct"](#perl_destruct) other than just calling ["perl\_run"](#perl_run), then this flag should be set early on. This matters if ["perl\_run"](#perl_run) will not be called, or if anything else will be done in addition to calling ["perl\_run"](#perl_run).
Returns a value be a suitable value to pass to the C library function `exit` (or to return from `main`), to serve as an exit code indicating the nature of the way the interpreter terminated. This takes into account any failure of ["perl\_parse"](#perl_parse) and any early exit from ["perl\_run"](#perl_run). The exit code is of the type required by the host operating system, so because of differing exit code conventions it is not portable to interpret specific numeric values as having specific meanings.
```
int perl_destruct(PerlInterpreter *my_perl)
```
`perl_free` Releases a Perl interpreter. See <perlembed>.
```
void perl_free(PerlInterpreter *my_perl)
```
`PERL_GET_CONTEXT` Described in <perlguts>.
`PerlInterpreter` Described in <perlembed>.
`perl_parse` Tells a Perl interpreter to parse a Perl script. This performs most of the initialisation of a Perl interpreter. See <perlembed> for a tutorial.
`my_perl` points to the Perl interpreter that is to parse the script. It must have been previously created through the use of ["perl\_alloc"](#perl_alloc) and ["perl\_construct"](#perl_construct). `xsinit` points to a callback function that will be called to set up the ability for this Perl interpreter to load XS extensions, or may be null to perform no such setup.
`argc` and `argv` supply a set of command-line arguments to the Perl interpreter, as would normally be passed to the `main` function of a C program. `argv[argc]` must be null. These arguments are where the script to parse is specified, either by naming a script file or by providing a script in a `-e` option. If [`$0`](perlvar#%240) will be written to in the Perl interpreter, then the argument strings must be in writable memory, and so mustn't just be string constants.
`env` specifies a set of environment variables that will be used by this Perl interpreter. If non-null, it must point to a null-terminated array of environment strings. If null, the Perl interpreter will use the environment supplied by the `environ` global variable.
This function initialises the interpreter, and parses and compiles the script specified by the command-line arguments. This includes executing code in `BEGIN`, `UNITCHECK`, and `CHECK` blocks. It does not execute `INIT` blocks or the main program.
Returns an integer of slightly tricky interpretation. The correct use of the return value is as a truth value indicating whether there was a failure in initialisation. If zero is returned, this indicates that initialisation was successful, and it is safe to proceed to call ["perl\_run"](#perl_run) and make other use of it. If a non-zero value is returned, this indicates some problem that means the interpreter wants to terminate. The interpreter should not be just abandoned upon such failure; the caller should proceed to shut the interpreter down cleanly with ["perl\_destruct"](#perl_destruct) and free it with ["perl\_free"](#perl_free).
For historical reasons, the non-zero return value also attempts to be a suitable value to pass to the C library function `exit` (or to return from `main`), to serve as an exit code indicating the nature of the way initialisation terminated. However, this isn't portable, due to differing exit code conventions. A historical bug is preserved for the time being: if the Perl built-in `exit` is called during this function's execution, with a type of exit entailing a zero exit code under the host operating system's conventions, then this function returns zero rather than a non-zero value. This bug, [perl #2754], leads to `perl_run` being called (and therefore `INIT` blocks and the main program running) despite a call to `exit`. It has been preserved because a popular module-installing module has come to rely on it and needs time to be fixed. This issue is [perl #132577], and the original bug is due to be fixed in Perl 5.30.
```
int perl_parse(PerlInterpreter *my_perl, XSINIT_t xsinit,
int argc, char** argv, char** env)
```
`perl_run` Tells a Perl interpreter to run its main program. See <perlembed> for a tutorial.
`my_perl` points to the Perl interpreter. It must have been previously created through the use of ["perl\_alloc"](#perl_alloc) and ["perl\_construct"](#perl_construct), and initialised through ["perl\_parse"](#perl_parse). This function should not be called if ["perl\_parse"](#perl_parse) returned a non-zero value, indicating a failure in initialisation or compilation.
This function executes code in `INIT` blocks, and then executes the main program. The code to be executed is that established by the prior call to ["perl\_parse"](#perl_parse). If the interpreter's `PL_exit_flags` word does not have the `PERL_EXIT_DESTRUCT_END` flag set, then this function will also execute code in `END` blocks. If it is desired to make any further use of the interpreter after calling this function, then `END` blocks should be postponed to ["perl\_destruct"](#perl_destruct) time by setting that flag.
Returns an integer of slightly tricky interpretation. The correct use of the return value is as a truth value indicating whether the program terminated non-locally. If zero is returned, this indicates that the program ran to completion, and it is safe to make other use of the interpreter (provided that the `PERL_EXIT_DESTRUCT_END` flag was set as described above). If a non-zero value is returned, this indicates that the interpreter wants to terminate early. The interpreter should not be just abandoned because of this desire to terminate; the caller should proceed to shut the interpreter down cleanly with ["perl\_destruct"](#perl_destruct) and free it with ["perl\_free"](#perl_free).
For historical reasons, the non-zero return value also attempts to be a suitable value to pass to the C library function `exit` (or to return from `main`), to serve as an exit code indicating the nature of the way the program terminated. However, this isn't portable, due to differing exit code conventions. An attempt is made to return an exit code of the type required by the host operating system, but because it is constrained to be non-zero, it is not necessarily possible to indicate every type of exit. It is only reliable on Unix, where a zero exit code can be augmented with a set bit that will be ignored. In any case, this function is not the correct place to acquire an exit code: one should get that from ["perl\_destruct"](#perl_destruct).
```
int perl_run(PerlInterpreter *my_perl)
```
`PERL_SET_CONTEXT` Described in <perlguts>.
```
void PERL_SET_CONTEXT(PerlInterpreter* i)
```
`PERL_SYS_INIT`
`PERL_SYS_INIT3` These provide system-specific tune up of the C runtime environment necessary to run Perl interpreters. Only one should be used, and it should be called only once, before creating any Perl interpreters.
They differ in that `PERL_SYS_INIT3` also initializes `env`.
```
void PERL_SYS_INIT (int *argc, char*** argv)
void PERL_SYS_INIT3(int *argc, char*** argv, char*** env)
```
`PERL_SYS_TERM` Provides system-specific clean up of the C runtime environment after running Perl interpreters. This should be called only once, after freeing any remaining Perl interpreters.
```
void PERL_SYS_TERM()
```
`PL_exit_flags` Contains flags controlling perl's behaviour on exit():
* `PERL_EXIT_DESTRUCT_END`
If set, END blocks are executed when the interpreter is destroyed. This is normally set by perl itself after the interpreter is constructed.
* `PERL_EXIT_ABORT`
Call `abort()` on exit. This is used internally by perl itself to abort if exit is called while processing exit.
* `PERL_EXIT_WARN`
Warn on exit.
* `PERL_EXIT_EXPECTED`
Set by the ["exit" in perlfunc](perlfunc#exit) operator.
```
U8 PL_exit_flags
```
`PL_origalen` Described in <perlembed>.
`PL_perl_destruct_level` This value may be set when embedding for full cleanup.
Possible values:
* 0 - none
* 1 - full
* 2 or greater - full with checks.
If `$ENV{PERL_DESTRUCT_LEVEL}` is set to an integer greater than the value of `PL_perl_destruct_level` its value is used instead.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
signed char PL_perl_destruct_level
```
`require_pv` Tells Perl to `require` the file named by the string argument. It is analogous to the Perl code `eval "require '$file'"`. It's even implemented that way; consider using load\_module instead.
NOTE: the `perl_require_pv()` form is **deprecated**.
```
void require_pv(const char* pv)
```
`vload_module` Like `["load\_module"](#load_module)` but the arguments are an encapsulated argument list.
```
void vload_module(U32 flags, SV* name, SV* ver, va_list* args)
```
Errno
-----
`sv_string_from_errnum` Generates the message string describing an OS error and returns it as an SV. `errnum` must be a value that `errno` could take, identifying the type of error.
If `tgtsv` is non-null then the string will be written into that SV (overwriting existing content) and it will be returned. If `tgtsv` is a null pointer then the string will be written into a new mortal SV which will be returned.
The message will be taken from whatever locale would be used by `$!`, and will be encoded in the SV in whatever manner would be used by `$!`. The details of this process are subject to future change. Currently, the message is taken from the C locale by default (usually producing an English message), and from the currently selected locale when in the scope of the `use locale` pragma. A heuristic attempt is made to decode the message from the locale's character encoding, but it will only be decoded as either UTF-8 or ISO-8859-1. It is always correctly decoded in a UTF-8 locale, usually in an ISO-8859-1 locale, and never in any other locale.
The SV is always returned containing an actual string, and with no other OK bits set. Unlike `$!`, a message is even yielded for `errnum` zero (meaning success), and if no useful message is available then a useless string (currently empty) is returned.
```
SV* sv_string_from_errnum(int errnum, SV* tgtsv)
```
Exception Handling (simple) Macros
-----------------------------------
`dXCPT` Set up necessary local variables for exception handling. See ["Exception Handling" in perlguts](perlguts#Exception-Handling).
```
dXCPT;
```
`JMPENV_JUMP` Described in <perlinterp>.
```
void JMPENV_JUMP(int v)
```
`JMPENV_PUSH` Described in <perlinterp>.
```
void JMPENV_PUSH(int v)
```
`PL_restartop` Described in <perlinterp>.
`XCPT_CATCH` Introduces a catch block. See ["Exception Handling" in perlguts](perlguts#Exception-Handling).
`XCPT_RETHROW` Rethrows a previously caught exception. See ["Exception Handling" in perlguts](perlguts#Exception-Handling).
```
XCPT_RETHROW;
```
`XCPT_TRY_END` Ends a try block. See ["Exception Handling" in perlguts](perlguts#Exception-Handling).
`XCPT_TRY_START` Starts a try block. See ["Exception Handling" in perlguts](perlguts#Exception-Handling).
Filesystem configuration values
--------------------------------
Also see ["List of capability HAS\_foo symbols"](#List-of-capability-HAS_foo-symbols).
`DIRNAMLEN` This symbol, if defined, indicates to the C program that the length of directory entry names is provided by a `d_namlen` field. Otherwise you need to do `strlen()` on the `d_name` field.
`DOSUID` This symbol, if defined, indicates that the C program should check the script that it is executing for setuid/setgid bits, and attempt to emulate setuid/setgid on systems that have disabled setuid #! scripts because the kernel can't do it securely. It is up to the package designer to make sure that this emulation is done securely. Among other things, it should do an fstat on the script it just opened to make sure it really is a setuid/setgid script, it should make sure the arguments passed correspond exactly to the argument on the #! line, and it should not trust any subprocesses to which it must pass the filename rather than the file descriptor of the script to be executed.
`EOF_NONBLOCK` This symbol, if defined, indicates to the C program that a `read()` on a non-blocking file descriptor will return 0 on `EOF`, and not the value held in `RD_NODATA` (-1 usually, in that case!).
`FCNTL_CAN_LOCK` This symbol, if defined, indicates that `fcntl()` can be used for file locking. Normally on Unix systems this is defined. It may be undefined on `VMS`.
`FFLUSH_ALL` This symbol, if defined, tells that to flush all pending stdio output one must loop through all the stdio file handles stored in an array and fflush them. Note that if `fflushNULL` is defined, fflushall will not even be probed for and will be left undefined.
`FFLUSH_NULL` This symbol, if defined, tells that `fflush(NULL)` correctly flushes all pending stdio output without side effects. In particular, on some platforms calling `fflush(NULL)` \*still\* corrupts `STDIN` if it is a pipe.
`FILE_base` This macro is used to access the `_base` field (or equivalent) of the `FILE` structure pointed to by its argument. This macro will always be defined if `USE_STDIO_BASE` is defined.
```
void * FILE_base(FILE * f)
```
`FILE_bufsiz` This macro is used to determine the number of bytes in the I/O buffer pointed to by `_base` field (or equivalent) of the `FILE` structure pointed to its argument. This macro will always be defined if `USE_STDIO_BASE` is defined.
```
Size_t FILE_bufsiz(FILE *f)
```
`FILE_cnt` This macro is used to access the `_cnt` field (or equivalent) of the `FILE` structure pointed to by its argument. This macro will always be defined if `USE_STDIO_PTR` is defined.
```
Size_t FILE_cnt(FILE * f)
```
`FILE_ptr` This macro is used to access the `_ptr` field (or equivalent) of the `FILE` structure pointed to by its argument. This macro will always be defined if `USE_STDIO_PTR` is defined.
```
void * FILE_ptr(FILE * f)
```
`FLEXFILENAMES` This symbol, if defined, indicates that the system supports filenames longer than 14 characters.
`HAS_DIR_DD_FD` This symbol, if defined, indicates that the the `DIR`\* dirstream structure contains a member variable named `dd_fd`.
`HAS_DUP2` This symbol, if defined, indicates that the `dup2` routine is available to duplicate file descriptors.
`HAS_DUP3` This symbol, if defined, indicates that the `dup3` routine is available to duplicate file descriptors.
`HAS_FAST_STDIO` This symbol, if defined, indicates that the "fast stdio" is available to manipulate the stdio buffers directly.
`HAS_FCHDIR` This symbol, if defined, indicates that the `fchdir` routine is available to change directory using a file descriptor.
`HAS_FCNTL` This symbol, if defined, indicates to the C program that the `fcntl()` function exists.
`HAS_FDCLOSE` This symbol, if defined, indicates that the `fdclose` routine is available to free a `FILE` structure without closing the underlying file descriptor. This function appeared in `FreeBSD` 10.2.
`HAS_FPATHCONF` This symbol, if defined, indicates that `pathconf()` is available to determine file-system related limits and options associated with a given open file descriptor.
`HAS_FPOS64_T` This symbol will be defined if the C compiler supports `fpos64_t`.
`HAS_FSTATFS` This symbol, if defined, indicates that the `fstatfs` routine is available to stat filesystems by file descriptors.
`HAS_FSTATVFS` This symbol, if defined, indicates that the `fstatvfs` routine is available to stat filesystems by file descriptors.
`HAS_GETFSSTAT` This symbol, if defined, indicates that the `getfsstat` routine is available to stat filesystems in bulk.
`HAS_GETMNT` This symbol, if defined, indicates that the `getmnt` routine is available to get filesystem mount info by filename.
`HAS_GETMNTENT` This symbol, if defined, indicates that the `getmntent` routine is available to iterate through mounted file systems to get their info.
`HAS_HASMNTOPT` This symbol, if defined, indicates that the `hasmntopt` routine is available to query the mount options of file systems.
`HAS_LSEEK_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `lseek()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern off_t lseek(int, off_t, int);
```
`HAS_MKDIR` This symbol, if defined, indicates that the `mkdir` routine is available to create directories. Otherwise you should fork off a new process to exec */bin/mkdir*.
`HAS_OFF64_T` This symbol will be defined if the C compiler supports `off64_t`.
`HAS_OPEN3` This manifest constant lets the C program know that the three argument form of `open(2)` is available.
`HAS_OPENAT` This symbol is defined if the `openat()` routine is available.
`HAS_POLL` This symbol, if defined, indicates that the `poll` routine is available to `poll` active file descriptors. Please check `I_POLL` and `I_SYS_POLL` to know which header should be included as well.
`HAS_READDIR` This symbol, if defined, indicates that the `readdir` routine is available to read directory entries. You may have to include *dirent.h*. See `["I\_DIRENT"](#I_DIRENT)`.
`HAS_READDIR64_R` This symbol, if defined, indicates that the `readdir64_r` routine is available to readdir64 re-entrantly.
`HAS_REWINDDIR` This symbol, if defined, indicates that the `rewinddir` routine is available. You may have to include *dirent.h*. See `["I\_DIRENT"](#I_DIRENT)`.
`HAS_RMDIR` This symbol, if defined, indicates that the `rmdir` routine is available to remove directories. Otherwise you should fork off a new process to exec */bin/rmdir*.
`HAS_SEEKDIR` This symbol, if defined, indicates that the `seekdir` routine is available. You may have to include *dirent.h*. See `["I\_DIRENT"](#I_DIRENT)`.
`HAS_SELECT` This symbol, if defined, indicates that the `select` routine is available to `select` active file descriptors. If the timeout field is used, *sys/time.h* may need to be included.
`HAS_SETVBUF` This symbol, if defined, indicates that the `setvbuf` routine is available to change buffering on an open stdio stream. to a line-buffered mode.
`HAS_STDIO_STREAM_ARRAY` This symbol, if defined, tells that there is an array holding the stdio streams.
`HAS_STRUCT_FS_DATA` This symbol, if defined, indicates that the `struct fs_data` to do `statfs()` is supported.
`HAS_STRUCT_STATFS` This symbol, if defined, indicates that the `struct statfs` to do `statfs()` is supported.
`HAS_STRUCT_STATFS_F_FLAGS` This symbol, if defined, indicates that the `struct statfs` does have the `f_flags` member containing the mount flags of the filesystem containing the file. This kind of `struct statfs` is coming from *sys/mount.h* (`BSD` 4.3), not from *sys/statfs.h* (`SYSV`). Older `BSDs` (like Ultrix) do not have `statfs()` and `struct statfs`, they have `ustat()` and `getmnt()` with `struct ustat` and `struct fs_data`.
`HAS_TELLDIR` This symbol, if defined, indicates that the `telldir` routine is available. You may have to include *dirent.h*. See `["I\_DIRENT"](#I_DIRENT)`.
`HAS_USTAT` This symbol, if defined, indicates that the `ustat` system call is available to query file system statistics by `dev_t`.
`I_FCNTL` This manifest constant tells the C program to include *fcntl.h*.
```
#ifdef I_FCNTL
#include <fcntl.h>
#endif
```
`I_SYS_DIR` This symbol, if defined, indicates to the C program that it should include *sys/dir.h*.
```
#ifdef I_SYS_DIR
#include <sys_dir.h>
#endif
```
`I_SYS_FILE` This symbol, if defined, indicates to the C program that it should include *sys/file.h* to get definition of `R_OK` and friends.
```
#ifdef I_SYS_FILE
#include <sys_file.h>
#endif
```
`I_SYS_NDIR` This symbol, if defined, indicates to the C program that it should include *sys/ndir.h*.
```
#ifdef I_SYS_NDIR
#include <sys_ndir.h>
#endif
```
`I_SYS_STATFS` This symbol, if defined, indicates that *sys/statfs.h* exists.
```
#ifdef I_SYS_STATFS
#include <sys_statfs.h>
#endif
```
`LSEEKSIZE` This symbol holds the number of bytes used by the `Off_t`.
`RD_NODATA` This symbol holds the return code from `read()` when no data is present on the non-blocking file descriptor. Be careful! If `EOF_NONBLOCK` is not defined, then you can't distinguish between no data and `EOF` by issuing a `read()`. You'll have to find another way to tell for sure!
`READDIR64_R_PROTO` This symbol encodes the prototype of `readdir64_r`. It is zero if `d_readdir64_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_readdir64_r` is defined.
`STDCHAR` This symbol is defined to be the type of char used in *stdio.h*. It has the values "unsigned char" or "char".
`STDIO_CNT_LVALUE` This symbol is defined if the `FILE_cnt` macro can be used as an lvalue.
`STDIO_PTR_LVALUE` This symbol is defined if the `FILE_ptr` macro can be used as an lvalue.
`STDIO_PTR_LVAL_NOCHANGE_CNT` This symbol is defined if using the `FILE_ptr` macro as an lvalue to increase the pointer by n leaves `File_cnt(fp)` unchanged.
`STDIO_PTR_LVAL_SETS_CNT` This symbol is defined if using the `FILE_ptr` macro as an lvalue to increase the pointer by n has the side effect of decreasing the value of `File_cnt(fp)` by n.
`STDIO_STREAM_ARRAY` This symbol tells the name of the array holding the stdio streams. Usual values include `_iob`, `__iob`, and `__sF`.
`ST_INO_SIGN` This symbol holds the signedness of `struct stat`'s `st_ino`. 1 for unsigned, -1 for signed.
`ST_INO_SIZE` This variable contains the size of `struct stat`'s `st_ino` in bytes.
`VAL_EAGAIN` This symbol holds the errno error code set by `read()` when no data was present on the non-blocking file descriptor.
`VAL_O_NONBLOCK` This symbol is to be used during `open()` or `fcntl(F_SETFL)` to turn on non-blocking I/O for the file descriptor. Note that there is no way back, i.e. you cannot turn it blocking again this way. If you wish to alternatively switch between blocking and non-blocking, use the `ioctl(FIOSNBIO)` call instead, but that is not supported by all devices.
`VOID_CLOSEDIR` This symbol, if defined, indicates that the `closedir()` routine does not return a value.
Floating point
---------------
Also ["List of capability HAS\_foo symbols"](#List-of-capability-HAS_foo-symbols) lists capabilities that arent in this section. For example `HAS_ASINH`, for the hyperbolic sine function.
`CASTFLAGS` This symbol contains flags that say what difficulties the compiler has casting odd floating values to unsigned long:
```
0 = ok
1 = couldn't cast < 0
2 = couldn't cast >= 0x80000000
4 = couldn't cast in argument expression list
```
`CASTNEGFLOAT` This symbol is defined if the C compiler can cast negative numbers to unsigned longs, ints and shorts.
`DOUBLE_HAS_INF` This symbol, if defined, indicates that the double has the infinity.
`DOUBLE_HAS_NAN` This symbol, if defined, indicates that the double has the not-a-number.
`DOUBLE_HAS_NEGATIVE_ZERO` This symbol, if defined, indicates that the double has the `negative_zero`.
`DOUBLE_HAS_SUBNORMALS` This symbol, if defined, indicates that the double has the subnormals (denormals).
`DOUBLEINFBYTES` This symbol, if defined, is a comma-separated list of hexadecimal bytes for the double precision infinity.
`DOUBLEKIND` `DOUBLEKIND` will be one of `DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN` `DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN` `DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN` `DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN` `DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN` `DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN` `DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE` `DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE` `DOUBLE_IS_VAX_F_FLOAT` `DOUBLE_IS_VAX_D_FLOAT` `DOUBLE_IS_VAX_G_FLOAT` `DOUBLE_IS_IBM_SINGLE_32_BIT` `DOUBLE_IS_IBM_DOUBLE_64_BIT` `DOUBLE_IS_CRAY_SINGLE_64_BIT` `DOUBLE_IS_UNKNOWN_FORMAT`
`DOUBLEMANTBITS` This symbol, if defined, tells how many mantissa bits there are in double precision floating point format. Note that this is usually `DBL_MANT_DIG` minus one, since with the standard `IEEE` 754 formats `DBL_MANT_DIG` includes the implicit bit, which doesn't really exist.
`DOUBLENANBYTES` This symbol, if defined, is a comma-separated list of hexadecimal bytes (0xHH) for the double precision not-a-number.
`DOUBLESIZE` This symbol contains the size of a double, so that the C preprocessor can make decisions based on it.
`DOUBLE_STYLE_CRAY` This symbol, if defined, indicates that the double is the 64-bit `CRAY` mainframe format.
`DOUBLE_STYLE_IBM` This symbol, if defined, indicates that the double is the 64-bit `IBM` mainframe format.
`DOUBLE_STYLE_IEEE` This symbol, if defined, indicates that the double is the 64-bit `IEEE` 754.
`DOUBLE_STYLE_VAX` This symbol, if defined, indicates that the double is the 64-bit `VAX` format D or G.
`HAS_ATOLF` This symbol, if defined, indicates that the `atolf` routine is available to convert strings into long doubles.
`HAS_CLASS` This symbol, if defined, indicates that the `class` routine is available to classify doubles. Available for example in `AIX`. The returned values are defined in *float.h* and are:
```
FP_PLUS_NORM Positive normalized, nonzero
FP_MINUS_NORM Negative normalized, nonzero
FP_PLUS_DENORM Positive denormalized, nonzero
FP_MINUS_DENORM Negative denormalized, nonzero
FP_PLUS_ZERO +0.0
FP_MINUS_ZERO -0.0
FP_PLUS_INF +INF
FP_MINUS_INF -INF
FP_NANS Signaling Not a Number (NaNS)
FP_NANQ Quiet Not a Number (NaNQ)
```
`HAS_FINITE` This symbol, if defined, indicates that the `finite` routine is available to check whether a double is `finite` (non-infinity non-NaN).
`HAS_FINITEL` This symbol, if defined, indicates that the `finitel` routine is available to check whether a long double is finite (non-infinity non-NaN).
`HAS_FPCLASS` This symbol, if defined, indicates that the `fpclass` routine is available to classify doubles. Available for example in Solaris/`SVR4`. The returned values are defined in *ieeefp.h* and are:
```
FP_SNAN signaling NaN
FP_QNAN quiet NaN
FP_NINF negative infinity
FP_PINF positive infinity
FP_NDENORM negative denormalized non-zero
FP_PDENORM positive denormalized non-zero
FP_NZERO negative zero
FP_PZERO positive zero
FP_NNORM negative normalized non-zero
FP_PNORM positive normalized non-zero
```
`HAS_FPCLASSIFY` This symbol, if defined, indicates that the `fpclassify` routine is available to classify doubles. Available for example in HP-UX. The returned values are defined in *math.h* and are
```
FP_NORMAL Normalized
FP_ZERO Zero
FP_INFINITE Infinity
FP_SUBNORMAL Denormalized
FP_NAN NaN
```
`HAS_FPCLASSL` This symbol, if defined, indicates that the `fpclassl` routine is available to classify long doubles. Available for example in `IRIX`. The returned values are defined in *ieeefp.h* and are:
```
FP_SNAN signaling NaN
FP_QNAN quiet NaN
FP_NINF negative infinity
FP_PINF positive infinity
FP_NDENORM negative denormalized non-zero
FP_PDENORM positive denormalized non-zero
FP_NZERO negative zero
FP_PZERO positive zero
FP_NNORM negative normalized non-zero
FP_PNORM positive normalized non-zero
```
`HAS_FPGETROUND` This symbol, if defined, indicates that the `fpgetround` routine is available to get the floating point rounding mode.
`HAS_FP_CLASS` This symbol, if defined, indicates that the `fp_class` routine is available to classify doubles. Available for example in Digital `UNIX`. The returned values are defined in *math.h* and are:
```
FP_SNAN Signaling NaN (Not-a-Number)
FP_QNAN Quiet NaN (Not-a-Number)
FP_POS_INF +infinity
FP_NEG_INF -infinity
FP_POS_NORM Positive normalized
FP_NEG_NORM Negative normalized
FP_POS_DENORM Positive denormalized
FP_NEG_DENORM Negative denormalized
FP_POS_ZERO +0.0 (positive zero)
FP_NEG_ZERO -0.0 (negative zero)
```
`HAS_FP_CLASSIFY` This symbol, if defined, indicates that the `fp_classify` routine is available to classify doubles. The values are defined in *math.h*
```
FP_NORMAL Normalized
FP_ZERO Zero
FP_INFINITE Infinity
FP_SUBNORMAL Denormalized
FP_NAN NaN
```
`HAS_FP_CLASSL` This symbol, if defined, indicates that the `fp_classl` routine is available to classify long doubles. Available for example in Digital `UNIX`. See for possible values `HAS_FP_CLASS`.
`HAS_FREXPL` This symbol, if defined, indicates that the `frexpl` routine is available to break a long double floating-point number into a normalized fraction and an integral power of 2.
`HAS_ILOGB` This symbol, if defined, indicates that the `ilogb` routine is available to get integer exponent of a floating-point value.
`HAS_ISFINITE` This symbol, if defined, indicates that the `isfinite` routine is available to check whether a double is finite (non-infinity non-NaN).
`HAS_ISFINITEL` This symbol, if defined, indicates that the `isfinitel` routine is available to check whether a long double is finite. (non-infinity non-NaN).
`HAS_ISINF` This symbol, if defined, indicates that the `isinf` routine is available to check whether a double is an infinity.
`HAS_ISINFL` This symbol, if defined, indicates that the `isinfl` routine is available to check whether a long double is an infinity.
`HAS_ISNAN` This symbol, if defined, indicates that the `isnan` routine is available to check whether a double is a NaN.
`HAS_ISNANL` This symbol, if defined, indicates that the `isnanl` routine is available to check whether a long double is a NaN.
`HAS_ISNORMAL` This symbol, if defined, indicates that the `isnormal` routine is available to check whether a double is normal (non-zero normalized).
`HAS_J0` This symbol, if defined, indicates to the C program that the `j0()` function is available for Bessel functions of the first kind of the order zero, for doubles.
`HAS_J0L` This symbol, if defined, indicates to the C program that the `j0l()` function is available for Bessel functions of the first kind of the order zero, for long doubles.
`HAS_LDBL_DIG` This symbol, if defined, indicates that this system's *float.h* or *limits.h* defines the symbol `LDBL_DIG`, which is the number of significant digits in a long double precision number. Unlike for `DBL_DIG`, there's no good guess for `LDBL_DIG` if it is undefined.
`HAS_LDEXPL` This symbol, if defined, indicates that the `ldexpl` routine is available to shift a long double floating-point number by an integral power of 2.
`HAS_LLRINT` This symbol, if defined, indicates that the `llrint` routine is available to return the long long value closest to a double (according to the current rounding mode).
`HAS_LLRINTL` This symbol, if defined, indicates that the `llrintl` routine is available to return the long long value closest to a long double (according to the current rounding mode).
`HAS_LLROUNDL` This symbol, if defined, indicates that the `llroundl` routine is available to return the nearest long long value away from zero of the long double argument value.
`HAS_LONG_DOUBLE` This symbol will be defined if the C compiler supports long doubles.
`HAS_LRINT` This symbol, if defined, indicates that the `lrint` routine is available to return the integral value closest to a double (according to the current rounding mode).
`HAS_LRINTL` This symbol, if defined, indicates that the `lrintl` routine is available to return the integral value closest to a long double (according to the current rounding mode).
`HAS_LROUNDL` This symbol, if defined, indicates that the `lroundl` routine is available to return the nearest integral value away from zero of the long double argument value.
`HAS_MODFL` This symbol, if defined, indicates that the `modfl` routine is available to split a long double x into a fractional part f and an integer part i such that |f| < 1.0 and (f + i) = x.
`HAS_NAN` This symbol, if defined, indicates that the `nan` routine is available to generate NaN.
`HAS_NEXTTOWARD` This symbol, if defined, indicates that the `nexttoward` routine is available to return the next machine representable long double from x in direction y.
`HAS_REMAINDER` This symbol, if defined, indicates that the `remainder` routine is available to return the floating-point `remainder`.
`HAS_SCALBN` This symbol, if defined, indicates that the `scalbn` routine is available to multiply floating-point number by integral power of radix.
`HAS_SIGNBIT` This symbol, if defined, indicates that the `signbit` routine is available to check if the given number has the sign bit set. This should include correct testing of -0.0. This will only be set if the `signbit()` routine is safe to use with the NV type used internally in perl. Users should call `Perl_signbit()`, which will be #defined to the system's `signbit()` function or macro if this symbol is defined.
`HAS_SQRTL` This symbol, if defined, indicates that the `sqrtl` routine is available to do long double square roots.
`HAS_STRTOD_L` This symbol, if defined, indicates that the `strtod_l` routine is available to convert strings to long doubles.
`HAS_STRTOLD` This symbol, if defined, indicates that the `strtold` routine is available to convert strings to long doubles.
`HAS_STRTOLD_L` This symbol, if defined, indicates that the `strtold_l` routine is available to convert strings to long doubles.
`HAS_TRUNC` This symbol, if defined, indicates that the `trunc` routine is available to round doubles towards zero.
`HAS_UNORDERED` This symbol, if defined, indicates that the `unordered` routine is available to check whether two doubles are `unordered` (effectively: whether either of them is NaN)
`I_FENV` This symbol, if defined, indicates to the C program that it should include *fenv.h* to get the floating point environment definitions.
```
#ifdef I_FENV
#include <fenv.h>
#endif
```
`I_QUADMATH` This symbol, if defined, indicates that *quadmath.h* exists and should be included.
```
#ifdef I_QUADMATH
#include <quadmath.h>
#endif
```
`LONGDBLINFBYTES` This symbol, if defined, is a comma-separated list of hexadecimal bytes for the long double precision infinity.
`LONGDBLMANTBITS` This symbol, if defined, tells how many mantissa bits there are in long double precision floating point format. Note that this can be `LDBL_MANT_DIG` minus one, since `LDBL_MANT_DIG` can include the `IEEE` 754 implicit bit. The common x86-style 80-bit long double does not have an implicit bit.
`LONGDBLNANBYTES` This symbol, if defined, is a comma-separated list of hexadecimal bytes (0xHH) for the long double precision not-a-number.
`LONG_DOUBLEKIND` `LONG_DOUBLEKIND` will be one of `LONG_DOUBLE_IS_DOUBLE` `LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN` `LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN` `LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN` `LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LITTLE_ENDIAN` `LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BIG_ENDIAN` `LONG_DOUBLE_IS_VAX_H_FLOAT` `LONG_DOUBLE_IS_UNKNOWN_FORMAT` It is only defined if the system supports long doubles.
`LONG_DOUBLESIZE` This symbol contains the size of a long double, so that the C preprocessor can make decisions based on it. It is only defined if the system supports long doubles. Note that this is `sizeof(long double)`, which may include unused bytes.
`LONG_DOUBLE_STYLE_IEEE` This symbol, if defined, indicates that the long double is any of the `IEEE` 754 style long doubles: `LONG_DOUBLE_STYLE_IEEE_STD`, `LONG_DOUBLE_STYLE_IEEE_EXTENDED`, `LONG_DOUBLE_STYLE_IEEE_DOUBLEDOUBLE`.
`LONG_DOUBLE_STYLE_IEEE_DOUBLEDOUBLE` This symbol, if defined, indicates that the long double is the 128-bit double-double.
`LONG_DOUBLE_STYLE_IEEE_EXTENDED` This symbol, if defined, indicates that the long double is the 80-bit `IEEE` 754. Note that despite the 'extended' this is less than the 'std', since this is an extension of the double precision.
`LONG_DOUBLE_STYLE_IEEE_STD` This symbol, if defined, indicates that the long double is the 128-bit `IEEE` 754.
`LONG_DOUBLE_STYLE_VAX` This symbol, if defined, indicates that the long double is the 128-bit `VAX` format H.
`NV` Described in <perlguts>.
`NVMANTBITS` This symbol, if defined, tells how many mantissa bits (not including implicit bit) there are in a Perl NV. This depends on which floating point type was chosen.
`NV_OVERFLOWS_INTEGERS_AT` This symbol gives the largest integer value that NVs can hold. This value + 1.0 cannot be stored accurately. It is expressed as constant floating point expression to reduce the chance of decimal/binary conversion issues. If it can not be determined, the value 0 is given.
`NV_PRESERVES_UV` This symbol, if defined, indicates that a variable of type `NVTYPE` can preserve all the bits of a variable of type `UVTYPE`.
`NV_PRESERVES_UV_BITS` This symbol contains the number of bits a variable of type `NVTYPE` can preserve of a variable of type `UVTYPE`.
`NVSIZE` This symbol contains the `sizeof(NV)`. Note that some floating point formats have unused bytes. The most notable example is the x86\* 80-bit extended precision which comes in byte sizes of 12 and 16 (for 32 and 64 bit platforms, respectively), but which only uses 10 bytes. Perl compiled with `-Duselongdouble` on x86\* is like this.
`NVTYPE` This symbol defines the C type used for Perl's NV.
`NV_ZERO_IS_ALLBITS_ZERO` This symbol, if defined, indicates that a variable of type `NVTYPE` stores 0.0 in memory as all bits zero.
General Configuration
----------------------
This section contains configuration information not otherwise found in the more specialized sections of this document. At the end is a list of `#defines` whose name should be enough to tell you what they do, and a list of #defines which tell you if you need to `#include` files to get the corresponding functionality.
`BYTEORDER` This symbol holds the hexadecimal constant defined in byteorder, in a UV, i.e. 0x1234 or 0x4321 or 0x12345678, etc... If the compiler supports cross-compiling or multiple-architecture binaries, use compiler-defined macros to determine the byte order.
`CHARBITS` This symbol contains the size of a char, so that the C preprocessor can make decisions based on it.
`DB_VERSION_MAJOR_CFG` This symbol, if defined, defines the major version number of Berkeley DB found in the *db.h* header when Perl was configured.
`DB_VERSION_MINOR_CFG` This symbol, if defined, defines the minor version number of Berkeley DB found in the *db.h* header when Perl was configured. For DB version 1 this is always 0.
`DB_VERSION_PATCH_CFG` This symbol, if defined, defines the patch version number of Berkeley DB found in the *db.h* header when Perl was configured. For DB version 1 this is always 0.
`DEFAULT_INC_EXCLUDES_DOT` This symbol, if defined, removes the legacy default behavior of including '.' at the end of @`INC`.
`DLSYM_NEEDS_UNDERSCORE` This symbol, if defined, indicates that we need to prepend an underscore to the symbol name before calling `dlsym()`. This only makes sense if you \*have\* dlsym, which we will presume is the case if you're using *dl\_dlopen.xs*.
`EBCDIC` This symbol, if defined, indicates that this system uses `EBCDIC` encoding.
`HAS_CSH` This symbol, if defined, indicates that the C-shell exists.
`HAS_GETHOSTNAME` This symbol, if defined, indicates that the C program may use the `gethostname()` routine to derive the host name. See also `["HAS\_UNAME"](#HAS_UNAME)` and `["PHOSTNAME"](#PHOSTNAME)`.
`HAS_GNULIBC` This symbol, if defined, indicates to the C program that the `GNU` C library is being used. A better check is to use the `__GLIBC__` and `__GLIBC_MINOR__` symbols supplied with glibc.
`HAS_LGAMMA` This symbol, if defined, indicates that the `lgamma` routine is available to do the log gamma function. See also `["HAS\_TGAMMA"](#HAS_TGAMMA)` and `["HAS\_LGAMMA\_R"](#HAS_LGAMMA_R)`.
`HAS_LGAMMA_R` This symbol, if defined, indicates that the `lgamma_r` routine is available to do the log gamma function without using the global signgam variable.
`HAS_NON_INT_BITFIELDS` This symbol, if defined, indicates that the C compiler accepts, without error or warning, `struct bitfields` that are declared with sizes other than plain 'int'; for example 'unsigned char' is accepted.
`HAS_PRCTL_SET_NAME` This symbol, if defined, indicates that the prctl routine is available to set process title and supports `PR_SET_NAME`.
`HAS_PROCSELFEXE` This symbol is defined if `PROCSELFEXE_PATH` is a symlink to the absolute pathname of the executing program.
`HAS_PSEUDOFORK` This symbol, if defined, indicates that an emulation of the fork routine is available.
`HAS_REGCOMP` This symbol, if defined, indicates that the `regcomp()` routine is available to do some regular pattern matching (usually on `POSIX`.2 conforming systems).
`HAS_SETPGID` This symbol, if defined, indicates that the `setpgid(pid, gpid)` routine is available to set process group ID.
`HAS_SIGSETJMP` This variable indicates to the C program that the `sigsetjmp()` routine is available to save the calling process's registers and stack environment for later use by `siglongjmp()`, and to optionally save the process's signal mask. See `["Sigjmp\_buf"](#Sigjmp_buf)`, `["Sigsetjmp"](#Sigsetjmp)`, and `["Siglongjmp"](#Siglongjmp)`.
`HAS_STRUCT_CMSGHDR` This symbol, if defined, indicates that the `struct cmsghdr` is supported.
`HAS_STRUCT_MSGHDR` This symbol, if defined, indicates that the `struct msghdr` is supported.
`HAS_TGAMMA` This symbol, if defined, indicates that the `tgamma` routine is available to do the gamma function. See also `["HAS\_LGAMMA"](#HAS_LGAMMA)`.
`HAS_UNAME` This symbol, if defined, indicates that the C program may use the `uname()` routine to derive the host name. See also `["HAS\_GETHOSTNAME"](#HAS_GETHOSTNAME)` and `["PHOSTNAME"](#PHOSTNAME)`.
`HAS_UNION_SEMUN` This symbol, if defined, indicates that the `union semun` is defined by including *sys/sem.h*. If not, the user code probably needs to define it as:
```
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
}
```
`I_DIRENT` This symbol, if defined, indicates to the C program that it should include *dirent.h*. Using this symbol also triggers the definition of the `Direntry_t` define which ends up being '`struct dirent`' or '`struct direct`' depending on the availability of *dirent.h*.
```
#ifdef I_DIRENT
#include <dirent.h>
#endif
```
`I_POLL` This symbol, if defined, indicates that *poll.h* exists and should be included. (see also `["HAS\_POLL"](#HAS_POLL)`)
```
#ifdef I_POLL
#include <poll.h>
#endif
```
`I_SYS_RESOURCE` This symbol, if defined, indicates to the C program that it should include *sys/resource.h*.
```
#ifdef I_SYS_RESOURCE
#include <sys_resource.h>
#endif
```
`LIBM_LIB_VERSION` This symbol, if defined, indicates that libm exports `_LIB_VERSION` and that *math.h* defines the enum to manipulate it.
`NEED_VA_COPY` This symbol, if defined, indicates that the system stores the variable argument list datatype, `va_list`, in a format that cannot be copied by simple assignment, so that some other means must be used when copying is required. As such systems vary in their provision (or non-provision) of copying mechanisms, *handy.h* defines a platform- independent macro, `Perl_va_copy(src, dst)`, to do the job.
`OSNAME` This symbol contains the name of the operating system, as determined by Configure. You shouldn't rely on it too much; the specific feature tests from Configure are generally more reliable.
`OSVERS` This symbol contains the version of the operating system, as determined by Configure. You shouldn't rely on it too much; the specific feature tests from Configure are generally more reliable.
`PHOSTNAME` This symbol, if defined, indicates the command to feed to the `popen()` routine to derive the host name. See also `["HAS\_GETHOSTNAME"](#HAS_GETHOSTNAME)` and `["HAS\_UNAME"](#HAS_UNAME)`. Note that the command uses a fully qualified path, so that it is safe even if used by a process with super-user privileges.
`PROCSELFEXE_PATH` If `HAS_PROCSELFEXE` is defined this symbol is the filename of the symbolic link pointing to the absolute pathname of the executing program.
`PTRSIZE` This symbol contains the size of a pointer, so that the C preprocessor can make decisions based on it. It will be `sizeof(void *)` if the compiler supports (void \*); otherwise it will be `sizeof(char *)`.
`RANDBITS` This symbol indicates how many bits are produced by the function used to generate normalized random numbers. Values include 15, 16, 31, and 48.
`SELECT_MIN_BITS` This symbol holds the minimum number of bits operated by select. That is, if you do `select(n, ...)`, how many bits at least will be cleared in the masks if some activity is detected. Usually this is either n or 32\*`ceil(n/32)`, especially many little-endians do the latter. This is only useful if you have `select()`, naturally.
`SETUID_SCRIPTS_ARE_SECURE_NOW` This symbol, if defined, indicates that the bug that prevents setuid scripts from being secure is not present in this kernel.
`ST_DEV_SIGN` This symbol holds the signedness of `struct stat`'s `st_dev`. 1 for unsigned, -1 for signed.
`ST_DEV_SIZE` This variable contains the size of `struct stat`'s `st_dev` in bytes.
###
List of capability `HAS_*foo*` symbols
This is a list of those symbols that dont appear elsewhere in ths document that indicate if the current platform has a certain capability. Their names all begin with `HAS_`. Only those symbols whose capability is directly derived from the name are listed here. All others have their meaning expanded out elsewhere in this document. This (relatively) compact list is because we think that the expansion would add little or no value and take up a lot of space (because there are so many). If you think certain ones should be expanded, send email to [[email protected]](mailto:[email protected]).
Each symbol here will be `#define`d if and only if the platform has the capability. If you need more detail, see the corresponding entry in *config.h*. For convenience, the list is split so that the ones that indicate there is a reentrant version of a capability are listed separately
`HAS_ACCEPT4`, `HAS_ACCESS`, `HAS_ACCESSX`, `HAS_ACOSH`, `HAS_AINTL`, `HAS_ALARM`, `HAS_ASINH`, `HAS_ATANH`, `HAS_ATOLL`, `HAS_CBRT`, `HAS_CHOWN`, `HAS_CHROOT`, `HAS_CHSIZE`, `HAS_CLEARENV`, `HAS_COPYSIGN`, `HAS_COPYSIGNL`, `HAS_CRYPT`, `HAS_CTERMID`, `HAS_CUSERID`, `HAS_DIRFD`, `HAS_DLADDR`, `HAS_DLERROR`, `HAS_EACCESS`, `HAS_ENDHOSTENT`, `HAS_ENDNETENT`, `HAS_ENDPROTOENT`, `HAS_ENDSERVENT`, `HAS_ERF`, `HAS_ERFC`, `HAS_EXP2`, `HAS_EXPM1`, `HAS_FCHMOD`, `HAS_FCHMODAT`, `HAS_FCHOWN`, `HAS_FDIM`, `HAS_FD_SET`, `HAS_FEGETROUND`, `HAS_FFS`, `HAS_FFSL`, `HAS_FGETPOS`, `HAS_FLOCK`, `HAS_FMA`, `HAS_FMAX`, `HAS_FMIN`, `HAS_FORK`, `HAS_FSEEKO`, `HAS_FSETPOS`, `HAS_FSYNC`, `HAS_FTELLO`, `HAS_GAI_STRERROR`, `HAS_GETADDRINFO`, `HAS_GETCWD`, `HAS_GETESPWNAM`, `HAS_GETGROUPS`, `HAS_GETHOSTBYADDR`, `HAS_GETHOSTBYNAME`, `HAS_GETHOSTENT`, `HAS_GETLOGIN`, `HAS_GETNAMEINFO`, `HAS_GETNETBYADDR`, `HAS_GETNETBYNAME`, `HAS_GETNETENT`, `HAS_GETPAGESIZE`, `HAS_GETPGID`, `HAS_GETPGRP`, `HAS_GETPGRP2`, `HAS_GETPPID`, `HAS_GETPRIORITY`, `HAS_GETPROTOBYNAME`, `HAS_GETPROTOBYNUMBER`, `HAS_GETPROTOENT`, `HAS_GETPRPWNAM`, `HAS_GETSERVBYNAME`, `HAS_GETSERVBYPORT`, `HAS_GETSERVENT`, `HAS_GETSPNAM`, `HAS_HTONL`, `HAS_HTONS`, `HAS_HYPOT`, `HAS_ILOGBL`, `HAS_INETNTOP`, `HAS_INETPTON`, `HAS_INET_ATON`, `HAS_IPV6_MREQ`, `HAS_IPV6_MREQ_SOURCE`, `HAS_IP_MREQ`, `HAS_IP_MREQ_SOURCE`, `HAS_ISASCII`, `HAS_ISBLANK`, `HAS_ISLESS`, `HAS_KILLPG`, `HAS_LCHOWN`, `HAS_LINK`, `HAS_LINKAT`, `HAS_LLROUND`, `HAS_LOCKF`, `HAS_LOG1P`, `HAS_LOG2`, `HAS_LOGB`, `HAS_LROUND`, `HAS_LSTAT`, `HAS_MADVISE`, `HAS_MBLEN`, `HAS_MBRLEN`, `HAS_MBRTOWC`, `HAS_MBSTOWCS`, `HAS_MBTOWC`, `HAS_MEMMEM`, `HAS_MEMRCHR`, `HAS_MKDTEMP`, `HAS_MKFIFO`, `HAS_MKOSTEMP`, `HAS_MKSTEMP`, `HAS_MKSTEMPS`, `HAS_MMAP`, `HAS_MPROTECT`, `HAS_MSG`, `HAS_MSYNC`, `HAS_MUNMAP`, `HAS_NEARBYINT`, `HAS_NEXTAFTER`, `HAS_NICE`, `HAS_NTOHL`, `HAS_NTOHS`, `HAS_PATHCONF`, `HAS_PAUSE`, `HAS_PHOSTNAME`, `HAS_PIPE`, `HAS_PIPE2`, `HAS_PRCTL`, `HAS_PTRDIFF_T`, `HAS_READLINK`, `HAS_READV`, `HAS_RECVMSG`, `HAS_REMQUO`, `HAS_RENAME`, `HAS_RENAMEAT`, `HAS_RINT`, `HAS_ROUND`, `HAS_SCALBNL`, `HAS_SEM`, `HAS_SENDMSG`, `HAS_SETEGID`, `HAS_SETEUID`, `HAS_SETGROUPS`, `HAS_SETHOSTENT`, `HAS_SETLINEBUF`, `HAS_SETNETENT`, `HAS_SETPGRP`, `HAS_SETPGRP2`, `HAS_SETPRIORITY`, `HAS_SETPROCTITLE`, `HAS_SETPROTOENT`, `HAS_SETREGID`, `HAS_SETRESGID`, `HAS_SETRESUID`, `HAS_SETREUID`, `HAS_SETRGID`, `HAS_SETRUID`, `HAS_SETSERVENT`, `HAS_SETSID`, `HAS_SHM`, `HAS_SIGACTION`, `HAS_SIGPROCMASK`, `HAS_SIN6_SCOPE_ID`, `HAS_SNPRINTF`, `HAS_STAT`, `HAS_STRCOLL`, `HAS_STRERROR_L`, `HAS_STRLCAT`, `HAS_STRLCPY`, `HAS_STRNLEN`, `HAS_STRTOD`, `HAS_STRTOL`, `HAS_STRTOLL`, `HAS_STRTOQ`, `HAS_STRTOUL`, `HAS_STRTOULL`, `HAS_STRTOUQ`, `HAS_STRXFRM`, `HAS_STRXFRM_L`, `HAS_SYMLINK`, `HAS_SYSCALL`, `HAS_SYSCONF`, `HAS_SYSTEM`, `HAS_SYS_ERRLIST`, `HAS_TCGETPGRP`, `HAS_TCSETPGRP`, `HAS_TOWLOWER`, `HAS_TOWUPPER`, `HAS_TRUNCATE`, `HAS_TRUNCL`, `HAS_UALARM`, `HAS_UMASK`, `HAS_UNLINKAT`, `HAS_UNSETENV`, `HAS_VFORK`, `HAS_VSNPRINTF`, `HAS_WAIT4`, `HAS_WAITPID`, `HAS_WCRTOMB`, `HAS_WCSCMP`, `HAS_WCSTOMBS`, `HAS_WCSXFRM`, `HAS_WCTOMB`, `HAS_WRITEV`, `HAS__FWALK`
And, the reentrant capabilities:
`HAS_CRYPT_R`, `HAS_CTERMID_R`, `HAS_DRAND48_R`, `HAS_ENDHOSTENT_R`, `HAS_ENDNETENT_R`, `HAS_ENDPROTOENT_R`, `HAS_ENDSERVENT_R`, `HAS_GETGRGID_R`, `HAS_GETGRNAM_R`, `HAS_GETHOSTBYADDR_R`, `HAS_GETHOSTBYNAME_R`, `HAS_GETHOSTENT_R`, `HAS_GETLOGIN_R`, `HAS_GETNETBYADDR_R`, `HAS_GETNETBYNAME_R`, `HAS_GETNETENT_R`, `HAS_GETPROTOBYNAME_R`, `HAS_GETPROTOBYNUMBER_R`, `HAS_GETPROTOENT_R`, `HAS_GETPWNAM_R`, `HAS_GETPWUID_R`, `HAS_GETSERVBYNAME_R`, `HAS_GETSERVBYPORT_R`, `HAS_GETSERVENT_R`, `HAS_GETSPNAM_R`, `HAS_RANDOM_R`, `HAS_READDIR_R`, `HAS_SETHOSTENT_R`, `HAS_SETNETENT_R`, `HAS_SETPROTOENT_R`, `HAS_SETSERVENT_R`, `HAS_SRAND48_R`, `HAS_SRANDOM_R`, `HAS_STRERROR_R`, `HAS_TMPNAM_R`, `HAS_TTYNAME_R`
Example usage:
```
#ifdef HAS_STRNLEN
use strnlen()
#else
use an alternative implementation
#endif
```
###
List of `#include` needed symbols
This list contains symbols that indicate if certain `#include` files are present on the platform. If your code accesses the functionality that one of these is for, you will need to `#include` it if the symbol on this list is `#define`d. For more detail, see the corresponding entry in *config.h*.
`I_ARPA_INET`, `I_BFD`, `I_CRYPT`, `I_DBM`, `I_DLFCN`, `I_EXECINFO`, `I_FP`, `I_FP_CLASS`, `I_GDBM`, `I_GDBMNDBM`, `I_GDBM_NDBM`, `I_GRP`, `I_IEEEFP`, `I_INTTYPES`, `I_LIBUTIL`, `I_MNTENT`, `I_NDBM`, `I_NETDB`, `I_NETINET_IN`, `I_NETINET_TCP`, `I_NET_ERRNO`, `I_PROT`, `I_PWD`, `I_RPCSVC_DBM`, `I_SGTTY`, `I_SHADOW`, `I_STDBOOL`, `I_STDINT`, `I_SUNMATH`, `I_SYSLOG`, `I_SYSMODE`, `I_SYSUIO`, `I_SYSUTSNAME`, `I_SYS_ACCESS`, `I_SYS_IOCTL`, `I_SYS_MOUNT`, `I_SYS_PARAM`, `I_SYS_POLL`, `I_SYS_SECURITY`, `I_SYS_SELECT`, `I_SYS_STAT`, `I_SYS_STATVFS`, `I_SYS_TIME`, `I_SYS_TIMES`, `I_SYS_TIME_KERNEL`, `I_SYS_TYPES`, `I_SYS_UN`, `I_SYS_VFS`, `I_SYS_WAIT`, `I_TERMIO`, `I_TERMIOS`, `I_UNISTD`, `I_USTAT`, `I_VFORK`, `I_WCHAR`, `I_WCTYPE`
Example usage:
```
#ifdef I_WCHAR
#include <wchar.h>
#endif
```
Global Variables
-----------------
These variables are global to an entire process. They are shared between all interpreters and all threads in a process. Any variables not documented here may be changed or removed without notice, so don't use them! If you feel you really do need to use an unlisted variable, first send email to [[email protected]](mailto:[email protected]). It may be that someone there will point out a way to accomplish what you need without using an internal variable. But if not, you should get a go-ahead to document and then use the variable.
`PL_check` Array, indexed by opcode, of functions that will be called for the "check" phase of optree building during compilation of Perl code. For most (but not all) types of op, once the op has been initially built and populated with child ops it will be filtered through the check function referenced by the appropriate element of this array. The new op is passed in as the sole argument to the check function, and the check function returns the completed op. The check function may (as the name suggests) check the op for validity and signal errors. It may also initialise or modify parts of the ops, or perform more radical surgery such as adding or removing child ops, or even throw the op away and return a different op in its place.
This array of function pointers is a convenient place to hook into the compilation process. An XS module can put its own custom check function in place of any of the standard ones, to influence the compilation of a particular type of op. However, a custom check function must never fully replace a standard check function (or even a custom check function from another module). A module modifying checking must instead **wrap** the preexisting check function. A custom check function must be selective about when to apply its custom behaviour. In the usual case where it decides not to do anything special with an op, it must chain the preexisting op function. Check functions are thus linked in a chain, with the core's base checker at the end.
For thread safety, modules should not write directly to this array. Instead, use the function ["wrap\_op\_checker"](#wrap_op_checker).
`PL_keyword_plugin` NOTE: `PL_keyword_plugin` is **experimental** and may change or be removed without notice.
Function pointer, pointing at a function used to handle extended keywords. The function should be declared as
```
int keyword_plugin_function(pTHX_
char *keyword_ptr, STRLEN keyword_len,
OP **op_ptr)
```
The function is called from the tokeniser, whenever a possible keyword is seen. `keyword_ptr` points at the word in the parser's input buffer, and `keyword_len` gives its length; it is not null-terminated. The function is expected to examine the word, and possibly other state such as [%^H](perlvar#%25%5EH), to decide whether it wants to handle it as an extended keyword. If it does not, the function should return `KEYWORD_PLUGIN_DECLINE`, and the normal parser process will continue.
If the function wants to handle the keyword, it first must parse anything following the keyword that is part of the syntax introduced by the keyword. See ["Lexer interface"](#Lexer-interface) for details.
When a keyword is being handled, the plugin function must build a tree of `OP` structures, representing the code that was parsed. The root of the tree must be stored in `*op_ptr`. The function then returns a constant indicating the syntactic role of the construct that it has parsed: `KEYWORD_PLUGIN_STMT` if it is a complete statement, or `KEYWORD_PLUGIN_EXPR` if it is an expression. Note that a statement construct cannot be used inside an expression (except via `do BLOCK` and similar), and an expression is not a complete statement (it requires at least a terminating semicolon).
When a keyword is handled, the plugin function may also have (compile-time) side effects. It may modify `%^H`, define functions, and so on. Typically, if side effects are the main purpose of a handler, it does not wish to generate any ops to be included in the normal compilation. In this case it is still required to supply an op tree, but it suffices to generate a single null op.
That's how the `*PL_keyword_plugin` function needs to behave overall. Conventionally, however, one does not completely replace the existing handler function. Instead, take a copy of `PL_keyword_plugin` before assigning your own function pointer to it. Your handler function should look for keywords that it is interested in and handle those. Where it is not interested, it should call the saved plugin function, passing on the arguments it received. Thus `PL_keyword_plugin` actually points at a chain of handler functions, all of which have an opportunity to handle keywords, and only the last function in the chain (built into the Perl core) will normally return `KEYWORD_PLUGIN_DECLINE`.
For thread safety, modules should not set this variable directly. Instead, use the function ["wrap\_keyword\_plugin"](#wrap_keyword_plugin).
`PL_phase` A value that indicates the current Perl interpreter's phase. Possible values include `PERL_PHASE_CONSTRUCT`, `PERL_PHASE_START`, `PERL_PHASE_CHECK`, `PERL_PHASE_INIT`, `PERL_PHASE_RUN`, `PERL_PHASE_END`, and `PERL_PHASE_DESTRUCT`.
For example, the following determines whether the interpreter is in global destruction:
```
if (PL_phase == PERL_PHASE_DESTRUCT) {
// we are in global destruction
}
```
`PL_phase` was introduced in Perl 5.14; in prior perls you can use `PL_dirty` (boolean) to determine whether the interpreter is in global destruction. (Use of `PL_dirty` is discouraged since 5.14.)
```
enum perl_phase PL_phase
```
GV Handling and Stashes
------------------------
A GV is a structure which corresponds to to a Perl typeglob, ie \*foo. It is a structure that holds a pointer to a scalar, an array, a hash etc, corresponding to $foo, @foo, %foo.
GVs are usually found as values in stashes (symbol table hashes) where Perl stores its global variables.
A **stash** is a hash that contains all variables that are defined within a package. See ["Stashes and Globs" in perlguts](perlguts#Stashes-and-Globs)
`amagic_call` Perform the overloaded (active magic) operation given by `method`. `method` is one of the values found in *overload.h*.
`flags` affects how the operation is performed, as follows:
`AMGf_noleft` `left` is not to be used in this operation.
`AMGf_noright` `right` is not to be used in this operation.
`AMGf_unary` The operation is done only on just one operand.
`AMGf_assign` The operation changes one of the operands, e.g., $x += 1
```
SV* amagic_call(SV* left, SV* right, int method, int dir)
```
`amagic_deref_call` Perform `method` overloading dereferencing on `ref`, returning the dereferenced result. `method` must be one of the dereference operations given in *overload.h*.
If overloading is inactive on `ref`, returns `ref` itself.
```
SV * amagic_deref_call(SV *ref, int method)
```
`gv_add_by_type` Make sure there is a slot of type `type` in the GV `gv`.
```
GV* gv_add_by_type(GV *gv, svtype type)
```
`Gv_AMupdate` Recalculates overload magic in the package given by `stash`.
Returns:
1 on success and there is some overload
0 if there is no overload
-1 if some error occurred and it couldn't croak (because `destructing` is true).
```
int Gv_AMupdate(HV* stash, bool destructing)
```
`gv_autoload4` Equivalent to `["gv\_autoload\_pvn"](#gv_autoload_pvn)`.
```
GV* gv_autoload4(HV* stash, const char* name, STRLEN len,
I32 method)
```
`GvAV` Return the AV from the GV.
```
AV* GvAV(GV* gv)
```
`gv_AVadd` `gv_HVadd` `gv_IOadd`
`gv_SVadd` Make sure there is a slot of the given type (AV, HV, IO, SV) in the GV `gv`.
```
GV* gv_AVadd(GV *gv)
GV* gv_HVadd(GV *gv)
GV* gv_IOadd(GV* gv)
GV* gv_SVadd(GV *gv)
```
`gv_const_sv` If `gv` is a typeglob whose subroutine entry is a constant sub eligible for inlining, or `gv` is a placeholder reference that would be promoted to such a typeglob, then returns the value returned by the sub. Otherwise, returns `NULL`.
```
SV* gv_const_sv(GV* gv)
```
`GvCV` Return the CV from the GV.
```
CV* GvCV(GV* gv)
```
`gv_fetchfile`
`gv_fetchfile_flags` These return the debugger glob for the file (compiled by Perl) whose name is given by the `name` parameter.
There are currently exactly two differences between these functions.
The `name` parameter to `gv_fetchfile` is a C string, meaning it is `NUL`-terminated; whereas the `name` parameter to `gv_fetchfile_flags` is a Perl string, whose length (in bytes) is passed in via the `namelen` parameter This means the name may contain embedded `NUL` characters. `namelen` doesn't exist in plain `gv_fetchfile`).
The other difference is that `gv_fetchfile_flags` has an extra `flags` parameter, which is currently completely ignored, but allows for possible future extensions.
```
GV* gv_fetchfile (const char* name)
GV* gv_fetchfile_flags(const char *const name, const STRLEN len,
const U32 flags)
```
`gv_fetchmeth` Like ["gv\_fetchmeth\_pvn"](#gv_fetchmeth_pvn), but lacks a flags parameter.
```
GV* gv_fetchmeth(HV* stash, const char* name, STRLEN len,
I32 level)
```
`gv_fetchmethod` See ["gv\_fetchmethod\_autoload"](#gv_fetchmethod_autoload).
```
GV* gv_fetchmethod(HV* stash, const char* name)
```
`gv_fetchmethod_autoload` Returns the glob which contains the subroutine to call to invoke the method on the `stash`. In fact in the presence of autoloading this may be the glob for "AUTOLOAD". In this case the corresponding variable `$AUTOLOAD` is already setup.
The third parameter of `gv_fetchmethod_autoload` determines whether AUTOLOAD lookup is performed if the given method is not present: non-zero means yes, look for AUTOLOAD; zero means no, don't look for AUTOLOAD. Calling `gv_fetchmethod` is equivalent to calling `gv_fetchmethod_autoload` with a non-zero `autoload` parameter.
These functions grant `"SUPER"` token as a prefix of the method name. Note that if you want to keep the returned glob for a long time, you need to check for it being "AUTOLOAD", since at the later time the call may load a different subroutine due to `$AUTOLOAD` changing its value. Use the glob created as a side effect to do this.
These functions have the same side-effects as `gv_fetchmeth` with `level==0`. The warning against passing the GV returned by `gv_fetchmeth` to `call_sv` applies equally to these functions.
```
GV* gv_fetchmethod_autoload(HV* stash, const char* name,
I32 autoload)
```
`gv_fetchmeth_autoload` This is the old form of ["gv\_fetchmeth\_pvn\_autoload"](#gv_fetchmeth_pvn_autoload), which has no flags parameter.
```
GV* gv_fetchmeth_autoload(HV* stash, const char* name,
STRLEN len, I32 level)
```
`gv_fetchmeth_pv` Exactly like ["gv\_fetchmeth\_pvn"](#gv_fetchmeth_pvn), but takes a nul-terminated string instead of a string/length pair.
```
GV* gv_fetchmeth_pv(HV* stash, const char* name, I32 level,
U32 flags)
```
`gv_fetchmeth_pvn` Returns the glob with the given `name` and a defined subroutine or `NULL`. The glob lives in the given `stash`, or in the stashes accessible via `@ISA` and `UNIVERSAL::`.
The argument `level` should be either 0 or -1. If `level==0`, as a side-effect creates a glob with the given `name` in the given `stash` which in the case of success contains an alias for the subroutine, and sets up caching info for this glob.
The only significant values for `flags` are `GV_SUPER`, `GV_NOUNIVERSAL`, and `SVf_UTF8`.
`GV_SUPER` indicates that we want to look up the method in the superclasses of the `stash`.
`GV_NOUNIVERSAL` indicates that we do not want to look up the method in the stash accessible by `UNIVERSAL::`.
The GV returned from `gv_fetchmeth` may be a method cache entry, which is not visible to Perl code. So when calling `call_sv`, you should not use the GV directly; instead, you should use the method's CV, which can be obtained from the GV with the `GvCV` macro.
```
GV* gv_fetchmeth_pvn(HV* stash, const char* name, STRLEN len,
I32 level, U32 flags)
```
`gv_fetchmeth_pvn_autoload` Same as `gv_fetchmeth_pvn()`, but looks for autoloaded subroutines too. Returns a glob for the subroutine.
For an autoloaded subroutine without a GV, will create a GV even if `level < 0`. For an autoloaded subroutine without a stub, `GvCV()` of the result may be zero.
Currently, the only significant value for `flags` is `SVf_UTF8`.
```
GV* gv_fetchmeth_pvn_autoload(HV* stash, const char* name,
STRLEN len, I32 level, U32 flags)
```
`gv_fetchmeth_pv_autoload` Exactly like ["gv\_fetchmeth\_pvn\_autoload"](#gv_fetchmeth_pvn_autoload), but takes a nul-terminated string instead of a string/length pair.
```
GV* gv_fetchmeth_pv_autoload(HV* stash, const char* name,
I32 level, U32 flags)
```
`gv_fetchmeth_sv` Exactly like ["gv\_fetchmeth\_pvn"](#gv_fetchmeth_pvn), but takes the name string in the form of an SV instead of a string/length pair.
```
GV* gv_fetchmeth_sv(HV* stash, SV* namesv, I32 level, U32 flags)
```
`gv_fetchmeth_sv_autoload` Exactly like ["gv\_fetchmeth\_pvn\_autoload"](#gv_fetchmeth_pvn_autoload), but takes the name string in the form of an SV instead of a string/length pair.
```
GV* gv_fetchmeth_sv_autoload(HV* stash, SV* namesv, I32 level,
U32 flags)
```
`gv_fetchpv` `gv_fetchpvn` `gv_fetchpvn_flags` `gv_fetchpvs` `gv_fetchsv`
`gv_fetchsv_nomg` These all return the GV of type `sv_type` whose name is given by the inputs, or NULL if no GV of that name and type could be found. See ["Stashes and Globs" in perlguts](perlguts#Stashes-and-Globs).
The only differences are how the input name is specified, and if 'get' magic is normally used in getting that name.
Don't be fooled by the fact that only one form has `flags` in its name. They all have a `flags` parameter in fact, and all the flag bits have the same meanings for all
If any of the flags `GV_ADD`, `GV_ADDMG`, `GV_ADDWARN`, `GV_ADDMULTI`, or `GV_NOINIT` is set, a GV is created if none already exists for the input name and type. However, `GV_ADDMG` will only do the creation for magical GV's. For all of these flags except `GV_NOINIT`, `["gv\_init\_pvn"](#gv_init_pvn)` is called after the addition. `GV_ADDWARN` is used when the caller expects that adding won't be necessary because the symbol should already exist; but if not, add it anyway, with a warning that it was unexpectedly absent. The `GV_ADDMULTI` flag means to pretend that the GV has been seen before (*i.e.*, suppress "Used once" warnings).
The flag `GV_NOADD_NOINIT` causes `["gv\_init\_pvn"](#gv_init_pvn)` not be to called if the GV existed but isn't PVGV.
If the `SVf_UTF8` bit is set, the name is treated as being encoded in UTF-8; otherwise the name won't be considered to be UTF-8 in the `pv`-named forms, and the UTF-8ness of the underlying SVs will be used in the `sv` forms.
If the flag `GV_NOTQUAL` is set, the caller warrants that the input name is a plain symbol name, not qualified with a package, otherwise the name is checked for being a qualified one.
In `gv_fetchpv`, `nambeg` is a C string, NUL-terminated with no intermediate NULs.
In `gv_fetchpvs`, `name` is a literal C string, hence is enclosed in double quotes.
`gv_fetchpvn` and `gv_fetchpvn_flags` are identical. In these, <nambeg> is a Perl string whose byte length is given by `full_len`, and may contain embedded NULs.
In `gv_fetchsv` and `gv_fetchsv_nomg`, the name is extracted from the PV of the input `name` SV. The only difference between these two forms is that 'get' magic is normally done on `name` in `gv_fetchsv`, and always skipped with `gv_fetchsv_nomg`. Including `GV_NO_SVGMAGIC` in the `flags` parameter to `gv_fetchsv` makes it behave identically to `gv_fetchsv_nomg`.
```
GV* gv_fetchpv (const char *nambeg, I32 flags,
const svtype sv_type)
GV * gv_fetchpvn (const char * nambeg, STRLEN full_len,
I32 flags, const svtype sv_type)
GV* gv_fetchpvn_flags(const char* name, STRLEN len, I32 flags,
const svtype sv_type)
GV * gv_fetchpvs ("name", I32 flags, const svtype sv_type)
GV* gv_fetchsv (SV *name, I32 flags, const svtype sv_type)
GV * gv_fetchsv_nomg (SV *name, I32 flags, const svtype sv_type)
```
`gv_fullname3` `gv_fullname4` `gv_efullname3`
`gv_efullname4` Place the full package name of `gv` into `sv`. The `gv_e*` forms return instead the effective package name (see ["HvENAME"](#HvENAME)).
If `prefix` is non-NULL, it is considered to be a C language NUL-terminated string, and the stored name will be prefaced with it.
The other difference between the functions is that the `*4` forms have an extra parameter, `keepmain`. If `true` an initial `main::` in the name is kept; if `false` it is stripped. With the `*3` forms, it is always kept.
```
void gv_fullname3 (SV* sv, const GV* gv, const char* prefix)
void gv_fullname4 (SV* sv, const GV* gv, const char* prefix,
bool keepmain)
void gv_efullname3(SV* sv, const GV* gv, const char* prefix)
void gv_efullname4(SV* sv, const GV* gv, const char* prefix,
bool keepmain)
```
`GvHV` Return the HV from the GV.
```
HV* GvHV(GV* gv)
```
`gv_init` The old form of `gv_init_pvn()`. It does not work with UTF-8 strings, as it has no flags parameter. If the `multi` parameter is set, the `GV_ADDMULTI` flag will be passed to `gv_init_pvn()`.
```
void gv_init(GV* gv, HV* stash, const char* name, STRLEN len,
int multi)
```
`gv_init_pv` Same as `gv_init_pvn()`, but takes a nul-terminated string for the name instead of separate char \* and length parameters.
```
void gv_init_pv(GV* gv, HV* stash, const char* name, U32 flags)
```
`gv_init_pvn` Converts a scalar into a typeglob. This is an incoercible typeglob; assigning a reference to it will assign to one of its slots, instead of overwriting it as happens with typeglobs created by `SvSetSV`. Converting any scalar that is `SvOK()` may produce unpredictable results and is reserved for perl's internal use.
`gv` is the scalar to be converted.
`stash` is the parent stash/package, if any.
`name` and `len` give the name. The name must be unqualified; that is, it must not include the package name. If `gv` is a stash element, it is the caller's responsibility to ensure that the name passed to this function matches the name of the element. If it does not match, perl's internal bookkeeping will get out of sync.
`flags` can be set to `SVf_UTF8` if `name` is a UTF-8 string, or the return value of SvUTF8(sv). It can also take the `GV_ADDMULTI` flag, which means to pretend that the GV has been seen before (i.e., suppress "Used once" warnings).
```
void gv_init_pvn(GV* gv, HV* stash, const char* name, STRLEN len,
U32 flags)
```
`gv_init_sv` Same as `gv_init_pvn()`, but takes an SV \* for the name instead of separate char \* and length parameters. `flags` is currently unused.
```
void gv_init_sv(GV* gv, HV* stash, SV* namesv, U32 flags)
```
`gv_stashpv` Returns a pointer to the stash for a specified package. Uses `strlen` to determine the length of `name`, then calls `gv_stashpvn()`.
```
HV* gv_stashpv(const char* name, I32 flags)
```
`gv_stashpvn` Returns a pointer to the stash for a specified package. The `namelen` parameter indicates the length of the `name`, in bytes. `flags` is passed to `gv_fetchpvn_flags()`, so if set to `GV_ADD` then the package will be created if it does not already exist. If the package does not exist and `flags` is 0 (or any other setting that does not create packages) then `NULL` is returned.
Flags may be one of:
```
GV_ADD Create and initialize the package if doesn't
already exist
GV_NOADD_NOINIT Don't create the package,
GV_ADDMG GV_ADD iff the GV is magical
GV_NOINIT GV_ADD, but don't initialize
GV_NOEXPAND Don't expand SvOK() entries to PVGV
SVf_UTF8 The name is in UTF-8
```
The most important of which are probably `GV_ADD` and `SVf_UTF8`.
Note, use of `gv_stashsv` instead of `gv_stashpvn` where possible is strongly recommended for performance reasons.
```
HV* gv_stashpvn(const char* name, U32 namelen, I32 flags)
```
`gv_stashpvs` Like `gv_stashpvn`, but takes a literal string instead of a string/length pair.
```
HV* gv_stashpvs("name", I32 create)
```
`gv_stashsv` Returns a pointer to the stash for a specified package. See `["gv\_stashpvn"](#gv_stashpvn)`.
Note this interface is strongly preferred over `gv_stashpvn` for performance reasons.
```
HV* gv_stashsv(SV* sv, I32 flags)
```
`GvSV` Return the SV from the GV.
Prior to Perl v5.9.3, this would add a scalar if none existed. Nowadays, use `["GvSVn"](#GvSVn)` for that, or compile perl with `-DPERL_CREATE_GVSV`. See [perl5100delta](https://perldoc.perl.org/5.36.0/perl5100delta).
```
SV* GvSV(GV* gv)
```
`GvSVn` Like `["GvSV"](#GvSV)`, but creates an empty scalar if none already exists.
```
SV* GvSVn(GV* gv)
```
`newGVgen`
`newGVgen_flags` Create a new, guaranteed to be unique, GV in the package given by the NUL-terminated C language string `pack`, and return a pointer to it.
For `newGVgen` or if `flags` in `newGVgen_flags` is 0, `pack` is to be considered to be encoded in Latin-1. The only other legal `flags` value is `SVf_UTF8`, which indicates `pack` is to be considered to be encoded in UTF-8.
```
GV* newGVgen (const char* pack)
GV* newGVgen_flags(const char* pack, U32 flags)
```
`PL_curstash` The stash for the package code will be compiled into.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
HV* PL_curstash
```
`PL_defgv` The GV representing `*_`. Useful for access to `$_`.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
GV * PL_defgv
```
`PL_defstash` Described in <perlguts>.
`save_gp` Saves the current GP of gv on the save stack to be restored on scope exit.
If `empty` is true, replace the GP with a new GP.
If `empty` is false, mark `gv` with `GVf_INTRO` so the next reference assigned is localized, which is how `local *foo = $someref;` works.
```
void save_gp(GV* gv, I32 empty)
```
`setdefout` Sets `PL_defoutgv`, the default file handle for output, to the passed in typeglob. As `PL_defoutgv` "owns" a reference on its typeglob, the reference count of the passed in typeglob is increased by one, and the reference count of the typeglob that `PL_defoutgv` points to is decreased by one.
```
void setdefout(GV* gv)
```
Hook manipulation
------------------
These functions provide convenient and thread-safe means of manipulating hook variables.
`wrap_op_checker` Puts a C function into the chain of check functions for a specified op type. This is the preferred way to manipulate the ["PL\_check"](#PL_check) array. `opcode` specifies which type of op is to be affected. `new_checker` is a pointer to the C function that is to be added to that opcode's check chain, and `old_checker_p` points to the storage location where a pointer to the next function in the chain will be stored. The value of `new_checker` is written into the ["PL\_check"](#PL_check) array, while the value previously stored there is written to `*old_checker_p`.
["PL\_check"](#PL_check) is global to an entire process, and a module wishing to hook op checking may find itself invoked more than once per process, typically in different threads. To handle that situation, this function is idempotent. The location `*old_checker_p` must initially (once per process) contain a null pointer. A C variable of static duration (declared at file scope, typically also marked `static` to give it internal linkage) will be implicitly initialised appropriately, if it does not have an explicit initialiser. This function will only actually modify the check chain if it finds `*old_checker_p` to be null. This function is also thread safe on the small scale. It uses appropriate locking to avoid race conditions in accessing ["PL\_check"](#PL_check).
When this function is called, the function referenced by `new_checker` must be ready to be called, except for `*old_checker_p` being unfilled. In a threading situation, `new_checker` may be called immediately, even before this function has returned. `*old_checker_p` will always be appropriately set before `new_checker` is called. If `new_checker` decides not to do anything special with an op that it is given (which is the usual case for most uses of op check hooking), it must chain the check function referenced by `*old_checker_p`.
Taken all together, XS code to hook an op checker should typically look something like this:
```
static Perl_check_t nxck_frob;
static OP *myck_frob(pTHX_ OP *op) {
...
op = nxck_frob(aTHX_ op);
...
return op;
}
BOOT:
wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
```
If you want to influence compilation of calls to a specific subroutine, then use ["cv\_set\_call\_checker\_flags"](#cv_set_call_checker_flags) rather than hooking checking of all `entersub` ops.
```
void wrap_op_checker(Optype opcode, Perl_check_t new_checker,
Perl_check_t *old_checker_p)
```
HV Handling
------------
A HV structure represents a Perl hash. It consists mainly of an array of pointers, each of which points to a linked list of HE structures. The array is indexed by the hash function of the key, so each linked list represents all the hash entries with the same hash value. Each HE contains a pointer to the actual value, plus a pointer to a HEK structure which holds the key and hash value.
`get_hv` Returns the HV of the specified Perl hash. `flags` are passed to `gv_fetchpv`. If `GV_ADD` is set and the Perl variable does not exist then it will be created. If `flags` is zero and the variable does not exist then `NULL` is returned.
NOTE: the `perl_get_hv()` form is **deprecated**.
```
HV* get_hv(const char *name, I32 flags)
```
`HE` Described in <perlguts>.
`HEf_SVKEY` This flag, used in the length slot of hash entries and magic structures, specifies the structure contains an `SV*` pointer where a `char*` pointer is to be expected. (For information only--not to be used).
`HeHASH` Returns the computed hash stored in the hash entry.
```
U32 HeHASH(HE* he)
```
`HeKEY` Returns the actual pointer stored in the key slot of the hash entry. The pointer may be either `char*` or `SV*`, depending on the value of `HeKLEN()`. Can be assigned to. The `HePV()` or `HeSVKEY()` macros are usually preferable for finding the value of a key.
```
void* HeKEY(HE* he)
```
`HeKLEN` If this is negative, and amounts to `HEf_SVKEY`, it indicates the entry holds an `SV*` key. Otherwise, holds the actual length of the key. Can be assigned to. The `HePV()` macro is usually preferable for finding key lengths.
```
STRLEN HeKLEN(HE* he)
```
`HePV` Returns the key slot of the hash entry as a `char*` value, doing any necessary dereferencing of possibly `SV*` keys. The length of the string is placed in `len` (this is a macro, so do *not* use `&len`). If you do not care about what the length of the key is, you may use the global variable `PL_na`, though this is rather less efficient than using a local variable. Remember though, that hash keys in perl are free to contain embedded nulls, so using `strlen()` or similar is not a good way to find the length of hash keys. This is very similar to the `SvPV()` macro described elsewhere in this document. See also `["HeUTF8"](#HeUTF8)`.
If you are using `HePV` to get values to pass to `newSVpvn()` to create a new SV, you should consider using `newSVhek(HeKEY_hek(he))` as it is more efficient.
```
char* HePV(HE* he, STRLEN len)
```
`HeSVKEY` Returns the key as an `SV*`, or `NULL` if the hash entry does not contain an `SV*` key.
```
SV* HeSVKEY(HE* he)
```
`HeSVKEY_force` Returns the key as an `SV*`. Will create and return a temporary mortal `SV*` if the hash entry contains only a `char*` key.
```
SV* HeSVKEY_force(HE* he)
```
`HeSVKEY_set` Sets the key to a given `SV*`, taking care to set the appropriate flags to indicate the presence of an `SV*` key, and returns the same `SV*`.
```
SV* HeSVKEY_set(HE* he, SV* sv)
```
`HeUTF8` Returns whether the `char *` value returned by `HePV` is encoded in UTF-8, doing any necessary dereferencing of possibly `SV*` keys. The value returned will be 0 or non-0, not necessarily 1 (or even a value with any low bits set), so **do not** blindly assign this to a `bool` variable, as `bool` may be a typedef for `char`.
```
U32 HeUTF8(HE* he)
```
`HeVAL` Returns the value slot (type `SV*`) stored in the hash entry. Can be assigned to.
```
SV *foo= HeVAL(hv);
HeVAL(hv)= sv;
```
```
SV* HeVAL(HE* he)
```
`HV` Described in <perlguts>.
`hv_assert` Check that a hash is in an internally consistent state.
NOTE: `hv_assert` must be explicitly called as `Perl_hv_assert` with an `aTHX_` parameter.
```
void Perl_hv_assert(pTHX_ HV *hv)
```
`hv_bucket_ratio` NOTE: `hv_bucket_ratio` is **experimental** and may change or be removed without notice.
If the hash is tied dispatches through to the SCALAR tied method, otherwise if the hash contains no keys returns 0, otherwise returns a mortal sv containing a string specifying the number of used buckets, followed by a slash, followed by the number of available buckets.
This function is expensive, it must scan all of the buckets to determine which are used, and the count is NOT cached. In a large hash this could be a lot of buckets.
```
SV* hv_bucket_ratio(HV *hv)
```
`hv_clear` Frees all the elements of a hash, leaving it empty. The XS equivalent of `%hash = ()`. See also ["hv\_undef"](#hv_undef).
See ["av\_clear"](#av_clear) for a note about the hash possibly being invalid on return.
```
void hv_clear(HV *hv)
```
`hv_clear_placeholders` Clears any placeholders from a hash. If a restricted hash has any of its keys marked as readonly and the key is subsequently deleted, the key is not actually deleted but is marked by assigning it a value of `&PL_sv_placeholder`. This tags it so it will be ignored by future operations such as iterating over the hash, but will still allow the hash to have a value reassigned to the key at some future point. This function clears any such placeholder keys from the hash. See `[Hash::Util::lock\_keys()](Hash::Util#lock_keys)` for an example of its use.
```
void hv_clear_placeholders(HV *hv)
```
`hv_copy_hints_hv` A specialised version of ["newHVhv"](#newHVhv) for copying `%^H`. `ohv` must be a pointer to a hash (which may have `%^H` magic, but should be generally non-magical), or `NULL` (interpreted as an empty hash). The content of `ohv` is copied to a new hash, which has the `%^H`-specific magic added to it. A pointer to the new hash is returned.
```
HV * hv_copy_hints_hv(HV *const ohv)
```
`hv_delete` Deletes a key/value pair in the hash. The value's SV is removed from the hash, made mortal, and returned to the caller. The absolute value of `klen` is the length of the key. If `klen` is negative the key is assumed to be in UTF-8-encoded Unicode. The `flags` value will normally be zero; if set to `G_DISCARD` then `NULL` will be returned. `NULL` will also be returned if the key is not found.
```
SV* hv_delete(HV *hv, const char *key, I32 klen, I32 flags)
```
`hv_delete_ent` Deletes a key/value pair in the hash. The value SV is removed from the hash, made mortal, and returned to the caller. The `flags` value will normally be zero; if set to `G_DISCARD` then `NULL` will be returned. `NULL` will also be returned if the key is not found. `hash` can be a valid precomputed hash value, or 0 to ask for it to be computed.
```
SV* hv_delete_ent(HV *hv, SV *keysv, I32 flags, U32 hash)
```
`HvENAME` Returns the effective name of a stash, or NULL if there is none. The effective name represents a location in the symbol table where this stash resides. It is updated automatically when packages are aliased or deleted. A stash that is no longer in the symbol table has no effective name. This name is preferable to `HvNAME` for use in MRO linearisations and isa caches.
```
char* HvENAME(HV* stash)
```
`HvENAMELEN` Returns the length of the stash's effective name.
```
STRLEN HvENAMELEN(HV *stash)
```
`HvENAMEUTF8` Returns true if the effective name is in UTF-8 encoding.
```
unsigned char HvENAMEUTF8(HV *stash)
```
`hv_exists` Returns a boolean indicating whether the specified hash key exists. The absolute value of `klen` is the length of the key. If `klen` is negative the key is assumed to be in UTF-8-encoded Unicode.
```
bool hv_exists(HV *hv, const char *key, I32 klen)
```
`hv_exists_ent` Returns a boolean indicating whether the specified hash key exists. `hash` can be a valid precomputed hash value, or 0 to ask for it to be computed.
```
bool hv_exists_ent(HV *hv, SV *keysv, U32 hash)
```
`hv_fetch` Returns the SV which corresponds to the specified key in the hash. The absolute value of `klen` is the length of the key. If `klen` is negative the key is assumed to be in UTF-8-encoded Unicode. If `lval` is set then the fetch will be part of a store. This means that if there is no value in the hash associated with the given key, then one is created and a pointer to it is returned. The `SV*` it points to can be assigned to. But always check that the return value is non-null before dereferencing it to an `SV*`.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied hashes.
```
SV** hv_fetch(HV *hv, const char *key, I32 klen, I32 lval)
```
`hv_fetchs` Like `hv_fetch`, but takes a literal string instead of a string/length pair.
```
SV** hv_fetchs(HV* tb, "key", I32 lval)
```
`hv_fetch_ent` Returns the hash entry which corresponds to the specified key in the hash. `hash` must be a valid precomputed hash number for the given `key`, or 0 if you want the function to compute it. IF `lval` is set then the fetch will be part of a store. Make sure the return value is non-null before accessing it. The return value when `hv` is a tied hash is a pointer to a static location, so be sure to make a copy of the structure if you need to store it somewhere.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied hashes.
```
HE* hv_fetch_ent(HV *hv, SV *keysv, I32 lval, U32 hash)
```
`HvFILL` Returns the number of hash buckets that happen to be in use.
As of perl 5.25 this function is used only for debugging purposes, and the number of used hash buckets is not in any way cached, thus this function can be costly to execute as it must iterate over all the buckets in the hash.
```
STRLEN HvFILL(HV *const hv)
```
`hv_iterinit` Prepares a starting point to traverse a hash table. Returns the number of keys in the hash, including placeholders (i.e. the same as `HvTOTALKEYS(hv)`). The return value is currently only meaningful for hashes without tie magic.
NOTE: Before version 5.004\_65, `hv_iterinit` used to return the number of hash buckets that happen to be in use. If you still need that esoteric value, you can get it through the macro `HvFILL(hv)`.
```
I32 hv_iterinit(HV *hv)
```
`hv_iterkey` Returns the key from the current position of the hash iterator. See `["hv\_iterinit"](#hv_iterinit)`.
```
char* hv_iterkey(HE* entry, I32* retlen)
```
`hv_iterkeysv` Returns the key as an `SV*` from the current position of the hash iterator. The return value will always be a mortal copy of the key. Also see `["hv\_iterinit"](#hv_iterinit)`.
```
SV* hv_iterkeysv(HE* entry)
```
`hv_iternext` Returns entries from a hash iterator. See `["hv\_iterinit"](#hv_iterinit)`.
You may call `hv_delete` or `hv_delete_ent` on the hash entry that the iterator currently points to, without losing your place or invalidating your iterator. Note that in this case the current entry is deleted from the hash with your iterator holding the last reference to it. Your iterator is flagged to free the entry on the next call to `hv_iternext`, so you must not discard your iterator immediately else the entry will leak - call `hv_iternext` to trigger the resource deallocation.
```
HE* hv_iternext(HV *hv)
```
`hv_iternextsv` Performs an `hv_iternext`, `hv_iterkey`, and `hv_iterval` in one operation.
```
SV* hv_iternextsv(HV *hv, char **key, I32 *retlen)
```
`hv_iternext_flags` NOTE: `hv_iternext_flags` is **experimental** and may change or be removed without notice.
Returns entries from a hash iterator. See `["hv\_iterinit"](#hv_iterinit)` and `["hv\_iternext"](#hv_iternext)`. The `flags` value will normally be zero; if `HV_ITERNEXT_WANTPLACEHOLDERS` is set the placeholders keys (for restricted hashes) will be returned in addition to normal keys. By default placeholders are automatically skipped over. Currently a placeholder is implemented with a value that is `&PL_sv_placeholder`. Note that the implementation of placeholders and restricted hashes may change, and the implementation currently is insufficiently abstracted for any change to be tidy.
```
HE* hv_iternext_flags(HV *hv, I32 flags)
```
`hv_iterval` Returns the value from the current position of the hash iterator. See `["hv\_iterkey"](#hv_iterkey)`.
```
SV* hv_iterval(HV *hv, HE *entry)
```
`hv_magic` Adds magic to a hash. See `["sv\_magic"](#sv_magic)`.
```
void hv_magic(HV *hv, GV *gv, int how)
```
`HvNAME` Returns the package name of a stash, or `NULL` if `stash` isn't a stash. See `["SvSTASH"](#SvSTASH)`, `["CvSTASH"](#CvSTASH)`.
```
char* HvNAME(HV* stash)
```
`HvNAMELEN` Returns the length of the stash's name.
Disfavored forms of HvNAME and HvNAMELEN; suppress mention of them
```
STRLEN HvNAMELEN(HV *stash)
```
`HvNAMEUTF8` Returns true if the name is in UTF-8 encoding.
```
unsigned char HvNAMEUTF8(HV *stash)
```
`hv_scalar` Evaluates the hash in scalar context and returns the result.
When the hash is tied dispatches through to the SCALAR method, otherwise returns a mortal SV containing the number of keys in the hash.
Note, prior to 5.25 this function returned what is now returned by the hv\_bucket\_ratio() function.
```
SV* hv_scalar(HV *hv)
```
`hv_store` Stores an SV in a hash. The hash key is specified as `key` and the absolute value of `klen` is the length of the key. If `klen` is negative the key is assumed to be in UTF-8-encoded Unicode. The `hash` parameter is the precomputed hash value; if it is zero then Perl will compute it.
The return value will be `NULL` if the operation failed or if the value did not need to be actually stored within the hash (as in the case of tied hashes). Otherwise it can be dereferenced to get the original `SV*`. Note that the caller is responsible for suitably incrementing the reference count of `val` before the call, and decrementing it if the function returned `NULL`. Effectively a successful `hv_store` takes ownership of one reference to `val`. This is usually what you want; a newly created SV has a reference count of one, so if all your code does is create SVs then store them in a hash, `hv_store` will own the only reference to the new SV, and your code doesn't need to do anything further to tidy up. `hv_store` is not implemented as a call to `hv_store_ent`, and does not create a temporary SV for the key, so if your key data is not already in SV form then use `hv_store` in preference to `hv_store_ent`.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied hashes.
```
SV** hv_store(HV *hv, const char *key, I32 klen, SV *val,
U32 hash)
```
`hv_stores` Like `hv_store`, but takes a literal string instead of a string/length pair and omits the hash parameter.
```
SV** hv_stores(HV* tb, "key", SV* val)
```
`hv_store_ent` Stores `val` in a hash. The hash key is specified as `key`. The `hash` parameter is the precomputed hash value; if it is zero then Perl will compute it. The return value is the new hash entry so created. It will be `NULL` if the operation failed or if the value did not need to be actually stored within the hash (as in the case of tied hashes). Otherwise the contents of the return value can be accessed using the `He?` macros described here. Note that the caller is responsible for suitably incrementing the reference count of `val` before the call, and decrementing it if the function returned NULL. Effectively a successful `hv_store_ent` takes ownership of one reference to `val`. This is usually what you want; a newly created SV has a reference count of one, so if all your code does is create SVs then store them in a hash, `hv_store` will own the only reference to the new SV, and your code doesn't need to do anything further to tidy up. Note that `hv_store_ent` only reads the `key`; unlike `val` it does not take ownership of it, so maintaining the correct reference count on `key` is entirely the caller's responsibility. The reason it does not take ownership, is that `key` is not used after this function returns, and so can be freed immediately. `hv_store` is not implemented as a call to `hv_store_ent`, and does not create a temporary SV for the key, so if your key data is not already in SV form then use `hv_store` in preference to `hv_store_ent`.
See ["Understanding the Magic of Tied Hashes and Arrays" in perlguts](perlguts#Understanding-the-Magic-of-Tied-Hashes-and-Arrays) for more information on how to use this function on tied hashes.
```
HE* hv_store_ent(HV *hv, SV *key, SV *val, U32 hash)
```
`hv_undef` Undefines the hash. The XS equivalent of `undef(%hash)`.
As well as freeing all the elements of the hash (like `hv_clear()`), this also frees any auxiliary data and storage associated with the hash.
See ["av\_clear"](#av_clear) for a note about the hash possibly being invalid on return.
```
void hv_undef(HV *hv)
```
`newHV` Creates a new HV. The reference count is set to 1.
```
HV* newHV()
```
`newHVhv` The content of `ohv` is copied to a new hash. A pointer to the new hash is returned.
```
HV* newHVhv(HV *hv)
```
`Nullhv` `**DEPRECATED!**` It is planned to remove `Nullhv` from a future release of Perl. Do not use it for new code; remove it from existing code.
Null HV pointer.
(deprecated - use `(HV *)NULL` instead)
`PERL_HASH` Described in <perlguts>.
```
void PERL_HASH(U32 hash, char *key, STRLEN klen)
```
`PL_modglobal` `PL_modglobal` is a general purpose, interpreter global HV for use by extensions that need to keep information on a per-interpreter basis. In a pinch, it can also be used as a symbol table for extensions to share data among each other. It is a good idea to use keys prefixed by the package name of the extension that owns the data.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
HV* PL_modglobal
```
Input/Output
-------------
`IoDIRP` Described in <perlguts>.
```
DIR * IoDIRP(IO *io)
```
`IOf_FLUSH` Described in <perlguts>.
`IoFLAGS` Described in <perlguts>.
```
U8 IoFLAGS(IO *io)
```
`IOf_UNTAINT` Described in <perlguts>.
`IoIFP` Described in <perlguts>.
```
PerlIO * IoIFP(IO *io)
```
`IoOFP` Described in <perlguts>.
```
PerlIO * IoOFP(IO *io)
```
`IoTYPE` Described in <perlguts>.
```
char IoTYPE(IO *io)
```
`my_chsize` The C library [chsize(3)](http://man.he.net/man3/chsize) if available, or a Perl implementation of it.
```
I32 my_chsize(int fd, Off_t length)
```
`my_dirfd` The C library `[dirfd(3)](http://man.he.net/man3/dirfd)` if available, or a Perl implementation of it, or die if not easily emulatable.
```
int my_dirfd(DIR* dir)
```
`my_pclose` A wrapper for the C library [pclose(3)](http://man.he.net/man3/pclose). Don't use the latter, as the Perl version knows things that interact with the rest of the perl interpreter.
```
I32 my_pclose(PerlIO* ptr)
```
`my_popen` A wrapper for the C library [popen(3)](http://man.he.net/man3/popen). Don't use the latter, as the Perl version knows things that interact with the rest of the perl interpreter.
```
PerlIO* my_popen(const char* cmd, const char* mode)
```
`newIO` Create a new IO, setting the reference count to 1.
```
IO* newIO()
```
`PERL_FLUSHALL_FOR_CHILD` This defines a way to flush all output buffers. This may be a performance issue, so we allow people to disable it. Also, if we are using stdio, there are broken implementations of fflush(NULL) out there, Solaris being the most prominent.
```
void PERL_FLUSHALL_FOR_CHILD
```
`PerlIO_apply_layers` `PerlIO_binmode` `PerlIO_canset_cnt` `PerlIO_clearerr` `PerlIO_close` `PerlIO_debug` `PerlIO_eof` `PerlIO_error` `PerlIO_exportFILE` `PerlIO_fast_gets` `PerlIO_fdopen` `PerlIO_fileno` `PerlIO_fill` `PerlIO_findFILE` `PerlIO_flush` `PerlIO_get_base` `PerlIO_get_bufsiz` `PerlIO_getc` `PerlIO_get_cnt` `PerlIO_getpos` `PerlIO_get_ptr` `PerlIO_has_base` `PerlIO_has_cntptr` `PerlIO_importFILE` `PerlIO_open` `PerlIO_printf` `PerlIO_putc` `PerlIO_puts` `PerlIO_read` `PerlIO_releaseFILE` `PerlIO_reopen` `PerlIO_rewind` `PerlIO_seek` `PerlIO_set_cnt` `PerlIO_setlinebuf` `PerlIO_setpos` `PerlIO_set_ptrcnt` `PerlIO_stderr` `PerlIO_stdin` `PerlIO_stdout` `PerlIO_stdoutf` `PerlIO_tell` `PerlIO_ungetc` `PerlIO_unread` `PerlIO_vprintf` `PerlIO_write` Described in <perlapio>.
```
int PerlIO_apply_layers(PerlIO *f, const char *mode,
const char *layers)
int PerlIO_binmode (PerlIO *f, int ptype, int imode,
const char *layers)
int PerlIO_canset_cnt (PerlIO *f)
void PerlIO_clearerr (PerlIO *f)
int PerlIO_close (PerlIO *f)
void PerlIO_debug (const char *fmt, ...)
int PerlIO_eof (PerlIO *f)
int PerlIO_error (PerlIO *f)
FILE * PerlIO_exportFILE (PerlIO *f, const char *mode)
int PerlIO_fast_gets (PerlIO *f)
PerlIO * PerlIO_fdopen (int fd, const char *mode)
int PerlIO_fileno (PerlIO *f)
int PerlIO_fill (PerlIO *f)
FILE * PerlIO_findFILE (PerlIO *f)
int PerlIO_flush (PerlIO *f)
STDCHAR * PerlIO_get_base (PerlIO *f)
SSize_t PerlIO_get_bufsiz (PerlIO *f)
int PerlIO_getc (PerlIO *d)
SSize_t PerlIO_get_cnt (PerlIO *f)
int PerlIO_getpos (PerlIO *f, SV *save)
STDCHAR * PerlIO_get_ptr (PerlIO *f)
int PerlIO_has_base (PerlIO *f)
int PerlIO_has_cntptr (PerlIO *f)
PerlIO * PerlIO_importFILE (FILE *stdio, const char *mode)
PerlIO * PerlIO_open (const char *path, const char *mode)
int PerlIO_printf (PerlIO *f, const char *fmt, ...)
int PerlIO_putc (PerlIO *f, int ch)
int PerlIO_puts (PerlIO *f, const char *string)
SSize_t PerlIO_read (PerlIO *f, void *vbuf,
Size_t count)
void PerlIO_releaseFILE (PerlIO *f, FILE *stdio)
PerlIO * PerlIO_reopen (const char *path, const char *mode,
PerlIO *old)
void PerlIO_rewind (PerlIO *f)
int PerlIO_seek (PerlIO *f, Off_t offset,
int whence)
void PerlIO_set_cnt (PerlIO *f, SSize_t cnt)
void PerlIO_setlinebuf (PerlIO *f)
int PerlIO_setpos (PerlIO *f, SV *saved)
void PerlIO_set_ptrcnt (PerlIO *f, STDCHAR *ptr,
SSize_t cnt)
PerlIO * PerlIO_stderr (PerlIO *f, const char *mode,
const char *layers)
PerlIO * PerlIO_stdin (PerlIO *f, const char *mode,
const char *layers)
PerlIO * PerlIO_stdout (PerlIO *f, const char *mode,
const char *layers)
int PerlIO_stdoutf (const char *fmt, ...)
Off_t PerlIO_tell (PerlIO *f)
int PerlIO_ungetc (PerlIO *f, int ch)
SSize_t PerlIO_unread (PerlIO *f, const void *vbuf,
Size_t count)
int PerlIO_vprintf (PerlIO *f, const char *fmt,
va_list args)
SSize_t PerlIO_write (PerlIO *f, const void *vbuf,
Size_t count)
```
`PERLIO_FUNCS_CAST` Cast the pointer `func` to be of type `PerlIO_funcs *`.
`PERLIO_FUNCS_DECL` Declare `ftab` to be a PerlIO function table, that is, of type `PerlIO_funcs`.
```
PERLIO_FUNCS_DECL(PerlIO * ftab)
```
`PERLIO_F_APPEND` `PERLIO_F_CANREAD` `PERLIO_F_CANWRITE` `PERLIO_F_CRLF` `PERLIO_F_EOF` `PERLIO_F_ERROR` `PERLIO_F_FASTGETS` `PERLIO_F_LINEBUF` `PERLIO_F_OPEN` `PERLIO_F_RDBUF` `PERLIO_F_TEMP` `PERLIO_F_TRUNCATE` `PERLIO_F_UNBUF` `PERLIO_F_UTF8` `PERLIO_F_WRBUF` Described in <perliol>.
`PERLIO_K_BUFFERED` `PERLIO_K_CANCRLF` `PERLIO_K_FASTGETS` `PERLIO_K_MULTIARG` `PERLIO_K_RAW` Described in <perliol>.
`PERLIO_NOT_STDIO` Described in <perlapio>.
`PL_maxsysfd` Described in <perliol>.
`repeatcpy` Make `count` copies of the `len` bytes beginning at `from`, placing them into memory beginning at `to`, which must be big enough to accommodate them all.
```
void repeatcpy(char* to, const char* from, I32 len, IV count)
```
`USE_STDIO` Described in <perlapio>.
Integer
-------
`CASTI32` This symbol is defined if the C compiler can cast negative or large floating point numbers to 32-bit ints.
`HAS_INT64_T` This symbol will defined if the C compiler supports `int64_t`. Usually the *inttypes.h* needs to be included, but sometimes *sys/types.h* is enough.
`HAS_LONG_LONG` This symbol will be defined if the C compiler supports long long.
`HAS_QUAD` This symbol, if defined, tells that there's a 64-bit integer type, `Quad_t`, and its unsigned counterpart, `Uquad_t`. `QUADKIND` will be one of `QUAD_IS_INT`, `QUAD_IS_LONG`, `QUAD_IS_LONG_LONG`, `QUAD_IS_INT64_T`, or `QUAD_IS___INT64`.
`I8` `I16` `I32` `I64` `IV` Described in <perlguts>.
`I32SIZE` This symbol contains the `sizeof(I32)`.
`I32TYPE` This symbol defines the C type used for Perl's I32.
`I64SIZE` This symbol contains the `sizeof(I64)`.
`I64TYPE` This symbol defines the C type used for Perl's I64.
`I16SIZE` This symbol contains the `sizeof(I16)`.
`I16TYPE` This symbol defines the C type used for Perl's I16.
`INT16_C` `INT32_C`
`INT64_C` Returns a token the C compiler recognizes for the constant `number` of the corresponding integer type on the machine.
If the machine does not have a 64-bit type, `INT64_C` is undefined. Use `["INTMAX\_C"](#INTMAX_C)` to get the largest type available on the platform.
```
I16 INT16_C(number)
I32 INT32_C(number)
I64 INT64_C(number)
```
`INTMAX_C` Returns a token the C compiler recognizes for the constant `number` of the widest integer type on the machine. For example, if the machine has `long long`s, `INTMAX_C(-1)` would yield
```
-1LL
```
See also, for example, `["INT32\_C"](#INT32_C)`.
Use ["IV"](#IV) to declare variables of the maximum usable size on this platform.
```
INTMAX_C(number)
```
`INTSIZE` This symbol contains the value of `sizeof(int)` so that the C preprocessor can make decisions based on it.
`I8SIZE` This symbol contains the `sizeof(I8)`.
`I8TYPE` This symbol defines the C type used for Perl's I8.
`IV_MAX` The largest signed integer that fits in an IV on this platform.
```
IV IV_MAX
```
`IV_MIN` The negative signed integer furthest away from 0 that fits in an IV on this platform.
```
IV IV_MIN
```
`IVSIZE` This symbol contains the `sizeof(IV)`.
`IVTYPE` This symbol defines the C type used for Perl's IV.
`line_t` The typedef to use to declare variables that are to hold line numbers.
`LONGLONGSIZE` This symbol contains the size of a long long, so that the C preprocessor can make decisions based on it. It is only defined if the system supports long long.
`LONGSIZE` This symbol contains the value of `sizeof(long)` so that the C preprocessor can make decisions based on it.
`memzero` Set the `l` bytes starting at `*d` to all zeroes.
```
void memzero(void * d, Size_t l)
```
`PERL_INT_FAST8_T` `PERL_INT_FAST16_T` `PERL_UINT_FAST8_T`
`PERL_UINT_FAST16_T` These are equivalent to the correspondingly-named C99 typedefs on platforms that have those; they evaluate to `int` and `unsigned int` on platforms that don't, so that you can portably take advantage of this C99 feature.
`PERL_INT_MAX` `PERL_INT_MIN` `PERL_LONG_MAX` `PERL_LONG_MIN` `PERL_SHORT_MAX` `PERL_SHORT_MIN` `PERL_UCHAR_MAX` `PERL_UCHAR_MIN` `PERL_UINT_MAX` `PERL_UINT_MIN` `PERL_ULONG_MAX` `PERL_ULONG_MIN` `PERL_USHORT_MAX` `PERL_USHORT_MIN` `PERL_QUAD_MAX` `PERL_QUAD_MIN` `PERL_UQUAD_MAX`
`PERL_UQUAD_MIN` These give the largest and smallest number representable in the current platform in variables of the corresponding types.
For signed types, the smallest representable number is the most negative number, the one furthest away from zero.
For C99 and later compilers, these correspond to things like `INT_MAX`, which are available to the C code. But these constants, furnished by Perl, allow code compiled on earlier compilers to portably have access to the same constants.
`SHORTSIZE` This symbol contains the value of `sizeof(short)` so that the C preprocessor can make decisions based on it.
`U8` `U16` `U32` `U64` `UV` Described in <perlguts>.
`U32SIZE` This symbol contains the `sizeof(U32)`.
`U32TYPE` This symbol defines the C type used for Perl's U32.
`U64SIZE` This symbol contains the `sizeof(U64)`.
`U64TYPE` This symbol defines the C type used for Perl's U64.
`U16SIZE` This symbol contains the `sizeof(U16)`.
`U16TYPE` This symbol defines the C type used for Perl's U16.
`UINT16_C` `UINT32_C`
`UINT64_C` Returns a token the C compiler recognizes for the constant `number` of the corresponding unsigned integer type on the machine.
If the machine does not have a 64-bit type, `UINT64_C` is undefined. Use `["UINTMAX\_C"](#UINTMAX_C)` to get the largest type available on the platform.
```
U16 UINT16_C(number)
U32 UINT32_C(number)
U64 UINT64_C(number)
```
`UINTMAX_C` Returns a token the C compiler recognizes for the constant `number` of the widest unsigned integer type on the machine. For example, if the machine has `long`s, `UINTMAX_C(1)` would yield
```
1UL
```
See also, for example, `["UINT32\_C"](#UINT32_C)`.
Use ["UV"](#UV) to declare variables of the maximum usable size on this platform.
```
UINTMAX_C(number)
```
`U8SIZE` This symbol contains the `sizeof(U8)`.
`U8TYPE` This symbol defines the C type used for Perl's U8.
`UV_MAX` The largest unsigned integer that fits in a UV on this platform.
```
UV UV_MAX
```
`UV_MIN` The smallest unsigned integer that fits in a UV on this platform. It should equal zero.
```
UV UV_MIN
```
`UVSIZE` This symbol contains the `sizeof(UV)`.
`UVTYPE` This symbol defines the C type used for Perl's UV.
`WIDEST_UTYPE` Yields the widest unsigned integer type on the platform, currently either `U32` or `U64`. This can be used in declarations such as
```
WIDEST_UTYPE my_uv;
```
or casts
```
my_uv = (WIDEST_UTYPE) val;
```
I/O Formats
------------
These are used for formatting the corresponding type For example, instead of saying
```
Perl_newSVpvf(pTHX_ "Create an SV with a %d in it\n", iv);
```
use
```
Perl_newSVpvf(pTHX_ "Create an SV with a " IVdf " in it\n", iv);
```
This keeps you from having to know if, say an IV, needs to be printed as `%d`, `%ld`, or something else.
`IVdf` This symbol defines the format string used for printing a Perl IV as a signed decimal integer.
`NVef` This symbol defines the format string used for printing a Perl NV using %e-ish floating point format.
`NVff` This symbol defines the format string used for printing a Perl NV using %f-ish floating point format.
`NVgf` This symbol defines the format string used for printing a Perl NV using %g-ish floating point format.
`PERL_PRIeldbl` This symbol, if defined, contains the string used by stdio to format long doubles (format 'e') for output.
`PERL_PRIfldbl` This symbol, if defined, contains the string used by stdio to format long doubles (format 'f') for output.
`PERL_PRIgldbl` This symbol, if defined, contains the string used by stdio to format long doubles (format 'g') for output.
`PERL_SCNfldbl` This symbol, if defined, contains the string used by stdio to format long doubles (format 'f') for input.
`PRINTF_FORMAT_NULL_OK` Allows `__printf__` format to be null when checking printf-style
`SVf` Described in <perlguts>.
`SVfARG` Described in <perlguts>.
```
SVfARG(SV *sv)
```
`UTF8f` Described in <perlguts>.
`UTF8fARG` Described in <perlguts>.
```
UTF8fARG(bool is_utf8, Size_t byte_len, char *str)
```
`UVf` `**DEPRECATED!**` It is planned to remove `UVf` from a future release of Perl. Do not use it for new code; remove it from existing code.
Obsolete form of `UVuf`, which you should convert to instead use
```
const char * UVf
```
`UVof` This symbol defines the format string used for printing a Perl UV as an unsigned octal integer.
`UVuf` This symbol defines the format string used for printing a Perl UV as an unsigned decimal integer.
`UVXf` This symbol defines the format string used for printing a Perl UV as an unsigned hexadecimal integer in uppercase `ABCDEF`.
`UVxf` This symbol defines the format string used for printing a Perl UV as an unsigned hexadecimal integer in lowercase abcdef.
Lexer interface
----------------
This is the lower layer of the Perl parser, managing characters and tokens.
`BHK` Described in <perlguts>.
`lex_bufutf8` NOTE: `lex_bufutf8` is **experimental** and may change or be removed without notice.
Indicates whether the octets in the lexer buffer (["PL\_parser->linestr"](#PL_parser-%3Elinestr)) should be interpreted as the UTF-8 encoding of Unicode characters. If not, they should be interpreted as Latin-1 characters. This is analogous to the `SvUTF8` flag for scalars.
In UTF-8 mode, it is not guaranteed that the lexer buffer actually contains valid UTF-8. Lexing code must be robust in the face of invalid encoding.
The actual `SvUTF8` flag of the ["PL\_parser->linestr"](#PL_parser-%3Elinestr) scalar is significant, but not the whole story regarding the input character encoding. Normally, when a file is being read, the scalar contains octets and its `SvUTF8` flag is off, but the octets should be interpreted as UTF-8 if the `use utf8` pragma is in effect. During a string eval, however, the scalar may have the `SvUTF8` flag on, and in this case its octets should be interpreted as UTF-8 unless the `use bytes` pragma is in effect. This logic may change in the future; use this function instead of implementing the logic yourself.
```
bool lex_bufutf8()
```
`lex_discard_to` NOTE: `lex_discard_to` is **experimental** and may change or be removed without notice.
Discards the first part of the ["PL\_parser->linestr"](#PL_parser-%3Elinestr) buffer, up to `ptr`. The remaining content of the buffer will be moved, and all pointers into the buffer updated appropriately. `ptr` must not be later in the buffer than the position of ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr): it is not permitted to discard text that has yet to be lexed.
Normally it is not necessarily to do this directly, because it suffices to use the implicit discarding behaviour of ["lex\_next\_chunk"](#lex_next_chunk) and things based on it. However, if a token stretches across multiple lines, and the lexing code has kept multiple lines of text in the buffer for that purpose, then after completion of the token it would be wise to explicitly discard the now-unneeded earlier lines, to avoid future multi-line tokens growing the buffer without bound.
```
void lex_discard_to(char* ptr)
```
`lex_grow_linestr` NOTE: `lex_grow_linestr` is **experimental** and may change or be removed without notice.
Reallocates the lexer buffer (["PL\_parser->linestr"](#PL_parser-%3Elinestr)) to accommodate at least `len` octets (including terminating `NUL`). Returns a pointer to the reallocated buffer. This is necessary before making any direct modification of the buffer that would increase its length. ["lex\_stuff\_pvn"](#lex_stuff_pvn) provides a more convenient way to insert text into the buffer.
Do not use `SvGROW` or `sv_grow` directly on `PL_parser->linestr`; this function updates all of the lexer's variables that point directly into the buffer.
```
char* lex_grow_linestr(STRLEN len)
```
`lex_next_chunk` NOTE: `lex_next_chunk` is **experimental** and may change or be removed without notice.
Reads in the next chunk of text to be lexed, appending it to ["PL\_parser->linestr"](#PL_parser-%3Elinestr). This should be called when lexing code has looked to the end of the current chunk and wants to know more. It is usual, but not necessary, for lexing to have consumed the entirety of the current chunk at this time.
If ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) is pointing to the very end of the current chunk (i.e., the current chunk has been entirely consumed), normally the current chunk will be discarded at the same time that the new chunk is read in. If `flags` has the `LEX_KEEP_PREVIOUS` bit set, the current chunk will not be discarded. If the current chunk has not been entirely consumed, then it will not be discarded regardless of the flag.
Returns true if some new text was added to the buffer, or false if the buffer has reached the end of the input text.
```
bool lex_next_chunk(U32 flags)
```
`lex_peek_unichar` NOTE: `lex_peek_unichar` is **experimental** and may change or be removed without notice.
Looks ahead one (Unicode) character in the text currently being lexed. Returns the codepoint (unsigned integer value) of the next character, or -1 if lexing has reached the end of the input text. To consume the peeked character, use ["lex\_read\_unichar"](#lex_read_unichar).
If the next character is in (or extends into) the next chunk of input text, the next chunk will be read in. Normally the current chunk will be discarded at the same time, but if `flags` has the `LEX_KEEP_PREVIOUS` bit set, then the current chunk will not be discarded.
If the input is being interpreted as UTF-8 and a UTF-8 encoding error is encountered, an exception is generated.
```
I32 lex_peek_unichar(U32 flags)
```
`lex_read_space` NOTE: `lex_read_space` is **experimental** and may change or be removed without notice.
Reads optional spaces, in Perl style, in the text currently being lexed. The spaces may include ordinary whitespace characters and Perl-style comments. `#line` directives are processed if encountered. ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) is moved past the spaces, so that it points at a non-space character (or the end of the input text).
If spaces extend into the next chunk of input text, the next chunk will be read in. Normally the current chunk will be discarded at the same time, but if `flags` has the `LEX_KEEP_PREVIOUS` bit set, then the current chunk will not be discarded.
```
void lex_read_space(U32 flags)
```
`lex_read_to` NOTE: `lex_read_to` is **experimental** and may change or be removed without notice.
Consume text in the lexer buffer, from ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) up to `ptr`. This advances ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) to match `ptr`, performing the correct bookkeeping whenever a newline character is passed. This is the normal way to consume lexed text.
Interpretation of the buffer's octets can be abstracted out by using the slightly higher-level functions ["lex\_peek\_unichar"](#lex_peek_unichar) and ["lex\_read\_unichar"](#lex_read_unichar).
```
void lex_read_to(char* ptr)
```
`lex_read_unichar` NOTE: `lex_read_unichar` is **experimental** and may change or be removed without notice.
Reads the next (Unicode) character in the text currently being lexed. Returns the codepoint (unsigned integer value) of the character read, and moves ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) past the character, or returns -1 if lexing has reached the end of the input text. To non-destructively examine the next character, use ["lex\_peek\_unichar"](#lex_peek_unichar) instead.
If the next character is in (or extends into) the next chunk of input text, the next chunk will be read in. Normally the current chunk will be discarded at the same time, but if `flags` has the `LEX_KEEP_PREVIOUS` bit set, then the current chunk will not be discarded.
If the input is being interpreted as UTF-8 and a UTF-8 encoding error is encountered, an exception is generated.
```
I32 lex_read_unichar(U32 flags)
```
`lex_start` NOTE: `lex_start` is **experimental** and may change or be removed without notice.
Creates and initialises a new lexer/parser state object, supplying a context in which to lex and parse from a new source of Perl code. A pointer to the new state object is placed in ["PL\_parser"](#PL_parser). An entry is made on the save stack so that upon unwinding, the new state object will be destroyed and the former value of ["PL\_parser"](#PL_parser) will be restored. Nothing else need be done to clean up the parsing context.
The code to be parsed comes from `line` and `rsfp`. `line`, if non-null, provides a string (in SV form) containing code to be parsed. A copy of the string is made, so subsequent modification of `line` does not affect parsing. `rsfp`, if non-null, provides an input stream from which code will be read to be parsed. If both are non-null, the code in `line` comes first and must consist of complete lines of input, and `rsfp` supplies the remainder of the source.
The `flags` parameter is reserved for future use. Currently it is only used by perl internally, so extensions should always pass zero.
```
void lex_start(SV* line, PerlIO *rsfp, U32 flags)
```
`lex_stuff_pv` NOTE: `lex_stuff_pv` is **experimental** and may change or be removed without notice.
Insert characters into the lexer buffer (["PL\_parser->linestr"](#PL_parser-%3Elinestr)), immediately after the current lexing point (["PL\_parser->bufptr"](#PL_parser-%3Ebufptr)), reallocating the buffer if necessary. This means that lexing code that runs later will see the characters as if they had appeared in the input. It is not recommended to do this as part of normal parsing, and most uses of this facility run the risk of the inserted characters being interpreted in an unintended manner.
The string to be inserted is represented by octets starting at `pv` and continuing to the first nul. These octets are interpreted as either UTF-8 or Latin-1, according to whether the `LEX_STUFF_UTF8` flag is set in `flags`. The characters are recoded for the lexer buffer, according to how the buffer is currently being interpreted (["lex\_bufutf8"](#lex_bufutf8)). If it is not convenient to nul-terminate a string to be inserted, the ["lex\_stuff\_pvn"](#lex_stuff_pvn) function is more appropriate.
```
void lex_stuff_pv(const char* pv, U32 flags)
```
`lex_stuff_pvn` NOTE: `lex_stuff_pvn` is **experimental** and may change or be removed without notice.
Insert characters into the lexer buffer (["PL\_parser->linestr"](#PL_parser-%3Elinestr)), immediately after the current lexing point (["PL\_parser->bufptr"](#PL_parser-%3Ebufptr)), reallocating the buffer if necessary. This means that lexing code that runs later will see the characters as if they had appeared in the input. It is not recommended to do this as part of normal parsing, and most uses of this facility run the risk of the inserted characters being interpreted in an unintended manner.
The string to be inserted is represented by `len` octets starting at `pv`. These octets are interpreted as either UTF-8 or Latin-1, according to whether the `LEX_STUFF_UTF8` flag is set in `flags`. The characters are recoded for the lexer buffer, according to how the buffer is currently being interpreted (["lex\_bufutf8"](#lex_bufutf8)). If a string to be inserted is available as a Perl scalar, the ["lex\_stuff\_sv"](#lex_stuff_sv) function is more convenient.
```
void lex_stuff_pvn(const char* pv, STRLEN len, U32 flags)
```
`lex_stuff_pvs` NOTE: `lex_stuff_pvs` is **experimental** and may change or be removed without notice.
Like ["lex\_stuff\_pvn"](#lex_stuff_pvn), but takes a literal string instead of a string/length pair.
```
void lex_stuff_pvs("pv", U32 flags)
```
`lex_stuff_sv` NOTE: `lex_stuff_sv` is **experimental** and may change or be removed without notice.
Insert characters into the lexer buffer (["PL\_parser->linestr"](#PL_parser-%3Elinestr)), immediately after the current lexing point (["PL\_parser->bufptr"](#PL_parser-%3Ebufptr)), reallocating the buffer if necessary. This means that lexing code that runs later will see the characters as if they had appeared in the input. It is not recommended to do this as part of normal parsing, and most uses of this facility run the risk of the inserted characters being interpreted in an unintended manner.
The string to be inserted is the string value of `sv`. The characters are recoded for the lexer buffer, according to how the buffer is currently being interpreted (["lex\_bufutf8"](#lex_bufutf8)). If a string to be inserted is not already a Perl scalar, the ["lex\_stuff\_pvn"](#lex_stuff_pvn) function avoids the need to construct a scalar.
```
void lex_stuff_sv(SV* sv, U32 flags)
```
`lex_unstuff` NOTE: `lex_unstuff` is **experimental** and may change or be removed without notice.
Discards text about to be lexed, from ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr) up to `ptr`. Text following `ptr` will be moved, and the buffer shortened. This hides the discarded text from any lexing code that runs later, as if the text had never appeared.
This is not the normal way to consume lexed text. For that, use ["lex\_read\_to"](#lex_read_to).
```
void lex_unstuff(char* ptr)
```
`parse_arithexpr` NOTE: `parse_arithexpr` is **experimental** and may change or be removed without notice.
Parse a Perl arithmetic expression. This may contain operators of precedence down to the bit shift operators. The expression must be followed (and thus terminated) either by a comparison or lower-precedence operator or by something that would normally terminate an expression such as semicolon. If `flags` has the `PARSE_OPTIONAL` bit set, then the expression is optional, otherwise it is mandatory. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the expression.
The op tree representing the expression is returned. If an optional expression is absent, a null pointer is returned, otherwise the pointer will be non-null.
If an error occurs in parsing or compilation, in most cases a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
```
OP* parse_arithexpr(U32 flags)
```
`parse_barestmt` NOTE: `parse_barestmt` is **experimental** and may change or be removed without notice.
Parse a single unadorned Perl statement. This may be a normal imperative statement or a declaration that has compile-time effect. It does not include any label or other affixture. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the statement.
The op tree representing the statement is returned. This may be a null pointer if the statement is null, for example if it was actually a subroutine definition (which has compile-time side effects). If not null, it will be ops directly implementing the statement, suitable to pass to ["newSTATEOP"](#newSTATEOP). It will not normally include a `nextstate` or equivalent op (except for those embedded in a scope contained entirely within the statement).
If an error occurs in parsing or compilation, in most cases a valid op tree (most likely null) is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
The `flags` parameter is reserved for future use, and must always be zero.
```
OP* parse_barestmt(U32 flags)
```
`parse_block` NOTE: `parse_block` is **experimental** and may change or be removed without notice.
Parse a single complete Perl code block. This consists of an opening brace, a sequence of statements, and a closing brace. The block constitutes a lexical scope, so `my` variables and various compile-time effects can be contained within it. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the statement.
The op tree representing the code block is returned. This is always a real op, never a null pointer. It will normally be a `lineseq` list, including `nextstate` or equivalent ops. No ops to construct any kind of runtime scope are included by virtue of it being a block.
If an error occurs in parsing or compilation, in most cases a valid op tree (most likely null) is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
The `flags` parameter is reserved for future use, and must always be zero.
```
OP* parse_block(U32 flags)
```
`parse_fullexpr` NOTE: `parse_fullexpr` is **experimental** and may change or be removed without notice.
Parse a single complete Perl expression. This allows the full expression grammar, including the lowest-precedence operators such as `or`. The expression must be followed (and thus terminated) by a token that an expression would normally be terminated by: end-of-file, closing bracketing punctuation, semicolon, or one of the keywords that signals a postfix expression-statement modifier. If `flags` has the `PARSE_OPTIONAL` bit set, then the expression is optional, otherwise it is mandatory. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the expression.
The op tree representing the expression is returned. If an optional expression is absent, a null pointer is returned, otherwise the pointer will be non-null.
If an error occurs in parsing or compilation, in most cases a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
```
OP* parse_fullexpr(U32 flags)
```
`parse_fullstmt` NOTE: `parse_fullstmt` is **experimental** and may change or be removed without notice.
Parse a single complete Perl statement. This may be a normal imperative statement or a declaration that has compile-time effect, and may include optional labels. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the statement.
The op tree representing the statement is returned. This may be a null pointer if the statement is null, for example if it was actually a subroutine definition (which has compile-time side effects). If not null, it will be the result of a ["newSTATEOP"](#newSTATEOP) call, normally including a `nextstate` or equivalent op.
If an error occurs in parsing or compilation, in most cases a valid op tree (most likely null) is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
The `flags` parameter is reserved for future use, and must always be zero.
```
OP* parse_fullstmt(U32 flags)
```
`parse_label` NOTE: `parse_label` is **experimental** and may change or be removed without notice.
Parse a single label, possibly optional, of the type that may prefix a Perl statement. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed. If `flags` has the `PARSE_OPTIONAL` bit set, then the label is optional, otherwise it is mandatory.
The name of the label is returned in the form of a fresh scalar. If an optional label is absent, a null pointer is returned.
If an error occurs in parsing, which can only occur if the label is mandatory, a valid label is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred.
```
SV* parse_label(U32 flags)
```
`parse_listexpr` NOTE: `parse_listexpr` is **experimental** and may change or be removed without notice.
Parse a Perl list expression. This may contain operators of precedence down to the comma operator. The expression must be followed (and thus terminated) either by a low-precedence logic operator such as `or` or by something that would normally terminate an expression such as semicolon. If `flags` has the `PARSE_OPTIONAL` bit set, then the expression is optional, otherwise it is mandatory. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the expression.
The op tree representing the expression is returned. If an optional expression is absent, a null pointer is returned, otherwise the pointer will be non-null.
If an error occurs in parsing or compilation, in most cases a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
```
OP* parse_listexpr(U32 flags)
```
`parse_stmtseq` NOTE: `parse_stmtseq` is **experimental** and may change or be removed without notice.
Parse a sequence of zero or more Perl statements. These may be normal imperative statements, including optional labels, or declarations that have compile-time effect, or any mixture thereof. The statement sequence ends when a closing brace or end-of-file is encountered in a place where a new statement could have validly started. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the statements.
The op tree representing the statement sequence is returned. This may be a null pointer if the statements were all null, for example if there were no statements or if there were only subroutine definitions (which have compile-time side effects). If not null, it will be a `lineseq` list, normally including `nextstate` or equivalent ops.
If an error occurs in parsing or compilation, in most cases a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
The `flags` parameter is reserved for future use, and must always be zero.
```
OP* parse_stmtseq(U32 flags)
```
`parse_subsignature` NOTE: `parse_subsignature` is **experimental** and may change or be removed without notice.
Parse a subroutine signature declaration. This is the contents of the parentheses following a named or anonymous subroutine declaration when the `signatures` feature is enabled. Note that this function neither expects nor consumes the opening and closing parentheses around the signature; it is the caller's job to handle these.
This function must only be called during parsing of a subroutine; after ["start\_subparse"](#start_subparse) has been called. It might allocate lexical variables on the pad for the current subroutine.
The op tree to unpack the arguments from the stack at runtime is returned. This op tree should appear at the beginning of the compiled function. The caller may wish to use ["op\_append\_list"](#op_append_list) to build their function body after it, or splice it together with the body before calling ["newATTRSUB"](#newATTRSUB).
The `flags` parameter is reserved for future use, and must always be zero.
```
OP* parse_subsignature(U32 flags)
```
`parse_termexpr` NOTE: `parse_termexpr` is **experimental** and may change or be removed without notice.
Parse a Perl term expression. This may contain operators of precedence down to the assignment operators. The expression must be followed (and thus terminated) either by a comma or lower-precedence operator or by something that would normally terminate an expression such as semicolon. If `flags` has the `PARSE_OPTIONAL` bit set, then the expression is optional, otherwise it is mandatory. It is up to the caller to ensure that the dynamic parser state (["PL\_parser"](#PL_parser) et al) is correctly set to reflect the source of the code to be parsed and the lexical context for the expression.
The op tree representing the expression is returned. If an optional expression is absent, a null pointer is returned, otherwise the pointer will be non-null.
If an error occurs in parsing or compilation, in most cases a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. Some compilation errors, however, will throw an exception immediately.
```
OP* parse_termexpr(U32 flags)
```
`PL_parser` Pointer to a structure encapsulating the state of the parsing operation currently in progress. The pointer can be locally changed to perform a nested parse without interfering with the state of an outer parse. Individual members of `PL_parser` have their own documentation.
`PL_parser->bufend` NOTE: `PL_parser->bufend` is **experimental** and may change or be removed without notice.
Direct pointer to the end of the chunk of text currently being lexed, the end of the lexer buffer. This is equal to `SvPVX(PL_parser->linestr) + SvCUR(PL_parser->linestr)`. A `NUL` character (zero octet) is always located at the end of the buffer, and does not count as part of the buffer's contents.
`PL_parser->bufptr` NOTE: `PL_parser->bufptr` is **experimental** and may change or be removed without notice.
Points to the current position of lexing inside the lexer buffer. Characters around this point may be freely examined, within the range delimited by `SvPVX(["PL\_parser->linestr"](#PL_parser-%3Elinestr))` and ["PL\_parser->bufend"](#PL_parser-%3Ebufend). The octets of the buffer may be intended to be interpreted as either UTF-8 or Latin-1, as indicated by ["lex\_bufutf8"](#lex_bufutf8).
Lexing code (whether in the Perl core or not) moves this pointer past the characters that it consumes. It is also expected to perform some bookkeeping whenever a newline character is consumed. This movement can be more conveniently performed by the function ["lex\_read\_to"](#lex_read_to), which handles newlines appropriately.
Interpretation of the buffer's octets can be abstracted out by using the slightly higher-level functions ["lex\_peek\_unichar"](#lex_peek_unichar) and ["lex\_read\_unichar"](#lex_read_unichar).
`PL_parser->linestart` NOTE: `PL_parser->linestart` is **experimental** and may change or be removed without notice.
Points to the start of the current line inside the lexer buffer. This is useful for indicating at which column an error occurred, and not much else. This must be updated by any lexing code that consumes a newline; the function ["lex\_read\_to"](#lex_read_to) handles this detail.
`PL_parser->linestr` NOTE: `PL_parser->linestr` is **experimental** and may change or be removed without notice.
Buffer scalar containing the chunk currently under consideration of the text currently being lexed. This is always a plain string scalar (for which `SvPOK` is true). It is not intended to be used as a scalar by normal scalar means; instead refer to the buffer directly by the pointer variables described below.
The lexer maintains various `char*` pointers to things in the `PL_parser->linestr` buffer. If `PL_parser->linestr` is ever reallocated, all of these pointers must be updated. Don't attempt to do this manually, but rather use ["lex\_grow\_linestr"](#lex_grow_linestr) if you need to reallocate the buffer.
The content of the text chunk in the buffer is commonly exactly one complete line of input, up to and including a newline terminator, but there are situations where it is otherwise. The octets of the buffer may be intended to be interpreted as either UTF-8 or Latin-1. The function ["lex\_bufutf8"](#lex_bufutf8) tells you which. Do not use the `SvUTF8` flag on this scalar, which may disagree with it.
For direct examination of the buffer, the variable ["PL\_parser->bufend"](#PL_parser-%3Ebufend) points to the end of the buffer. The current lexing position is pointed to by ["PL\_parser->bufptr"](#PL_parser-%3Ebufptr). Direct use of these pointers is usually preferable to examination of the scalar through normal scalar means.
`wrap_keyword_plugin` NOTE: `wrap_keyword_plugin` is **experimental** and may change or be removed without notice.
Puts a C function into the chain of keyword plugins. This is the preferred way to manipulate the ["PL\_keyword\_plugin"](#PL_keyword_plugin) variable. `new_plugin` is a pointer to the C function that is to be added to the keyword plugin chain, and `old_plugin_p` points to the storage location where a pointer to the next function in the chain will be stored. The value of `new_plugin` is written into the ["PL\_keyword\_plugin"](#PL_keyword_plugin) variable, while the value previously stored there is written to `*old_plugin_p`.
["PL\_keyword\_plugin"](#PL_keyword_plugin) is global to an entire process, and a module wishing to hook keyword parsing may find itself invoked more than once per process, typically in different threads. To handle that situation, this function is idempotent. The location `*old_plugin_p` must initially (once per process) contain a null pointer. A C variable of static duration (declared at file scope, typically also marked `static` to give it internal linkage) will be implicitly initialised appropriately, if it does not have an explicit initialiser. This function will only actually modify the plugin chain if it finds `*old_plugin_p` to be null. This function is also thread safe on the small scale. It uses appropriate locking to avoid race conditions in accessing ["PL\_keyword\_plugin"](#PL_keyword_plugin).
When this function is called, the function referenced by `new_plugin` must be ready to be called, except for `*old_plugin_p` being unfilled. In a threading situation, `new_plugin` may be called immediately, even before this function has returned. `*old_plugin_p` will always be appropriately set before `new_plugin` is called. If `new_plugin` decides not to do anything special with the identifier that it is given (which is the usual case for most calls to a keyword plugin), it must chain the plugin function referenced by `*old_plugin_p`.
Taken all together, XS code to install a keyword plugin should typically look something like this:
```
static Perl_keyword_plugin_t next_keyword_plugin;
static OP *my_keyword_plugin(pTHX_
char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
{
if (memEQs(keyword_ptr, keyword_len,
"my_new_keyword")) {
...
} else {
return next_keyword_plugin(aTHX_
keyword_ptr, keyword_len, op_ptr);
}
}
BOOT:
wrap_keyword_plugin(my_keyword_plugin,
&next_keyword_plugin);
```
Direct access to ["PL\_keyword\_plugin"](#PL_keyword_plugin) should be avoided.
```
void wrap_keyword_plugin(Perl_keyword_plugin_t new_plugin,
Perl_keyword_plugin_t *old_plugin_p)
```
Locales
-------
`DECLARATION_FOR_LC_NUMERIC_MANIPULATION` This macro should be used as a statement. It declares a private variable (whose name begins with an underscore) that is needed by the other macros in this section. Failing to include this correctly should lead to a syntax error. For compatibility with C89 C compilers it should be placed in a block before any executable statements.
```
void DECLARATION_FOR_LC_NUMERIC_MANIPULATION
```
`foldEQ_locale` Returns true if the leading `len` bytes of the strings `s1` and `s2` are the same case-insensitively in the current locale; false otherwise.
```
I32 foldEQ_locale(const char* a, const char* b, I32 len)
```
`HAS_DUPLOCALE` This symbol, if defined, indicates that the `duplocale` routine is available to duplicate a locale object.
`HAS_FREELOCALE` This symbol, if defined, indicates that the `freelocale` routine is available to deallocates the resources associated with a locale object.
`HAS_LC_MONETARY_2008` This symbol, if defined, indicates that the localeconv routine is available and has the additional members added in `POSIX` 1003.1-2008.
`HAS_LOCALECONV` This symbol, if defined, indicates that the `localeconv` routine is available for numeric and monetary formatting conventions.
`HAS_LOCALECONV_L` This symbol, if defined, indicates that the `localeconv_l` routine is available to query certain information about a locale.
`HAS_NEWLOCALE` This symbol, if defined, indicates that the `newlocale` routine is available to return a new locale object or modify an existing locale object.
`HAS_NL_LANGINFO` This symbol, if defined, indicates that the `nl_langinfo` routine is available to return local data. You will also need *langinfo.h* and therefore `I_LANGINFO`.
`HAS_NL_LANGINFO_L` This symbol, when defined, indicates presence of the `nl_langinfo_l()` function
`HAS_QUERYLOCALE` This symbol, if defined, indicates that the `querylocale` routine is available to return the name of the locale for a category mask.
`HAS_SETLOCALE` This symbol, if defined, indicates that the `setlocale` routine is available to handle locale-specific ctype implementations.
`HAS_SETLOCALE_R` This symbol, if defined, indicates that the `setlocale_r` routine is available to setlocale re-entrantly.
`HAS_THREAD_SAFE_NL_LANGINFO_L` This symbol, when defined, indicates presence of the `nl_langinfo_l()` function, and that it is thread-safe.
`HAS_USELOCALE` This symbol, if defined, indicates that the `uselocale` routine is available to set the current locale for the calling thread.
`I_LANGINFO` This symbol, if defined, indicates that *langinfo.h* exists and should be included.
```
#ifdef I_LANGINFO
#include <langinfo.h>
#endif
```
`I_LOCALE` This symbol, if defined, indicates to the C program that it should include *locale.h*.
```
#ifdef I_LOCALE
#include <locale.h>
#endif
```
`IN_LOCALE` Evaluates to TRUE if the plain locale pragma without a parameter (`use locale`) is in effect.
```
bool IN_LOCALE
```
`IN_LOCALE_COMPILETIME` Evaluates to TRUE if, when compiling a perl program (including an `eval`) if the plain locale pragma without a parameter (`use locale`) is in effect.
```
bool IN_LOCALE_COMPILETIME
```
`IN_LOCALE_RUNTIME` Evaluates to TRUE if, when executing a perl program (including an `eval`) if the plain locale pragma without a parameter (`use locale`) is in effect.
```
bool IN_LOCALE_RUNTIME
```
`I_XLOCALE` This symbol, if defined, indicates to the C program that the header *xlocale.h* is available. See also `["NEED\_XLOCALE\_H"](#NEED_XLOCALE_H)`
```
#ifdef I_XLOCALE
#include <xlocale.h>
#endif
```
`NEED_XLOCALE_H` This symbol, if defined, indicates that the C program should include *xlocale.h* to get `newlocale()` and its friends.
`Perl_langinfo` This is an (almost) drop-in replacement for the system `[nl\_langinfo(3)](http://man.he.net/man3/nl_langinfo)`, taking the same `item` parameter values, and returning the same information. But it is more thread-safe than regular `nl_langinfo()`, and hides the quirks of Perl's locale handling from your code, and can be used on systems that lack a native `nl_langinfo`.
Expanding on these:
* The reason it isn't quite a drop-in replacement is actually an advantage. The only difference is that it returns `const char *`, whereas plain `nl_langinfo()` returns `char *`, but you are (only by documentation) forbidden to write into the buffer. By declaring this `const`, the compiler enforces this restriction, so if it is violated, you know at compilation time, rather than getting segfaults at runtime.
* It delivers the correct results for the `RADIXCHAR` and `THOUSEP` items, without you having to write extra code. The reason for the extra code would be because these are from the `LC_NUMERIC` locale category, which is normally kept set by Perl so that the radix is a dot, and the separator is the empty string, no matter what the underlying locale is supposed to be, and so to get the expected results, you have to temporarily toggle into the underlying locale, and later toggle back. (You could use plain `nl_langinfo` and `["STORE\_LC\_NUMERIC\_FORCE\_TO\_UNDERLYING"](#STORE_LC_NUMERIC_FORCE_TO_UNDERLYING)` for this but then you wouldn't get the other advantages of `Perl_langinfo()`; not keeping `LC_NUMERIC` in the C (or equivalent) locale would break a lot of CPAN, which is expecting the radix (decimal point) character to be a dot.)
* The system function it replaces can have its static return buffer trashed, not only by a subsequent call to that function, but by a `freelocale`, `setlocale`, or other locale change. The returned buffer of this function is not changed until the next call to it, so the buffer is never in a trashed state.
* Its return buffer is per-thread, so it also is never overwritten by a call to this function from another thread; unlike the function it replaces.
* But most importantly, it works on systems that don't have `nl_langinfo`, such as Windows, hence makes your code more portable. Of the fifty-some possible items specified by the POSIX 2008 standard, <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/langinfo.h.html>, only one is completely unimplemented, though on non-Windows platforms, another significant one is also not implemented). It uses various techniques to recover the other items, including calling `[localeconv(3)](http://man.he.net/man3/localeconv)`, and `[strftime(3)](http://man.he.net/man3/strftime)`, both of which are specified in C89, so should be always be available. Later `strftime()` versions have additional capabilities; `""` is returned for those not available on your system.
It is important to note that when called with an item that is recovered by using `localeconv`, the buffer from any previous explicit call to `localeconv` will be overwritten. This means you must save that buffer's contents if you need to access them after a call to this function. (But note that you might not want to be using `localeconv()` directly anyway, because of issues like the ones listed in the second item of this list (above) for `RADIXCHAR` and `THOUSEP`. You can use the methods given in <perlcall> to call ["localeconv" in POSIX](posix#localeconv) and avoid all the issues, but then you have a hash to unpack).
The details for those items which may deviate from what this emulation returns and what a native `nl_langinfo()` would return are specified in <I18N::Langinfo>.
When using `Perl_langinfo` on systems that don't have a native `nl_langinfo()`, you must
```
#include "perl_langinfo.h"
```
before the `perl.h` `#include`. You can replace your `langinfo.h` `#include` with this one. (Doing it this way keeps out the symbols that plain `langinfo.h` would try to import into the namespace for code that doesn't need it.)
The original impetus for `Perl_langinfo()` was so that code that needs to find out the current currency symbol, floating point radix character, or digit grouping separator can use, on all systems, the simpler and more thread-friendly `nl_langinfo` API instead of `[localeconv(3)](http://man.he.net/man3/localeconv)` which is a pain to make thread-friendly. For other fields returned by `localeconv`, it is better to use the methods given in <perlcall> to call [`POSIX::localeconv()`](posix#localeconv), which is thread-friendly.
```
const char* Perl_langinfo(const nl_item item)
```
`Perl_setlocale` This is an (almost) drop-in replacement for the system [`setlocale(3)`](setlocale(3)), taking the same parameters, and returning the same information, except that it returns the correct underlying `LC_NUMERIC` locale. Regular `setlocale` will instead return `C` if the underlying locale has a non-dot decimal point character, or a non-empty thousands separator for displaying floating point numbers. This is because perl keeps that locale category such that it has a dot and empty separator, changing the locale briefly during the operations where the underlying one is required. `Perl_setlocale` knows about this, and compensates; regular `setlocale` doesn't.
Another reason it isn't completely a drop-in replacement is that it is declared to return `const char *`, whereas the system setlocale omits the `const` (presumably because its API was specified long ago, and can't be updated; it is illegal to change the information `setlocale` returns; doing so leads to segfaults.)
Finally, `Perl_setlocale` works under all circumstances, whereas plain `setlocale` can be completely ineffective on some platforms under some configurations.
`Perl_setlocale` should not be used to change the locale except on systems where the predefined variable `${^SAFE_LOCALES}` is 1. On some such systems, the system `setlocale()` is ineffective, returning the wrong information, and failing to actually change the locale. `Perl_setlocale`, however works properly in all circumstances.
The return points to a per-thread static buffer, which is overwritten the next time `Perl_setlocale` is called from the same thread.
```
const char* Perl_setlocale(const int category,
const char* locale)
```
`RESTORE_LC_NUMERIC` This is used in conjunction with one of the macros ["STORE\_LC\_NUMERIC\_SET\_TO\_NEEDED"](#STORE_LC_NUMERIC_SET_TO_NEEDED) and ["STORE\_LC\_NUMERIC\_FORCE\_TO\_UNDERLYING"](#STORE_LC_NUMERIC_FORCE_TO_UNDERLYING) to properly restore the `LC_NUMERIC` state.
A call to ["DECLARATION\_FOR\_LC\_NUMERIC\_MANIPULATION"](#DECLARATION_FOR_LC_NUMERIC_MANIPULATION) must have been made to declare at compile time a private variable used by this macro and the two `STORE` ones. This macro should be called as a single statement, not an expression, but with an empty argument list, like this:
```
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
RESTORE_LC_NUMERIC();
...
}
```
```
void RESTORE_LC_NUMERIC()
```
`SETLOCALE_ACCEPTS_ANY_LOCALE_NAME` This symbol, if defined, indicates that the setlocale routine is available and it accepts any input locale name as valid.
`STORE_LC_NUMERIC_FORCE_TO_UNDERLYING` This is used by XS code that is `LC_NUMERIC` locale-aware to force the locale for category `LC_NUMERIC` to be what perl thinks is the current underlying locale. (The perl interpreter could be wrong about what the underlying locale actually is if some C or XS code has called the C library function [setlocale(3)](http://man.he.net/man3/setlocale) behind its back; calling ["sync\_locale"](#sync_locale) before calling this macro will update perl's records.)
A call to ["DECLARATION\_FOR\_LC\_NUMERIC\_MANIPULATION"](#DECLARATION_FOR_LC_NUMERIC_MANIPULATION) must have been made to declare at compile time a private variable used by this macro. This macro should be called as a single statement, not an expression, but with an empty argument list, like this:
```
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
STORE_LC_NUMERIC_FORCE_TO_UNDERLYING();
...
RESTORE_LC_NUMERIC();
...
}
```
The private variable is used to save the current locale state, so that the requisite matching call to ["RESTORE\_LC\_NUMERIC"](#RESTORE_LC_NUMERIC) can restore it.
On threaded perls not operating with thread-safe functionality, this macro uses a mutex to force a critical section. Therefore the matching RESTORE should be close by, and guaranteed to be called.
```
void STORE_LC_NUMERIC_FORCE_TO_UNDERLYING()
```
`STORE_LC_NUMERIC_SET_TO_NEEDED` This is used to help wrap XS or C code that is `LC_NUMERIC` locale-aware. This locale category is generally kept set to a locale where the decimal radix character is a dot, and the separator between groups of digits is empty. This is because most XS code that reads floating point numbers is expecting them to have this syntax.
This macro makes sure the current `LC_NUMERIC` state is set properly, to be aware of locale if the call to the XS or C code from the Perl program is from within the scope of a `use locale`; or to ignore locale if the call is instead from outside such scope.
This macro is the start of wrapping the C or XS code; the wrap ending is done by calling the ["RESTORE\_LC\_NUMERIC"](#RESTORE_LC_NUMERIC) macro after the operation. Otherwise the state can be changed that will adversely affect other XS code.
A call to ["DECLARATION\_FOR\_LC\_NUMERIC\_MANIPULATION"](#DECLARATION_FOR_LC_NUMERIC_MANIPULATION) must have been made to declare at compile time a private variable used by this macro. This macro should be called as a single statement, not an expression, but with an empty argument list, like this:
```
{
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
...
STORE_LC_NUMERIC_SET_TO_NEEDED();
...
RESTORE_LC_NUMERIC();
...
}
```
On threaded perls not operating with thread-safe functionality, this macro uses a mutex to force a critical section. Therefore the matching RESTORE should be close by, and guaranteed to be called; see ["WITH\_LC\_NUMERIC\_SET\_TO\_NEEDED"](#WITH_LC_NUMERIC_SET_TO_NEEDED) for a more contained way to ensure that.
```
void STORE_LC_NUMERIC_SET_TO_NEEDED()
```
`STORE_LC_NUMERIC_SET_TO_NEEDED_IN` Same as ["STORE\_LC\_NUMERIC\_SET\_TO\_NEEDED"](#STORE_LC_NUMERIC_SET_TO_NEEDED) with in\_lc\_numeric provided as the precalculated value of `IN_LC(LC_NUMERIC)`. It is the caller's responsibility to ensure that the status of `PL_compiling` and `PL_hints` cannot have changed since the precalculation.
```
void STORE_LC_NUMERIC_SET_TO_NEEDED_IN(bool in_lc_numeric)
```
`switch_to_global_locale` On systems without locale support, or on typical single-threaded builds, or on platforms that do not support per-thread locale operations, this function does nothing. On such systems that do have locale support, only a locale global to the whole program is available.
On multi-threaded builds on systems that do have per-thread locale operations, this function converts the thread it is running in to use the global locale. This is for code that has not yet or cannot be updated to handle multi-threaded locale operation. As long as only a single thread is so-converted, everything works fine, as all the other threads continue to ignore the global one, so only this thread looks at it.
However, on Windows systems this isn't quite true prior to Visual Studio 15, at which point Microsoft fixed a bug. A race can occur if you use the following operations on earlier Windows platforms:
[POSIX::localeconv](posix#localeconv)
<I18N::Langinfo>, items `CRNCYSTR` and `THOUSEP`
["Perl\_langinfo" in perlapi](perlapi#Perl_langinfo), items `CRNCYSTR` and `THOUSEP`
The first item is not fixable (except by upgrading to a later Visual Studio release), but it would be possible to work around the latter two items by using the Windows API functions `GetNumberFormat` and `GetCurrencyFormat`; patches welcome.
Without this function call, threads that use the [`setlocale(3)`](setlocale(3)) system function will not work properly, as all the locale-sensitive functions will look at the per-thread locale, and `setlocale` will have no effect on this thread.
Perl code should convert to either call [`Perl_setlocale`](perlapi#Perl_setlocale) (which is a drop-in for the system `setlocale`) or use the methods given in <perlcall> to call [`POSIX::setlocale`](posix#setlocale). Either one will transparently properly handle all cases of single- vs multi-thread, POSIX 2008-supported or not.
Non-Perl libraries, such as `gtk`, that call the system `setlocale` can continue to work if this function is called before transferring control to the library.
Upon return from the code that needs to use the global locale, [`sync_locale()`](perlapi#sync_locale) should be called to restore the safe multi-thread operation.
```
void switch_to_global_locale()
```
`sync_locale` [`Perl_setlocale`](perlapi#Perl_setlocale) can be used at any time to query or change the locale (though changing the locale is antisocial and dangerous on multi-threaded systems that don't have multi-thread safe locale operations. (See ["Multi-threaded operation" in perllocale](perllocale#Multi-threaded-operation)). Using the system [`setlocale(3)`](setlocale(3)) should be avoided. Nevertheless, certain non-Perl libraries called from XS, such as `Gtk` do so, and this can't be changed. When the locale is changed by XS code that didn't use [`Perl_setlocale`](perlapi#Perl_setlocale), Perl needs to be told that the locale has changed. Use this function to do so, before returning to Perl.
The return value is a boolean: TRUE if the global locale at the time of call was in effect; and FALSE if a per-thread locale was in effect. This can be used by the caller that needs to restore things as-they-were to decide whether or not to call [`Perl_switch_to_global_locale`](perlapi#switch_to_global_locale).
```
bool sync_locale()
```
`WITH_LC_NUMERIC_SET_TO_NEEDED` This macro invokes the supplied statement or block within the context of a ["STORE\_LC\_NUMERIC\_SET\_TO\_NEEDED"](#STORE_LC_NUMERIC_SET_TO_NEEDED) .. ["RESTORE\_LC\_NUMERIC"](#RESTORE_LC_NUMERIC) pair if required, so eg:
```
WITH_LC_NUMERIC_SET_TO_NEEDED(
SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis)
);
```
is equivalent to:
```
{
#ifdef USE_LOCALE_NUMERIC
DECLARATION_FOR_LC_NUMERIC_MANIPULATION;
STORE_LC_NUMERIC_SET_TO_NEEDED();
#endif
SNPRINTF_G(fv, ebuf, sizeof(ebuf), precis);
#ifdef USE_LOCALE_NUMERIC
RESTORE_LC_NUMERIC();
#endif
}
```
```
void WITH_LC_NUMERIC_SET_TO_NEEDED(block)
```
`WITH_LC_NUMERIC_SET_TO_NEEDED_IN` Same as ["WITH\_LC\_NUMERIC\_SET\_TO\_NEEDED"](#WITH_LC_NUMERIC_SET_TO_NEEDED) with in\_lc\_numeric provided as the precalculated value of `IN_LC(LC_NUMERIC)`. It is the caller's responsibility to ensure that the status of `PL_compiling` and `PL_hints` cannot have changed since the precalculation.
```
void WITH_LC_NUMERIC_SET_TO_NEEDED_IN(bool in_lc_numeric, block)
```
Magic
-----
"Magic" is special data attached to SV structures in order to give them "magical" properties. When any Perl code tries to read from, or assign to, an SV marked as magical, it calls the 'get' or 'set' function associated with that SV's magic. A get is called prior to reading an SV, in order to give it a chance to update its internal value (get on $. writes the line number of the last read filehandle into the SV's IV slot), while set is called after an SV has been written to, in order to allow it to make use of its changed value (set on $/ copies the SV's new value to the PL\_rs global variable).
Magic is implemented as a linked list of MAGIC structures attached to the SV. Each MAGIC struct holds the type of the magic, a pointer to an array of functions that implement the get(), set(), length() etc functions, plus space for some flags and pointers. For example, a tied variable has a MAGIC structure that contains a pointer to the object associated with the tie.
`mg_clear` Clear something magical that the SV represents. See `["sv\_magic"](#sv_magic)`.
```
int mg_clear(SV* sv)
```
`mg_copy` Copies the magic from one SV to another. See `["sv\_magic"](#sv_magic)`.
```
int mg_copy(SV *sv, SV *nsv, const char *key, I32 klen)
```
`MGf_COPY` `MGf_DUP` `MGf_LOCAL` Described in <perlguts>.
`mg_find` Finds the magic pointer for `type` matching the SV. See `["sv\_magic"](#sv_magic)`.
```
MAGIC* mg_find(const SV* sv, int type)
```
`mg_findext` Finds the magic pointer of `type` with the given `vtbl` for the `SV`. See `["sv\_magicext"](#sv_magicext)`.
```
MAGIC* mg_findext(const SV* sv, int type, const MGVTBL *vtbl)
```
`mg_free` Free any magic storage used by the SV. See `["sv\_magic"](#sv_magic)`.
```
int mg_free(SV* sv)
```
`mg_freeext` Remove any magic of type `how` using virtual table `vtbl` from the SV `sv`. See ["sv\_magic"](#sv_magic).
`mg_freeext(sv, how, NULL)` is equivalent to `mg_free_type(sv, how)`.
```
void mg_freeext(SV* sv, int how, const MGVTBL *vtbl)
```
`mg_free_type` Remove any magic of type `how` from the SV `sv`. See ["sv\_magic"](#sv_magic).
```
void mg_free_type(SV* sv, int how)
```
`mg_get` Do magic before a value is retrieved from the SV. The type of SV must be >= `SVt_PVMG`. See `["sv\_magic"](#sv_magic)`.
```
int mg_get(SV* sv)
```
`mg_length` `**DEPRECATED!**` It is planned to remove `mg_length` from a future release of Perl. Do not use it for new code; remove it from existing code.
Reports on the SV's length in bytes, calling length magic if available, but does not set the UTF8 flag on `sv`. It will fall back to 'get' magic if there is no 'length' magic, but with no indication as to whether it called 'get' magic. It assumes `sv` is a `PVMG` or higher. Use `sv_len()` instead.
```
U32 mg_length(SV* sv)
```
`mg_magical` Turns on the magical status of an SV. See `["sv\_magic"](#sv_magic)`.
```
void mg_magical(SV* sv)
```
`mg_set` Do magic after a value is assigned to the SV. See `["sv\_magic"](#sv_magic)`.
```
int mg_set(SV* sv)
```
`MGVTBL` Described in <perlguts>.
`perl_clone` Create and return a new interpreter by cloning the current one.
`perl_clone` takes these flags as parameters:
`CLONEf_COPY_STACKS` - is used to, well, copy the stacks also, without it we only clone the data and zero the stacks, with it we copy the stacks and the new perl interpreter is ready to run at the exact same point as the previous one. The pseudo-fork code uses `COPY_STACKS` while the threads->create doesn't.
`CLONEf_KEEP_PTR_TABLE` - `perl_clone` keeps a ptr\_table with the pointer of the old variable as a key and the new variable as a value, this allows it to check if something has been cloned and not clone it again, but rather just use the value and increase the refcount. If `KEEP_PTR_TABLE` is not set then `perl_clone` will kill the ptr\_table using the function `ptr_table_free(PL_ptr_table); PL_ptr_table = NULL;`. A reason to keep it around is if you want to dup some of your own variables which are outside the graph that perl scans.
`CLONEf_CLONE_HOST` - This is a win32 thing, it is ignored on unix, it tells perl's win32host code (which is c++) to clone itself, this is needed on win32 if you want to run two threads at the same time, if you just want to do some stuff in a separate perl interpreter and then throw it away and return to the original one, you don't need to do anything.
```
PerlInterpreter* perl_clone(PerlInterpreter *proto_perl,
UV flags)
```
`PERL_MAGIC_arylen` `PERL_MAGIC_arylen_p` `PERL_MAGIC_backref` `PERL_MAGIC_bm` `PERL_MAGIC_checkcall` `PERL_MAGIC_collxfrm` `PERL_MAGIC_dbfile` `PERL_MAGIC_dbline` `PERL_MAGIC_debugvar` `PERL_MAGIC_defelem` `PERL_MAGIC_env` `PERL_MAGIC_envelem` `PERL_MAGIC_ext` `PERL_MAGIC_fm` `PERL_MAGIC_hints` `PERL_MAGIC_hintselem` `PERL_MAGIC_isa` `PERL_MAGIC_isaelem` `PERL_MAGIC_lvref` `PERL_MAGIC_nkeys` `PERL_MAGIC_nonelem` `PERL_MAGIC_overload_table` `PERL_MAGIC_pos` `PERL_MAGIC_qr` `PERL_MAGIC_regdata` `PERL_MAGIC_regdatum` `PERL_MAGIC_regex_global` `PERL_MAGIC_rhash` `PERL_MAGIC_shared` `PERL_MAGIC_shared_scalar` `PERL_MAGIC_sig` `PERL_MAGIC_sigelem` `PERL_MAGIC_substr` `PERL_MAGIC_sv` `PERL_MAGIC_symtab` `PERL_MAGIC_taint` `PERL_MAGIC_tied` `PERL_MAGIC_tiedelem` `PERL_MAGIC_tiedscalar` `PERL_MAGIC_utf8` `PERL_MAGIC_uvar` `PERL_MAGIC_uvar_elem` `PERL_MAGIC_vec` `PERL_MAGIC_vstring` Described in <perlguts>.
`ptr_table_fetch` Look for `sv` in the pointer-mapping table `tbl`, returning its value, or NULL if not found.
```
void* ptr_table_fetch(PTR_TBL_t *const tbl, const void *const sv)
```
`ptr_table_free` Clear and free a ptr table
```
void ptr_table_free(PTR_TBL_t *const tbl)
```
`ptr_table_new` Create a new pointer-mapping table
```
PTR_TBL_t* ptr_table_new()
```
`ptr_table_split` Double the hash bucket size of an existing ptr table
```
void ptr_table_split(PTR_TBL_t *const tbl)
```
`ptr_table_store` Add a new entry to a pointer-mapping table `tbl`. In hash terms, `oldsv` is the key; Cnewsv> is the value.
The names "old" and "new" are specific to the core's typical use of ptr\_tables in thread cloning.
```
void ptr_table_store(PTR_TBL_t *const tbl,
const void *const oldsv, void *const newsv)
```
`SvTIED_obj` Described in <perlinterp>.
```
SvTIED_obj(SV *sv, MAGIC *mg)
```
Memory Management
------------------
`dump_mstats` When enabled by compiling with `-DDEBUGGING_MSTATS`, print out statistics about malloc as two lines of numbers, one showing the length of the free list for each size category, the second showing the number of mallocs - frees for each size category.
`s`, if not NULL, is used as a phrase to include in the output, such as "after compilation".
```
void dump_mstats(const char* s)
```
`HASATTRIBUTE_MALLOC` Can we handle `GCC` attribute for malloc-style functions.
`HAS_MALLOC_GOOD_SIZE` This symbol, if defined, indicates that the `malloc_good_size` routine is available for use.
`HAS_MALLOC_SIZE` This symbol, if defined, indicates that the `malloc_size` routine is available for use.
`I_MALLOCMALLOC` This symbol, if defined, indicates to the C program that it should include *malloc/malloc.h*.
```
#ifdef I_MALLOCMALLOC
#include <mallocmalloc.h>
#endif
```
`MYMALLOC` This symbol, if defined, indicates that we're using our own malloc.
`Newx`
`safemalloc` The XSUB-writer's interface to the C `malloc` function.
Memory obtained by this should **ONLY** be freed with ["Safefree"](#Safefree).
In 5.9.3, Newx() and friends replace the older New() API, and drops the first parameter, *x*, a debug aid which allowed callers to identify themselves. This aid has been superseded by a new build option, PERL\_MEM\_LOG (see ["PERL\_MEM\_LOG" in perlhacktips](perlhacktips#PERL_MEM_LOG)). The older API is still there for use in XS modules supporting older perls.
```
void Newx (void* ptr, int nitems, type)
void* safemalloc(size_t size)
```
`Newxc` The XSUB-writer's interface to the C `malloc` function, with cast. See also `["Newx"](#Newx)`.
Memory obtained by this should **ONLY** be freed with ["Safefree"](#Safefree).
```
void Newxc(void* ptr, int nitems, type, cast)
```
`Newxz`
`safecalloc` The XSUB-writer's interface to the C `malloc` function. The allocated memory is zeroed with `memzero`. See also `["Newx"](#Newx)`.
Memory obtained by this should **ONLY** be freed with ["Safefree"](#Safefree).
```
void Newxz (void* ptr, int nitems, type)
void* safecalloc(size_t nitems, size_t item_size)
```
`PERL_MALLOC_WRAP` This symbol, if defined, indicates that we'd like malloc wrap checks.
`Renew`
`saferealloc` The XSUB-writer's interface to the C `realloc` function.
Memory obtained by this should **ONLY** be freed with ["Safefree"](#Safefree).
```
void Renew (void* ptr, int nitems, type)
void* saferealloc(void *ptr, size_t size)
```
`Renewc` The XSUB-writer's interface to the C `realloc` function, with cast.
Memory obtained by this should **ONLY** be freed with ["Safefree"](#Safefree).
```
void Renewc(void* ptr, int nitems, type, cast)
```
`Safefree` The XSUB-writer's interface to the C `free` function.
This should **ONLY** be used on memory obtained using ["Newx"](#Newx) and friends.
```
void Safefree(void* ptr)
```
`safesyscalloc` Safe version of system's calloc()
```
Malloc_t safesyscalloc(MEM_SIZE elements, MEM_SIZE size)
```
`safesysfree` Safe version of system's free()
```
Free_t safesysfree(Malloc_t where)
```
`safesysmalloc` Paranoid version of system's malloc()
```
Malloc_t safesysmalloc(MEM_SIZE nbytes)
```
`safesysrealloc` Paranoid version of system's realloc()
```
Malloc_t safesysrealloc(Malloc_t where, MEM_SIZE nbytes)
```
MRO
---
These functions are related to the method resolution order of perl classes Also see <perlmroapi>.
`HvMROMETA` Described in <perlmroapi>.
```
struct mro_meta * HvMROMETA(HV *hv)
```
`mro_get_from_name` Returns the previously registered mro with the given `name`, or NULL if not registered. See ["`mro_register`"](#mro_register).
NOTE: `mro_get_from_name` must be explicitly called as `Perl_mro_get_from_name` with an `aTHX_` parameter.
```
const struct mro_alg * Perl_mro_get_from_name(pTHX_ SV *name)
```
`mro_get_linear_isa` Returns the mro linearisation for the given stash. By default, this will be whatever `mro_get_linear_isa_dfs` returns unless some other MRO is in effect for the stash. The return value is a read-only AV\*.
You are responsible for `SvREFCNT_inc()` on the return value if you plan to store it anywhere semi-permanently (otherwise it might be deleted out from under you the next time the cache is invalidated).
```
AV* mro_get_linear_isa(HV* stash)
```
`MRO_GET_PRIVATE_DATA` Described in <perlmroapi>.
```
SV* MRO_GET_PRIVATE_DATA(struct mro_meta *const smeta,
const struct mro_alg *const which)
```
`mro_method_changed_in` Invalidates method caching on any child classes of the given stash, so that they might notice the changes in this one.
Ideally, all instances of `PL_sub_generation++` in perl source outside of *mro.c* should be replaced by calls to this.
Perl automatically handles most of the common ways a method might be redefined. However, there are a few ways you could change a method in a stash without the cache code noticing, in which case you need to call this method afterwards:
1) Directly manipulating the stash HV entries from XS code.
2) Assigning a reference to a readonly scalar constant into a stash entry in order to create a constant subroutine (like *constant.pm* does).
This same method is available from pure perl via, `mro::method_changed_in(classname)`.
```
void mro_method_changed_in(HV* stash)
```
`mro_register` Registers a custom mro plugin. See <perlmroapi> for details on this and other mro functions.
NOTE: `mro_register` must be explicitly called as `Perl_mro_register` with an `aTHX_` parameter.
```
void Perl_mro_register(pTHX_ const struct mro_alg *mro)
```
`mro_set_mro` Set `meta` to the value contained in the registered mro plugin whose name is `name`.
Croaks if `name` hasn't been registered
NOTE: `mro_set_mro` must be explicitly called as `Perl_mro_set_mro` with an `aTHX_` parameter.
```
void Perl_mro_set_mro(pTHX_ struct mro_meta *const meta,
SV *const name)
```
`mro_set_private_data` Described in <perlmroapi>.
NOTE: `mro_set_private_data` must be explicitly called as `Perl_mro_set_private_data` with an `aTHX_` parameter.
```
SV* Perl_mro_set_private_data(pTHX_
struct mro_meta *const smeta,
const struct mro_alg *const which,
SV *const data)
```
Multicall Functions
--------------------
`dMULTICALL` Declare local variables for a multicall. See ["LIGHTWEIGHT CALLBACKS" in perlcall](perlcall#LIGHTWEIGHT-CALLBACKS).
```
dMULTICALL;
```
`MULTICALL` Make a lightweight callback. See ["LIGHTWEIGHT CALLBACKS" in perlcall](perlcall#LIGHTWEIGHT-CALLBACKS).
```
MULTICALL;
```
`POP_MULTICALL` Closing bracket for a lightweight callback. See ["LIGHTWEIGHT CALLBACKS" in perlcall](perlcall#LIGHTWEIGHT-CALLBACKS).
```
POP_MULTICALL;
```
`PUSH_MULTICALL` Opening bracket for a lightweight callback. See ["LIGHTWEIGHT CALLBACKS" in perlcall](perlcall#LIGHTWEIGHT-CALLBACKS).
```
PUSH_MULTICALL(CV* the_cv);
```
Numeric Functions
------------------
`Atol` `**DEPRECATED!**` It is planned to remove `Atol` from a future release of Perl. Do not use it for new code; remove it from existing code.
Described in <perlhacktips>.
```
Atol(const char * nptr)
```
`Atoul` `**DEPRECATED!**` It is planned to remove `Atoul` from a future release of Perl. Do not use it for new code; remove it from existing code.
Described in <perlhacktips>.
```
Atoul(const char * nptr)
```
`Drand01` This macro is to be used to generate uniformly distributed random numbers over the range [0., 1.[. You may have to supply an 'extern double `drand48()`;' in your program since SunOS 4.1.3 doesn't provide you with anything relevant in its headers. See `["HAS\_DRAND48\_PROTO"](#HAS_DRAND48_PROTO)`.
```
double Drand01()
```
`Gconvert` This preprocessor macro is defined to convert a floating point number to a string without a trailing decimal point. This emulates the behavior of `sprintf("%g")`, but is sometimes much more efficient. If `gconvert()` is not available, but `gcvt()` drops the trailing decimal point, then `gcvt()` is used. If all else fails, a macro using `sprintf("%g")` is used. Arguments for the Gconvert macro are: value, number of digits, whether trailing zeros should be retained, and the output buffer. The usual values are:
```
d_Gconvert='gconvert((x),(n),(t),(b))'
d_Gconvert='gcvt((x),(n),(b))'
d_Gconvert='sprintf((b),"%.*g",(n),(x))'
```
The last two assume trailing zeros should not be kept.
```
char * Gconvert(double x, Size_t n, bool t, char * b)
```
`grok_atoUV` parse a string, looking for a decimal unsigned integer.
On entry, `pv` points to the beginning of the string; `valptr` points to a UV that will receive the converted value, if found; `endptr` is either NULL or points to a variable that points to one byte beyond the point in `pv` that this routine should examine. If `endptr` is NULL, `pv` is assumed to be NUL-terminated.
Returns FALSE if `pv` doesn't represent a valid unsigned integer value (with no leading zeros). Otherwise it returns TRUE, and sets `*valptr` to that value.
If you constrain the portion of `pv` that is looked at by this function (by passing a non-NULL `endptr`), and if the intial bytes of that portion form a valid value, it will return TRUE, setting `*endptr` to the byte following the final digit of the value. But if there is no constraint at what's looked at, all of `pv` must be valid in order for TRUE to be returned. `*endptr` is unchanged from its value on input if FALSE is returned;
The only characters this accepts are the decimal digits '0'..'9'.
As opposed to [atoi(3)](http://man.he.net/man3/atoi) or [strtol(3)](http://man.he.net/man3/strtol), `grok_atoUV` does NOT allow optional leading whitespace, nor negative inputs. If such features are required, the calling code needs to explicitly implement those.
Note that this function returns FALSE for inputs that would overflow a UV, or have leading zeros. Thus a single `0` is accepted, but not `00` nor `01`, `002`, *etc*.
Background: `atoi` has severe problems with illegal inputs, it cannot be used for incremental parsing, and therefore should be avoided `atoi` and `strtol` are also affected by locale settings, which can also be seen as a bug (global state controlled by user environment).
```
bool grok_atoUV(const char* pv, UV* valptr, const char** endptr)
```
`grok_bin` converts a string representing a binary number to numeric form.
On entry `start` and `*len_p` give the string to scan, `*flags` gives conversion flags, and `result` should be `NULL` or a pointer to an NV. The scan stops at the end of the string, or at just before the first invalid character. Unless `PERL_SCAN_SILENT_ILLDIGIT` is set in `*flags`, encountering an invalid character (except NUL) will also trigger a warning. On return `*len_p` is set to the length of the scanned string, and `*flags` gives output flags.
If the value is <= `UV_MAX` it is returned as a UV, the output flags are clear, and nothing is written to `*result`. If the value is > `UV_MAX`, `grok_bin` returns `UV_MAX`, sets `PERL_SCAN_GREATER_THAN_UV_MAX` in the output flags, and writes an approximation of the correct value into `*result` (which is an NV; or the approximation is discarded if `result` is NULL).
The binary number may optionally be prefixed with `"0b"` or `"b"` unless `PERL_SCAN_DISALLOW_PREFIX` is set in `*flags` on entry.
If `PERL_SCAN_ALLOW_UNDERSCORES` is set in `*flags` then any or all pairs of digits may be separated from each other by a single underscore; also a single leading underscore is accepted.
```
UV grok_bin(const char* start, STRLEN* len_p, I32* flags,
NV *result)
```
`grok_hex` converts a string representing a hex number to numeric form.
On entry `start` and `*len_p` give the string to scan, `*flags` gives conversion flags, and `result` should be `NULL` or a pointer to an NV. The scan stops at the end of the string, or at just before the first invalid character. Unless `PERL_SCAN_SILENT_ILLDIGIT` is set in `*flags`, encountering an invalid character (except NUL) will also trigger a warning. On return `*len_p` is set to the length of the scanned string, and `*flags` gives output flags.
If the value is <= `UV_MAX` it is returned as a UV, the output flags are clear, and nothing is written to `*result`. If the value is > `UV_MAX`, `grok_hex` returns `UV_MAX`, sets `PERL_SCAN_GREATER_THAN_UV_MAX` in the output flags, and writes an approximation of the correct value into `*result` (which is an NV; or the approximation is discarded if `result` is NULL).
The hex number may optionally be prefixed with `"0x"` or `"x"` unless `PERL_SCAN_DISALLOW_PREFIX` is set in `*flags` on entry.
If `PERL_SCAN_ALLOW_UNDERSCORES` is set in `*flags` then any or all pairs of digits may be separated from each other by a single underscore; also a single leading underscore is accepted.
```
UV grok_hex(const char* start, STRLEN* len_p, I32* flags,
NV *result)
```
`grok_infnan` Helper for `grok_number()`, accepts various ways of spelling "infinity" or "not a number", and returns one of the following flag combinations:
```
IS_NUMBER_INFINITY
IS_NUMBER_NAN
IS_NUMBER_INFINITY | IS_NUMBER_NEG
IS_NUMBER_NAN | IS_NUMBER_NEG
0
```
possibly |-ed with `IS_NUMBER_TRAILING`.
If an infinity or a not-a-number is recognized, `*sp` will point to one byte past the end of the recognized string. If the recognition fails, zero is returned, and `*sp` will not move.
```
int grok_infnan(const char** sp, const char *send)
```
`grok_number` Identical to `grok_number_flags()` with `flags` set to zero.
```
int grok_number(const char *pv, STRLEN len, UV *valuep)
```
`grok_number_flags` Recognise (or not) a number. The type of the number is returned (0 if unrecognised), otherwise it is a bit-ORed combination of `IS_NUMBER_IN_UV`, `IS_NUMBER_GREATER_THAN_UV_MAX`, `IS_NUMBER_NOT_INT`, `IS_NUMBER_NEG`, `IS_NUMBER_INFINITY`, `IS_NUMBER_NAN` (defined in perl.h).
If the value of the number can fit in a UV, it is returned in `*valuep`. `IS_NUMBER_IN_UV` will be set to indicate that `*valuep` is valid, `IS_NUMBER_IN_UV` will never be set unless `*valuep` is valid, but `*valuep` may have been assigned to during processing even though `IS_NUMBER_IN_UV` is not set on return. If `valuep` is `NULL`, `IS_NUMBER_IN_UV` will be set for the same cases as when `valuep` is non-`NULL`, but no actual assignment (or SEGV) will occur.
`IS_NUMBER_NOT_INT` will be set with `IS_NUMBER_IN_UV` if trailing decimals were seen (in which case `*valuep` gives the true value truncated to an integer), and `IS_NUMBER_NEG` if the number is negative (in which case `*valuep` holds the absolute value). `IS_NUMBER_IN_UV` is not set if `e` notation was used or the number is larger than a UV.
`flags` allows only `PERL_SCAN_TRAILING`, which allows for trailing non-numeric text on an otherwise successful *grok*, setting `IS_NUMBER_TRAILING` on the result.
```
int grok_number_flags(const char *pv, STRLEN len, UV *valuep,
U32 flags)
```
`GROK_NUMERIC_RADIX` A synonym for ["grok\_numeric\_radix"](#grok_numeric_radix)
```
bool GROK_NUMERIC_RADIX(NN const char **sp, NN const char *send)
```
`grok_numeric_radix` Scan and skip for a numeric decimal separator (radix).
```
bool grok_numeric_radix(const char **sp, const char *send)
```
`grok_oct` converts a string representing an octal number to numeric form.
On entry `start` and `*len_p` give the string to scan, `*flags` gives conversion flags, and `result` should be `NULL` or a pointer to an NV. The scan stops at the end of the string, or at just before the first invalid character. Unless `PERL_SCAN_SILENT_ILLDIGIT` is set in `*flags`, encountering an invalid character (except NUL) will also trigger a warning. On return `*len_p` is set to the length of the scanned string, and `*flags` gives output flags.
If the value is <= `UV_MAX` it is returned as a UV, the output flags are clear, and nothing is written to `*result`. If the value is > `UV_MAX`, `grok_oct` returns `UV_MAX`, sets `PERL_SCAN_GREATER_THAN_UV_MAX` in the output flags, and writes an approximation of the correct value into `*result` (which is an NV; or the approximation is discarded if `result` is NULL).
If `PERL_SCAN_ALLOW_UNDERSCORES` is set in `*flags` then any or all pairs of digits may be separated from each other by a single underscore; also a single leading underscore is accepted.
The `PERL_SCAN_DISALLOW_PREFIX` flag is always treated as being set for this function.
```
UV grok_oct(const char* start, STRLEN* len_p, I32* flags,
NV *result)
```
`isinfnan` `Perl_isinfnan()` is a utility function that returns true if the NV argument is either an infinity or a `NaN`, false otherwise. To test in more detail, use `Perl_isinf()` and `Perl_isnan()`.
This is also the logical inverse of Perl\_isfinite().
```
bool isinfnan(NV nv)
```
`my_atof` [`atof`(3)](atof(3)), but properly works with Perl locale handling, accepting a dot radix character always, but also the current locale's radix character if and only if called from within the lexical scope of a Perl `use locale` statement.
N.B. `s` must be NUL terminated.
```
NV my_atof(const char *s)
```
`my_strtod` This function is equivalent to the libc strtod() function, and is available even on platforms that lack plain strtod(). Its return value is the best available precision depending on platform capabilities and *Configure* options.
It properly handles the locale radix character, meaning it expects a dot except when called from within the scope of `use locale`, in which case the radix character should be that specified by the current locale.
The synonym Strtod() may be used instead.
```
NV my_strtod(const char * const s, char ** e)
```
`PERL_ABS` Typeless `abs` or `fabs`, *etc*. (The usage below indicates it is for integers, but it works for any type.) Use instead of these, since the C library ones force their argument to be what it is expecting, potentially leading to disaster. But also beware that this evaluates its argument twice, so no `x++`.
```
int PERL_ABS(int x)
```
`Perl_acos` `Perl_asin` `Perl_atan` `Perl_atan2` `Perl_ceil` `Perl_cos` `Perl_cosh` `Perl_exp` `Perl_floor` `Perl_fmod` `Perl_frexp` `Perl_isfinite` `Perl_isinf` `Perl_isnan` `Perl_ldexp` `Perl_log` `Perl_log10` `Perl_modf` `Perl_pow` `Perl_sin` `Perl_sinh` `Perl_sqrt` `Perl_tan`
`Perl_tanh` These perform the corresponding mathematical operation on the operand(s), using the libc function designed for the task that has just enough precision for an NV on this platform. If no such function with sufficient precision exists, the highest precision one available is used.
```
NV Perl_acos (NV x)
NV Perl_asin (NV x)
NV Perl_atan (NV x)
NV Perl_atan2 (NV x, NV y)
NV Perl_ceil (NV x)
NV Perl_cos (NV x)
NV Perl_cosh (NV x)
NV Perl_exp (NV x)
NV Perl_floor (NV x)
NV Perl_fmod (NV x, NV y)
NV Perl_frexp (NV x, int *exp)
IV Perl_isfinite(NV x)
IV Perl_isinf (NV x)
IV Perl_isnan (NV x)
NV Perl_ldexp (NV x, int exp)
NV Perl_log (NV x)
NV Perl_log10 (NV x)
NV Perl_modf (NV x, NV *iptr)
NV Perl_pow (NV x, NV y)
NV Perl_sin (NV x)
NV Perl_sinh (NV x)
NV Perl_sqrt (NV x)
NV Perl_tan (NV x)
NV Perl_tanh (NV x)
```
`Perl_signbit` NOTE: `Perl_signbit` is **experimental** and may change or be removed without notice.
Return a non-zero integer if the sign bit on an NV is set, and 0 if it is not.
If *Configure* detects this system has a `signbit()` that will work with our NVs, then we just use it via the `#define` in *perl.h*. Otherwise, fall back on this implementation. The main use of this function is catching `-0.0`.
`Configure` notes: This function is called `'Perl_signbit'` instead of a plain `'signbit'` because it is easy to imagine a system having a `signbit()` function or macro that doesn't happen to work with our particular choice of NVs. We shouldn't just re-`#define` `signbit` as `Perl_signbit` and expect the standard system headers to be happy. Also, this is a no-context function (no `pTHX_`) because `Perl_signbit()` is usually re-`#defined` in *perl.h* as a simple macro call to the system's `signbit()`. Users should just always call `Perl_signbit()`.
```
int Perl_signbit(NV f)
```
`PL_hexdigit` This array, indexed by an integer, converts that value into the character that represents it. For example, if the input is 8, the return will be a string whose first character is '8'. What is actually returned is a pointer into a string. All you are interested in is the first character of that string. To get uppercase letters (for the values 10..15), add 16 to the index. Hence, `PL_hexdigit[11]` is `'b'`, and `PL_hexdigit[11+16]` is `'B'`. Adding 16 to an index whose representation is '0'..'9' yields the same as not adding 16. Indices outside the range 0..31 result in (bad) undedefined behavior.
`READ_XDIGIT` Returns the value of an ASCII-range hex digit and advances the string pointer. Behaviour is only well defined when isXDIGIT(\*str) is true.
```
U8 READ_XDIGIT(char str*)
```
`scan_bin` For backwards compatibility. Use `grok_bin` instead.
```
NV scan_bin(const char* start, STRLEN len, STRLEN* retlen)
```
`scan_hex` For backwards compatibility. Use `grok_hex` instead.
```
NV scan_hex(const char* start, STRLEN len, STRLEN* retlen)
```
`scan_oct` For backwards compatibility. Use `grok_oct` instead.
```
NV scan_oct(const char* start, STRLEN len, STRLEN* retlen)
```
`seedDrand01` This symbol defines the macro to be used in seeding the random number generator (see `["Drand01"](#Drand01)`).
```
void seedDrand01(Rand_seed_t x)
```
`Strtod` This is a synonym for ["my\_strtod"](#my_strtod).
```
NV Strtod(NN const char * const s, NULLOK char ** e)
```
`Strtol` Platform and configuration independent `strtol`. This expands to the appropriate `strotol`-like function based on the platform and *Configure* options>. For example it could expand to `strtoll` or `strtoq` instead of `strtol`.
```
NV Strtol(NN const char * const s, NULLOK char ** e, int base)
```
`Strtoul` Platform and configuration independent `strtoul`. This expands to the appropriate `strotoul`-like function based on the platform and *Configure* options>. For example it could expand to `strtoull` or `strtouq` instead of `strtoul`.
```
NV Strtoul(NN const char * const s, NULLOK char ** e, int base)
```
Optrees
-------
`alloccopstash` NOTE: `alloccopstash` is **experimental** and may change or be removed without notice.
Available only under threaded builds, this function allocates an entry in `PL_stashpad` for the stash passed to it.
```
PADOFFSET alloccopstash(HV *hv)
```
`BINOP` Described in <perlguts>.
`block_end` Handles compile-time scope exit. `floor` is the savestack index returned by `block_start`, and `seq` is the body of the block. Returns the block, possibly modified.
```
OP* block_end(I32 floor, OP* seq)
```
`block_start` Handles compile-time scope entry. Arranges for hints to be restored on block exit and also handles pad sequence numbers to make lexical variables scope right. Returns a savestack index for use with `block_end`.
```
int block_start(int full)
```
`ck_entersub_args_list` Performs the default fixup of the arguments part of an `entersub` op tree. This consists of applying list context to each of the argument ops. This is the standard treatment used on a call marked with `&`, or a method call, or a call through a subroutine reference, or any other call where the callee can't be identified at compile time, or a call where the callee has no prototype.
```
OP* ck_entersub_args_list(OP *entersubop)
```
`ck_entersub_args_proto` Performs the fixup of the arguments part of an `entersub` op tree based on a subroutine prototype. This makes various modifications to the argument ops, from applying context up to inserting `refgen` ops, and checking the number and syntactic types of arguments, as directed by the prototype. This is the standard treatment used on a subroutine call, not marked with `&`, where the callee can be identified at compile time and has a prototype.
`protosv` supplies the subroutine prototype to be applied to the call. It may be a normal defined scalar, of which the string value will be used. Alternatively, for convenience, it may be a subroutine object (a `CV*` that has been cast to `SV*`) which has a prototype. The prototype supplied, in whichever form, does not need to match the actual callee referenced by the op tree.
If the argument ops disagree with the prototype, for example by having an unacceptable number of arguments, a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. In the error message, the callee is referred to by the name defined by the `namegv` parameter.
```
OP* ck_entersub_args_proto(OP *entersubop, GV *namegv,
SV *protosv)
```
`ck_entersub_args_proto_or_list` Performs the fixup of the arguments part of an `entersub` op tree either based on a subroutine prototype or using default list-context processing. This is the standard treatment used on a subroutine call, not marked with `&`, where the callee can be identified at compile time.
`protosv` supplies the subroutine prototype to be applied to the call, or indicates that there is no prototype. It may be a normal scalar, in which case if it is defined then the string value will be used as a prototype, and if it is undefined then there is no prototype. Alternatively, for convenience, it may be a subroutine object (a `CV*` that has been cast to `SV*`), of which the prototype will be used if it has one. The prototype (or lack thereof) supplied, in whichever form, does not need to match the actual callee referenced by the op tree.
If the argument ops disagree with the prototype, for example by having an unacceptable number of arguments, a valid op tree is returned anyway. The error is reflected in the parser state, normally resulting in a single exception at the top level of parsing which covers all the compilation errors that occurred. In the error message, the callee is referred to by the name defined by the `namegv` parameter.
```
OP* ck_entersub_args_proto_or_list(OP *entersubop, GV *namegv,
SV *protosv)
```
`cv_const_sv` If `cv` is a constant sub eligible for inlining, returns the constant value returned by the sub. Otherwise, returns `NULL`.
Constant subs can be created with `newCONSTSUB` or as described in ["Constant Functions" in perlsub](perlsub#Constant-Functions).
```
SV* cv_const_sv(const CV *const cv)
```
`cv_get_call_checker` The original form of ["cv\_get\_call\_checker\_flags"](#cv_get_call_checker_flags), which does not return checker flags. When using a checker function returned by this function, it is only safe to call it with a genuine GV as its `namegv` argument.
```
void cv_get_call_checker(CV *cv, Perl_call_checker *ckfun_p,
SV **ckobj_p)
```
`cv_get_call_checker_flags` Retrieves the function that will be used to fix up a call to `cv`. Specifically, the function is applied to an `entersub` op tree for a subroutine call, not marked with `&`, where the callee can be identified at compile time as `cv`.
The C-level function pointer is returned in `*ckfun_p`, an SV argument for it is returned in `*ckobj_p`, and control flags are returned in `*ckflags_p`. The function is intended to be called in this manner:
```
entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
```
In this call, `entersubop` is a pointer to the `entersub` op, which may be replaced by the check function, and `namegv` supplies the name that should be used by the check function to refer to the callee of the `entersub` op if it needs to emit any diagnostics. It is permitted to apply the check function in non-standard situations, such as to a call to a different subroutine or to a method call.
`namegv` may not actually be a GV. If the `CALL_CHECKER_REQUIRE_GV` bit is clear in `*ckflags_p`, it is permitted to pass a CV or other SV instead, anything that can be used as the first argument to ["cv\_name"](#cv_name). If the `CALL_CHECKER_REQUIRE_GV` bit is set in `*ckflags_p` then the check function requires `namegv` to be a genuine GV.
By default, the check function is [Perl\_ck\_entersub\_args\_proto\_or\_list](#ck_entersub_args_proto_or_list), the SV parameter is `cv` itself, and the `CALL_CHECKER_REQUIRE_GV` flag is clear. This implements standard prototype processing. It can be changed, for a particular subroutine, by ["cv\_set\_call\_checker\_flags"](#cv_set_call_checker_flags).
If the `CALL_CHECKER_REQUIRE_GV` bit is set in `gflags` then it indicates that the caller only knows about the genuine GV version of `namegv`, and accordingly the corresponding bit will always be set in `*ckflags_p`, regardless of the check function's recorded requirements. If the `CALL_CHECKER_REQUIRE_GV` bit is clear in `gflags` then it indicates the caller knows about the possibility of passing something other than a GV as `namegv`, and accordingly the corresponding bit may be either set or clear in `*ckflags_p`, indicating the check function's recorded requirements.
`gflags` is a bitset passed into `cv_get_call_checker_flags`, in which only the `CALL_CHECKER_REQUIRE_GV` bit currently has a defined meaning (for which see above). All other bits should be clear.
```
void cv_get_call_checker_flags(CV *cv, U32 gflags,
Perl_call_checker *ckfun_p,
SV **ckobj_p, U32 *ckflags_p)
```
`cv_set_call_checker` The original form of ["cv\_set\_call\_checker\_flags"](#cv_set_call_checker_flags), which passes it the `CALL_CHECKER_REQUIRE_GV` flag for backward-compatibility. The effect of that flag setting is that the check function is guaranteed to get a genuine GV as its `namegv` argument.
```
void cv_set_call_checker(CV *cv, Perl_call_checker ckfun,
SV *ckobj)
```
`cv_set_call_checker_flags` Sets the function that will be used to fix up a call to `cv`. Specifically, the function is applied to an `entersub` op tree for a subroutine call, not marked with `&`, where the callee can be identified at compile time as `cv`.
The C-level function pointer is supplied in `ckfun`, an SV argument for it is supplied in `ckobj`, and control flags are supplied in `ckflags`. The function should be defined like this:
```
STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
```
It is intended to be called in this manner:
```
entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
```
In this call, `entersubop` is a pointer to the `entersub` op, which may be replaced by the check function, and `namegv` supplies the name that should be used by the check function to refer to the callee of the `entersub` op if it needs to emit any diagnostics. It is permitted to apply the check function in non-standard situations, such as to a call to a different subroutine or to a method call.
`namegv` may not actually be a GV. For efficiency, perl may pass a CV or other SV instead. Whatever is passed can be used as the first argument to ["cv\_name"](#cv_name). You can force perl to pass a GV by including `CALL_CHECKER_REQUIRE_GV` in the `ckflags`.
`ckflags` is a bitset, in which only the `CALL_CHECKER_REQUIRE_GV` bit currently has a defined meaning (for which see above). All other bits should be clear.
The current setting for a particular CV can be retrieved by ["cv\_get\_call\_checker\_flags"](#cv_get_call_checker_flags).
```
void cv_set_call_checker_flags(CV *cv, Perl_call_checker ckfun,
SV *ckobj, U32 ckflags)
```
`LINKLIST` Given the root of an optree, link the tree in execution order using the `op_next` pointers and return the first op executed. If this has already been done, it will not be redone, and `o->op_next` will be returned. If `o->op_next` is not already set, `o` should be at least an `UNOP`.
```
OP* LINKLIST(OP *o)
```
`LISTOP` Described in <perlguts>.
`LOGOP` Described in <perlguts>.
`LOOP` Described in <perlguts>.
`newASSIGNOP` Constructs, checks, and returns an assignment op. `left` and `right` supply the parameters of the assignment; they are consumed by this function and become part of the constructed op tree.
If `optype` is `OP_ANDASSIGN`, `OP_ORASSIGN`, or `OP_DORASSIGN`, then a suitable conditional optree is constructed. If `optype` is the opcode of a binary operator, such as `OP_BIT_OR`, then an op is constructed that performs the binary operation and assigns the result to the left argument. Either way, if `optype` is non-zero then `flags` has no effect.
If `optype` is zero, then a plain scalar or list assignment is constructed. Which type of assignment it is is automatically determined. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 or 2 is automatically set as required.
```
OP* newASSIGNOP(I32 flags, OP* left, I32 optype, OP* right)
```
`newATTRSUB` Construct a Perl subroutine, also performing some surrounding jobs.
This is the same as ["`newATTRSUB_x`" in perlintern](perlintern#newATTRSUB_x) with its `o_is_gv` parameter set to FALSE. This means that if `o` is null, the new sub will be anonymous; otherwise the name will be derived from `o` in the way described (as with all other details) in ["`newATTRSUB_x`" in perlintern](perlintern#newATTRSUB_x).
```
CV* newATTRSUB(I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
```
`newBINOP` Constructs, checks, and returns an op of any binary type. `type` is the opcode. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 or 2 is automatically set as required. `first` and `last` supply up to two ops to be the direct children of the binary op; they are consumed by this function and become part of the constructed op tree.
```
OP* newBINOP(I32 type, I32 flags, OP* first, OP* last)
```
`newCONDOP` Constructs, checks, and returns a conditional-expression (`cond_expr`) op. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 is automatically set. `first` supplies the expression selecting between the two branches, and `trueop` and `falseop` supply the branches; they are consumed by this function and become part of the constructed op tree.
```
OP* newCONDOP(I32 flags, OP* first, OP* trueop, OP* falseop)
```
`newCONSTSUB` Behaves like ["newCONSTSUB\_flags"](#newCONSTSUB_flags), except that `name` is nul-terminated rather than of counted length, and no flags are set. (This means that `name` is always interpreted as Latin-1.)
```
CV* newCONSTSUB(HV* stash, const char* name, SV* sv)
```
`newCONSTSUB_flags` Construct a constant subroutine, also performing some surrounding jobs. A scalar constant-valued subroutine is eligible for inlining at compile-time, and in Perl code can be created by `sub FOO () { 123 }`. Other kinds of constant subroutine have other treatment.
The subroutine will have an empty prototype and will ignore any arguments when called. Its constant behaviour is determined by `sv`. If `sv` is null, the subroutine will yield an empty list. If `sv` points to a scalar, the subroutine will always yield that scalar. If `sv` points to an array, the subroutine will always yield a list of the elements of that array in list context, or the number of elements in the array in scalar context. This function takes ownership of one counted reference to the scalar or array, and will arrange for the object to live as long as the subroutine does. If `sv` points to a scalar then the inlining assumes that the value of the scalar will never change, so the caller must ensure that the scalar is not subsequently written to. If `sv` points to an array then no such assumption is made, so it is ostensibly safe to mutate the array or its elements, but whether this is really supported has not been determined.
The subroutine will have `CvFILE` set according to `PL_curcop`. Other aspects of the subroutine will be left in their default state. The caller is free to mutate the subroutine beyond its initial state after this function has returned.
If `name` is null then the subroutine will be anonymous, with its `CvGV` referring to an `__ANON__` glob. If `name` is non-null then the subroutine will be named accordingly, referenced by the appropriate glob. `name` is a string of length `len` bytes giving a sigilless symbol name, in UTF-8 if `flags` has the `SVf_UTF8` bit set and in Latin-1 otherwise. The name may be either qualified or unqualified. If the name is unqualified then it defaults to being in the stash specified by `stash` if that is non-null, or to `PL_curstash` if `stash` is null. The symbol is always added to the stash if necessary, with `GV_ADDMULTI` semantics.
`flags` should not have bits set other than `SVf_UTF8`.
If there is already a subroutine of the specified name, then the new sub will replace the existing one in the glob. A warning may be generated about the redefinition.
If the subroutine has one of a few special names, such as `BEGIN` or `END`, then it will be claimed by the appropriate queue for automatic running of phase-related subroutines. In this case the relevant glob will be left not containing any subroutine, even if it did contain one before. Execution of the subroutine will likely be a no-op, unless `sv` was a tied array or the caller modified the subroutine in some interesting way before it was executed. In the case of `BEGIN`, the treatment is buggy: the sub will be executed when only half built, and may be deleted prematurely, possibly causing a crash.
The function returns a pointer to the constructed subroutine. If the sub is anonymous then ownership of one counted reference to the subroutine is transferred to the caller. If the sub is named then the caller does not get ownership of a reference. In most such cases, where the sub has a non-phase name, the sub will be alive at the point it is returned by virtue of being contained in the glob that names it. A phase-named subroutine will usually be alive by virtue of the reference owned by the phase's automatic run queue. A `BEGIN` subroutine may have been destroyed already by the time this function returns, but currently bugs occur in that case before the caller gets control. It is the caller's responsibility to ensure that it knows which of these situations applies.
```
CV* newCONSTSUB_flags(HV* stash, const char* name, STRLEN len,
U32 flags, SV* sv)
```
`newDEFEROP` NOTE: `newDEFEROP` is **experimental** and may change or be removed without notice.
Constructs and returns a deferred-block statement that implements the `defer` semantics. The `block` optree is consumed by this function and becomes part of the returned optree.
The `flags` argument carries additional flags to set on the returned op, including the `op_private` field.
```
OP* newDEFEROP(I32 flags, OP *block)
```
`newDEFSVOP` Constructs and returns an op to access `$_`.
```
OP* newDEFSVOP()
```
`newFOROP` Constructs, checks, and returns an op tree expressing a `foreach` loop (iteration through a list of values). This is a heavyweight loop, with structure that allows exiting the loop by `last` and suchlike.
`sv` optionally supplies the variable(s) that will be aliased to each item in turn; if null, it defaults to `$_`. `expr` supplies the list of values to iterate over. `block` supplies the main body of the loop, and `cont` optionally supplies a `continue` block that operates as a second half of the body. All of these optree inputs are consumed by this function and become part of the constructed op tree.
`flags` gives the eight bits of `op_flags` for the `leaveloop` op and, shifted up eight bits, the eight bits of `op_private` for the `leaveloop` op, except that (in both cases) some bits will be set automatically.
```
OP* newFOROP(I32 flags, OP* sv, OP* expr, OP* block, OP* cont)
```
`newGIVENOP` Constructs, checks, and returns an op tree expressing a `given` block. `cond` supplies the expression to whose value `$_` will be locally aliased, and `block` supplies the body of the `given` construct; they are consumed by this function and become part of the constructed op tree. `defsv_off` must be zero (it used to identity the pad slot of lexical $\_).
```
OP* newGIVENOP(OP* cond, OP* block, PADOFFSET defsv_off)
```
`newGVOP` Constructs, checks, and returns an op of any type that involves an embedded reference to a GV. `type` is the opcode. `flags` gives the eight bits of `op_flags`. `gv` identifies the GV that the op should reference; calling this function does not transfer ownership of any reference to it.
```
OP* newGVOP(I32 type, I32 flags, GV* gv)
```
`newLISTOP` Constructs, checks, and returns an op of any list type. `type` is the opcode. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically if required. `first` and `last` supply up to two ops to be direct children of the list op; they are consumed by this function and become part of the constructed op tree.
For most list operators, the check function expects all the kid ops to be present already, so calling `newLISTOP(OP_JOIN, ...)` (e.g.) is not appropriate. What you want to do in that case is create an op of type `OP_LIST`, append more children to it, and then call ["op\_convert\_list"](#op_convert_list). See ["op\_convert\_list"](#op_convert_list) for more information.
```
OP* newLISTOP(I32 type, I32 flags, OP* first, OP* last)
```
`newLOGOP` Constructs, checks, and returns a logical (flow control) op. `type` is the opcode. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 is automatically set. `first` supplies the expression controlling the flow, and `other` supplies the side (alternate) chain of ops; they are consumed by this function and become part of the constructed op tree.
```
OP* newLOGOP(I32 optype, I32 flags, OP *first, OP *other)
```
`newLOOPEX` Constructs, checks, and returns a loop-exiting op (such as `goto` or `last`). `type` is the opcode. `label` supplies the parameter determining the target of the op; it is consumed by this function and becomes part of the constructed op tree.
```
OP* newLOOPEX(I32 type, OP* label)
```
`newLOOPOP` Constructs, checks, and returns an op tree expressing a loop. This is only a loop in the control flow through the op tree; it does not have the heavyweight loop structure that allows exiting the loop by `last` and suchlike. `flags` gives the eight bits of `op_flags` for the top-level op, except that some bits will be set automatically as required. `expr` supplies the expression controlling loop iteration, and `block` supplies the body of the loop; they are consumed by this function and become part of the constructed op tree. `debuggable` is currently unused and should always be 1.
```
OP* newLOOPOP(I32 flags, I32 debuggable, OP* expr, OP* block)
```
`newMETHOP` Constructs, checks, and returns an op of method type with a method name evaluated at runtime. `type` is the opcode. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 is automatically set. `dynamic_meth` supplies an op which evaluates method name; it is consumed by this function and become part of the constructed op tree. Supported optypes: `OP_METHOD`.
```
OP* newMETHOP(I32 type, I32 flags, OP* dynamic_meth)
```
`newMETHOP_named` Constructs, checks, and returns an op of method type with a constant method name. `type` is the opcode. `flags` gives the eight bits of `op_flags`, and, shifted up eight bits, the eight bits of `op_private`. `const_meth` supplies a constant method name; it must be a shared COW string. Supported optypes: `OP_METHOD_NAMED`.
```
OP* newMETHOP_named(I32 type, I32 flags, SV* const_meth)
```
`newNULLLIST` Constructs, checks, and returns a new `stub` op, which represents an empty list expression.
```
OP* newNULLLIST()
```
`newOP` Constructs, checks, and returns an op of any base type (any type that has no extra fields). `type` is the opcode. `flags` gives the eight bits of `op_flags`, and, shifted up eight bits, the eight bits of `op_private`.
```
OP* newOP(I32 optype, I32 flags)
```
`newPADOP` Constructs, checks, and returns an op of any type that involves a reference to a pad element. `type` is the opcode. `flags` gives the eight bits of `op_flags`. A pad slot is automatically allocated, and is populated with `sv`; this function takes ownership of one reference to it.
This function only exists if Perl has been compiled to use ithreads.
```
OP* newPADOP(I32 type, I32 flags, SV* sv)
```
`newPMOP` Constructs, checks, and returns an op of any pattern matching type. `type` is the opcode. `flags` gives the eight bits of `op_flags` and, shifted up eight bits, the eight bits of `op_private`.
```
OP* newPMOP(I32 type, I32 flags)
```
`newPVOP` Constructs, checks, and returns an op of any type that involves an embedded C-level pointer (PV). `type` is the opcode. `flags` gives the eight bits of `op_flags`. `pv` supplies the C-level pointer. Depending on the op type, the memory referenced by `pv` may be freed when the op is destroyed. If the op is of a freeing type, `pv` must have been allocated using `PerlMemShared_malloc`.
```
OP* newPVOP(I32 type, I32 flags, char* pv)
```
`newRANGE` Constructs and returns a `range` op, with subordinate `flip` and `flop` ops. `flags` gives the eight bits of `op_flags` for the `flip` op and, shifted up eight bits, the eight bits of `op_private` for both the `flip` and `range` ops, except that the bit with value 1 is automatically set. `left` and `right` supply the expressions controlling the endpoints of the range; they are consumed by this function and become part of the constructed op tree.
```
OP* newRANGE(I32 flags, OP* left, OP* right)
```
`newSLICEOP` Constructs, checks, and returns an `lslice` (list slice) op. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 or 2 is automatically set as required. `listval` and `subscript` supply the parameters of the slice; they are consumed by this function and become part of the constructed op tree.
```
OP* newSLICEOP(I32 flags, OP* subscript, OP* listop)
```
`newSTATEOP` Constructs a state op (COP). The state op is normally a `nextstate` op, but will be a `dbstate` op if debugging is enabled for currently-compiled code. The state op is populated from `PL_curcop` (or `PL_compiling`). If `label` is non-null, it supplies the name of a label to attach to the state op; this function takes ownership of the memory pointed at by `label`, and will free it. `flags` gives the eight bits of `op_flags` for the state op.
If `o` is null, the state op is returned. Otherwise the state op is combined with `o` into a `lineseq` list op, which is returned. `o` is consumed by this function and becomes part of the returned op tree.
```
OP* newSTATEOP(I32 flags, char* label, OP* o)
```
`newSUB` Like `["newATTRSUB"](#newATTRSUB)`, but without attributes.
```
CV* newSUB(I32 floor, OP* o, OP* proto, OP* block)
```
`newSVOP` Constructs, checks, and returns an op of any type that involves an embedded SV. `type` is the opcode. `flags` gives the eight bits of `op_flags`. `sv` gives the SV to embed in the op; this function takes ownership of one reference to it.
```
OP* newSVOP(I32 type, I32 flags, SV* sv)
```
`newTRYCATCHOP` NOTE: `newTRYCATCHOP` is **experimental** and may change or be removed without notice.
Constructs and returns a conditional execution statement that implements the `try`/`catch` semantics. First the op tree in `tryblock` is executed, inside a context that traps exceptions. If an exception occurs then the optree in `catchblock` is executed, with the trapped exception set into the lexical variable given by `catchvar` (which must be an op of type `OP_PADSV`). All the optrees are consumed by this function and become part of the returned op tree.
The `flags` argument is currently ignored.
```
OP* newTRYCATCHOP(I32 flags, OP* tryblock, OP *catchvar,
OP* catchblock)
```
`newUNOP` Constructs, checks, and returns an op of any unary type. `type` is the opcode. `flags` gives the eight bits of `op_flags`, except that `OPf_KIDS` will be set automatically if required, and, shifted up eight bits, the eight bits of `op_private`, except that the bit with value 1 is automatically set. `first` supplies an optional op to be the direct child of the unary op; it is consumed by this function and become part of the constructed op tree.
```
OP* newUNOP(I32 type, I32 flags, OP* first)
```
`newUNOP_AUX` Similar to `newUNOP`, but creates an `UNOP_AUX` struct instead, with `op_aux` initialised to `aux`
```
OP* newUNOP_AUX(I32 type, I32 flags, OP* first,
UNOP_AUX_item *aux)
```
`newWHENOP` Constructs, checks, and returns an op tree expressing a `when` block. `cond` supplies the test expression, and `block` supplies the block that will be executed if the test evaluates to true; they are consumed by this function and become part of the constructed op tree. `cond` will be interpreted DWIMically, often as a comparison against `$_`, and may be null to generate a `default` block.
```
OP* newWHENOP(OP* cond, OP* block)
```
`newWHILEOP` Constructs, checks, and returns an op tree expressing a `while` loop. This is a heavyweight loop, with structure that allows exiting the loop by `last` and suchlike.
`loop` is an optional preconstructed `enterloop` op to use in the loop; if it is null then a suitable op will be constructed automatically. `expr` supplies the loop's controlling expression. `block` supplies the main body of the loop, and `cont` optionally supplies a `continue` block that operates as a second half of the body. All of these optree inputs are consumed by this function and become part of the constructed op tree.
`flags` gives the eight bits of `op_flags` for the `leaveloop` op and, shifted up eight bits, the eight bits of `op_private` for the `leaveloop` op, except that (in both cases) some bits will be set automatically. `debuggable` is currently unused and should always be 1. `has_my` can be supplied as true to force the loop body to be enclosed in its own scope.
```
OP* newWHILEOP(I32 flags, I32 debuggable, LOOP* loop, OP* expr,
OP* block, OP* cont, I32 has_my)
```
`newXS` Used by `xsubpp` to hook up XSUBs as Perl subs. `filename` needs to be static storage, as it is used directly as CvFILE(), without a copy being made.
`OA_BASEOP` `OA_BINOP` `OA_COP` `OA_LISTOP` `OA_LOGOP` `OA_PADOP` `OA_PMOP` `OA_PVOP_OR_SVOP` `OA_SVOP` `OA_UNOP` `OA_LOOP` Described in <perlguts>.
`OP` Described in <perlguts>.
`op_append_elem` Append an item to the list of ops contained directly within a list-type op, returning the lengthened list. `first` is the list-type op, and `last` is the op to append to the list. `optype` specifies the intended opcode for the list. If `first` is not already a list of the right type, it will be upgraded into one. If either `first` or `last` is null, the other is returned unchanged.
```
OP* op_append_elem(I32 optype, OP* first, OP* last)
```
`op_append_list` Concatenate the lists of ops contained directly within two list-type ops, returning the combined list. `first` and `last` are the list-type ops to concatenate. `optype` specifies the intended opcode for the list. If either `first` or `last` is not already a list of the right type, it will be upgraded into one. If either `first` or `last` is null, the other is returned unchanged.
```
OP* op_append_list(I32 optype, OP* first, OP* last)
```
`OP_CLASS` Return the class of the provided OP: that is, which of the \*OP structures it uses. For core ops this currently gets the information out of `PL_opargs`, which does not always accurately reflect the type used; in v5.26 onwards, see also the function `["op\_class"](#op_class)` which can do a better job of determining the used type.
For custom ops the type is returned from the registration, and it is up to the registree to ensure it is accurate. The value returned will be one of the `OA_`\* constants from *op.h*.
```
U32 OP_CLASS(OP *o)
```
`op_contextualize` Applies a syntactic context to an op tree representing an expression. `o` is the op tree, and `context` must be `G_SCALAR`, `G_LIST`, or `G_VOID` to specify the context to apply. The modified op tree is returned.
```
OP* op_contextualize(OP* o, I32 context)
```
`op_convert_list` Converts `o` into a list op if it is not one already, and then converts it into the specified `type`, calling its check function, allocating a target if it needs one, and folding constants.
A list-type op is usually constructed one kid at a time via `newLISTOP`, `op_prepend_elem` and `op_append_elem`. Then finally it is passed to `op_convert_list` to make it the right type.
```
OP* op_convert_list(I32 optype, I32 flags, OP* o)
```
`OP_DESC` Return a short description of the provided OP.
```
const char * OP_DESC(OP *o)
```
`op_free` Free an op and its children. Only use this when an op is no longer linked to from any optree.
```
void op_free(OP* arg)
```
`OpHAS_SIBLING` Returns true if `o` has a sibling
```
bool OpHAS_SIBLING(OP *o)
```
`OpLASTSIB_set` Marks `o` as having no further siblings and marks o as having the specified parent. See also `["OpMORESIB\_set"](#OpMORESIB_set)` and `OpMAYBESIB_set`. For a higher-level interface, see `["op\_sibling\_splice"](#op_sibling_splice)`.
```
void OpLASTSIB_set(OP *o, OP *parent)
```
`op_linklist` This function is the implementation of the ["LINKLIST"](#LINKLIST) macro. It should not be called directly.
```
OP* op_linklist(OP *o)
```
`op_lvalue` NOTE: `op_lvalue` is **experimental** and may change or be removed without notice.
Propagate lvalue ("modifiable") context to an op and its children. `type` represents the context type, roughly based on the type of op that would do the modifying, although `local()` is represented by `OP_NULL`, because it has no op type of its own (it is signalled by a flag on the lvalue op).
This function detects things that can't be modified, such as `$x+1`, and generates errors for them. For example, `$x+1 = 2` would cause it to be called with an op of type `OP_ADD` and a `type` argument of `OP_SASSIGN`.
It also flags things that need to behave specially in an lvalue context, such as `$$x = 5` which might have to vivify a reference in `$x`.
```
OP* op_lvalue(OP* o, I32 type)
```
`OpMAYBESIB_set` Conditionally does `OpMORESIB_set` or `OpLASTSIB_set` depending on whether `sib` is non-null. For a higher-level interface, see `["op\_sibling\_splice"](#op_sibling_splice)`.
```
void OpMAYBESIB_set(OP *o, OP *sib, OP *parent)
```
`OpMORESIB_set` Sets the sibling of `o` to the non-zero value `sib`. See also `["OpLASTSIB\_set"](#OpLASTSIB_set)` and `["OpMAYBESIB\_set"](#OpMAYBESIB_set)`. For a higher-level interface, see `["op\_sibling\_splice"](#op_sibling_splice)`.
```
void OpMORESIB_set(OP *o, OP *sib)
```
`OP_NAME` Return the name of the provided OP. For core ops this looks up the name from the op\_type; for custom ops from the op\_ppaddr.
```
const char * OP_NAME(OP *o)
```
`op_null` Neutralizes an op when it is no longer needed, but is still linked to from other ops.
```
void op_null(OP* o)
```
`op_parent` Returns the parent OP of `o`, if it has a parent. Returns `NULL` otherwise.
```
OP* op_parent(OP *o)
```
`op_prepend_elem` Prepend an item to the list of ops contained directly within a list-type op, returning the lengthened list. `first` is the op to prepend to the list, and `last` is the list-type op. `optype` specifies the intended opcode for the list. If `last` is not already a list of the right type, it will be upgraded into one. If either `first` or `last` is null, the other is returned unchanged.
```
OP* op_prepend_elem(I32 optype, OP* first, OP* last)
```
`op_scope` NOTE: `op_scope` is **experimental** and may change or be removed without notice.
Wraps up an op tree with some additional ops so that at runtime a dynamic scope will be created. The original ops run in the new dynamic scope, and then, provided that they exit normally, the scope will be unwound. The additional ops used to create and unwind the dynamic scope will normally be an `enter`/`leave` pair, but a `scope` op may be used instead if the ops are simple enough to not need the full dynamic scope structure.
```
OP* op_scope(OP* o)
```
`OpSIBLING` Returns the sibling of `o`, or `NULL` if there is no sibling
```
OP* OpSIBLING(OP *o)
```
`op_sibling_splice` A general function for editing the structure of an existing chain of op\_sibling nodes. By analogy with the perl-level `splice()` function, allows you to delete zero or more sequential nodes, replacing them with zero or more different nodes. Performs the necessary op\_first/op\_last housekeeping on the parent node and op\_sibling manipulation on the children. The last deleted node will be marked as the last node by updating the op\_sibling/op\_sibparent or op\_moresib field as appropriate.
Note that op\_next is not manipulated, and nodes are not freed; that is the responsibility of the caller. It also won't create a new list op for an empty list etc; use higher-level functions like op\_append\_elem() for that.
`parent` is the parent node of the sibling chain. It may passed as `NULL` if the splicing doesn't affect the first or last op in the chain.
`start` is the node preceding the first node to be spliced. Node(s) following it will be deleted, and ops will be inserted after it. If it is `NULL`, the first node onwards is deleted, and nodes are inserted at the beginning.
`del_count` is the number of nodes to delete. If zero, no nodes are deleted. If -1 or greater than or equal to the number of remaining kids, all remaining kids are deleted.
`insert` is the first of a chain of nodes to be inserted in place of the nodes. If `NULL`, no nodes are inserted.
The head of the chain of deleted ops is returned, or `NULL` if no ops were deleted.
For example:
```
action before after returns
------ ----- ----- -------
P P
splice(P, A, 2, X-Y-Z) | | B-C
A-B-C-D A-X-Y-Z-D
P P
splice(P, NULL, 1, X-Y) | | A
A-B-C-D X-Y-B-C-D
P P
splice(P, NULL, 3, NULL) | | A-B-C
A-B-C-D D
P P
splice(P, B, 0, X-Y) | | NULL
A-B-C-D A-B-X-Y-C-D
```
For lower-level direct manipulation of `op_sibparent` and `op_moresib`, see `["OpMORESIB\_set"](#OpMORESIB_set)`, `["OpLASTSIB\_set"](#OpLASTSIB_set)`, `["OpMAYBESIB\_set"](#OpMAYBESIB_set)`.
```
OP* op_sibling_splice(OP *parent, OP *start, int del_count,
OP* insert)
```
`OP_TYPE_IS` Returns true if the given OP is not a `NULL` pointer and if it is of the given type.
The negation of this macro, `OP_TYPE_ISNT` is also available as well as `OP_TYPE_IS_NN` and `OP_TYPE_ISNT_NN` which elide the NULL pointer check.
```
bool OP_TYPE_IS(OP *o, Optype type)
```
`OP_TYPE_IS_OR_WAS` Returns true if the given OP is not a NULL pointer and if it is of the given type or used to be before being replaced by an OP of type OP\_NULL.
The negation of this macro, `OP_TYPE_ISNT_AND_WASNT` is also available as well as `OP_TYPE_IS_OR_WAS_NN` and `OP_TYPE_ISNT_AND_WASNT_NN` which elide the `NULL` pointer check.
```
bool OP_TYPE_IS_OR_WAS(OP *o, Optype type)
```
`op_wrap_finally` NOTE: `op_wrap_finally` is **experimental** and may change or be removed without notice.
Wraps the given `block` optree fragment in its own scoped block, arranging for the `finally` optree fragment to be invoked when leaving that block for any reason. Both optree fragments are consumed and the combined result is returned.
```
OP* op_wrap_finally(OP *block, OP *finally)
```
`peep_t` Described in <perlguts>.
`Perl_cpeep_t` Described in <perlguts>.
`PL_opfreehook` When non-`NULL`, the function pointed by this variable will be called each time an OP is freed with the corresponding OP as the argument. This allows extensions to free any extra attribute they have locally attached to an OP. It is also assured to first fire for the parent OP and then for its kids.
When you replace this variable, it is considered a good practice to store the possibly previously installed hook and that you recall it inside your own.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
Perl_ophook_t PL_opfreehook
```
`PL_peepp` Pointer to the per-subroutine peephole optimiser. This is a function that gets called at the end of compilation of a Perl subroutine (or equivalently independent piece of Perl code) to perform fixups of some ops and to perform small-scale optimisations. The function is called once for each subroutine that is compiled, and is passed, as sole parameter, a pointer to the op that is the entry point to the subroutine. It modifies the op tree in place.
The peephole optimiser should never be completely replaced. Rather, add code to it by wrapping the existing optimiser. The basic way to do this can be seen in ["Compile pass 3: peephole optimization" in perlguts](perlguts#Compile-pass-3%3A-peephole-optimization). If the new code wishes to operate on ops throughout the subroutine's structure, rather than just at the top level, it is likely to be more convenient to wrap the ["PL\_rpeepp"](#PL_rpeepp) hook.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
peep_t PL_peepp
```
`PL_rpeepp` Pointer to the recursive peephole optimiser. This is a function that gets called at the end of compilation of a Perl subroutine (or equivalently independent piece of Perl code) to perform fixups of some ops and to perform small-scale optimisations. The function is called once for each chain of ops linked through their `op_next` fields; it is recursively called to handle each side chain. It is passed, as sole parameter, a pointer to the op that is at the head of the chain. It modifies the op tree in place.
The peephole optimiser should never be completely replaced. Rather, add code to it by wrapping the existing optimiser. The basic way to do this can be seen in ["Compile pass 3: peephole optimization" in perlguts](perlguts#Compile-pass-3%3A-peephole-optimization). If the new code wishes to operate only on ops at a subroutine's top level, rather than throughout the structure, it is likely to be more convenient to wrap the ["PL\_peepp"](#PL_peepp) hook.
On threaded perls, each thread has an independent copy of this variable; each initialized at creation time with the current value of the creating thread's copy.
```
peep_t PL_rpeepp
```
`PMOP` Described in <perlguts>.
`rv2cv_op_cv` Examines an op, which is expected to identify a subroutine at runtime, and attempts to determine at compile time which subroutine it identifies. This is normally used during Perl compilation to determine whether a prototype can be applied to a function call. `cvop` is the op being considered, normally an `rv2cv` op. A pointer to the identified subroutine is returned, if it could be determined statically, and a null pointer is returned if it was not possible to determine statically.
Currently, the subroutine can be identified statically if the RV that the `rv2cv` is to operate on is provided by a suitable `gv` or `const` op. A `gv` op is suitable if the GV's CV slot is populated. A `const` op is suitable if the constant value must be an RV pointing to a CV. Details of this process may change in future versions of Perl. If the `rv2cv` op has the `OPpENTERSUB_AMPER` flag set then no attempt is made to identify the subroutine statically: this flag is used to suppress compile-time magic on a subroutine call, forcing it to use default runtime behaviour.
If `flags` has the bit `RV2CVOPCV_MARK_EARLY` set, then the handling of a GV reference is modified. If a GV was examined and its CV slot was found to be empty, then the `gv` op has the `OPpEARLY_CV` flag set. If the op is not optimised away, and the CV slot is later populated with a subroutine having a prototype, that flag eventually triggers the warning "called too early to check prototype".
If `flags` has the bit `RV2CVOPCV_RETURN_NAME_GV` set, then instead of returning a pointer to the subroutine it returns a pointer to the GV giving the most appropriate name for the subroutine in this context. Normally this is just the `CvGV` of the subroutine, but for an anonymous (`CvANON`) subroutine that is referenced through a GV it will be the referencing GV. The resulting `GV*` is cast to `CV*` to be returned. A null pointer is returned as usual if there is no statically-determinable subroutine.
```
CV* rv2cv_op_cv(OP *cvop, U32 flags)
```
`UNOP` Described in <perlguts>.
`XOP` Described in <perlguts>.
Pack and Unpack
----------------
`pack_cat` `**DEPRECATED!**` It is planned to remove `pack_cat` from a future release of Perl. Do not use it for new code; remove it from existing code.
The engine implementing `pack()` Perl function. Note: parameters `next_in_list` and `flags` are not used. This call should not be used; use `["packlist"](#packlist)` instead.
```
void pack_cat(SV *cat, const char *pat, const char *patend,
SV **beglist, SV **endlist, SV ***next_in_list,
U32 flags)
```
`packlist` The engine implementing `pack()` Perl function.
```
void packlist(SV *cat, const char *pat, const char *patend,
SV **beglist, SV **endlist)
```
`unpack_str` `**DEPRECATED!**` It is planned to remove `unpack_str` from a future release of Perl. Do not use it for new code; remove it from existing code.
The engine implementing `unpack()` Perl function. Note: parameters `strbeg`, `new_s` and `ocnt` are not used. This call should not be used, use `unpackstring` instead.
```
SSize_t unpack_str(const char *pat, const char *patend,
const char *s, const char *strbeg,
const char *strend, char **new_s, I32 ocnt,
U32 flags)
```
`unpackstring` The engine implementing the `unpack()` Perl function.
Using the template `pat..patend`, this function unpacks the string `s..strend` into a number of mortal SVs, which it pushes onto the perl argument (`@_`) stack (so you will need to issue a `PUTBACK` before and `SPAGAIN` after the call to this function). It returns the number of pushed elements.
The `strend` and `patend` pointers should point to the byte following the last character of each string.
Although this function returns its values on the perl argument stack, it doesn't take any parameters from that stack (and thus in particular there's no need to do a `PUSHMARK` before calling it, unlike ["call\_pv"](#call_pv) for example).
```
SSize_t unpackstring(const char *pat, const char *patend,
const char *s, const char *strend,
U32 flags)
```
Pad Data Structures
--------------------
`CvPADLIST` NOTE: `CvPADLIST` is **experimental** and may change or be removed without notice.
CV's can have CvPADLIST(cv) set to point to a PADLIST. This is the CV's scratchpad, which stores lexical variables and opcode temporary and per-thread values.
For these purposes "formats" are a kind-of CV; eval""s are too (except they're not callable at will and are always thrown away after the eval"" is done executing). Require'd files are simply evals without any outer lexical scope.
XSUBs do not have a `CvPADLIST`. `dXSTARG` fetches values from `PL_curpad`, but that is really the callers pad (a slot of which is allocated by every entersub). Do not get or set `CvPADLIST` if a CV is an XSUB (as determined by `CvISXSUB()`), `CvPADLIST` slot is reused for a different internal purpose in XSUBs.
The PADLIST has a C array where pads are stored.
The 0th entry of the PADLIST is a PADNAMELIST which represents the "names" or rather the "static type information" for lexicals. The individual elements of a PADNAMELIST are PADNAMEs. Future refactorings might stop the PADNAMELIST from being stored in the PADLIST's array, so don't rely on it. See ["PadlistNAMES"](#PadlistNAMES).
The CvDEPTH'th entry of a PADLIST is a PAD (an AV) which is the stack frame at that depth of recursion into the CV. The 0th slot of a frame AV is an AV which is `@_`. Other entries are storage for variables and op targets.
Iterating over the PADNAMELIST iterates over all possible pad items. Pad slots for targets (`SVs_PADTMP`) and GVs end up having &PL\_padname\_undef "names", while slots for constants have `&PL_padname_const` "names" (see `["pad\_alloc"](#pad_alloc)`). That `&PL_padname_undef` and `&PL_padname_const` are used is an implementation detail subject to change. To test for them, use `!PadnamePV(name)` and `PadnamePV(name) && !PadnameLEN(name)`, respectively.
Only `my`/`our` variable slots get valid names. The rest are op targets/GVs/constants which are statically allocated or resolved at compile time. These don't have names by which they can be looked up from Perl code at run time through eval"" the way `my`/`our` variables can be. Since they can't be looked up by "name" but only by their index allocated at compile time (which is usually in `PL_op->op_targ`), wasting a name SV for them doesn't make sense.
The pad names in the PADNAMELIST have their PV holding the name of the variable. The `COP_SEQ_RANGE_LOW` and `_HIGH` fields form a range (low+1..high inclusive) of cop\_seq numbers for which the name is valid. During compilation, these fields may hold the special value PERL\_PADSEQ\_INTRO to indicate various stages:
```
COP_SEQ_RANGE_LOW _HIGH
----------------- -----
PERL_PADSEQ_INTRO 0 variable not yet introduced:
{ my ($x
valid-seq# PERL_PADSEQ_INTRO variable in scope:
{ my ($x);
valid-seq# valid-seq# compilation of scope complete:
{ my ($x); .... }
```
When a lexical var hasn't yet been introduced, it already exists from the perspective of duplicate declarations, but not for variable lookups, e.g.
```
my ($x, $x); # '"my" variable $x masks earlier declaration'
my $x = $x; # equal to my $x = $::x;
```
For typed lexicals `PadnameTYPE` points at the type stash. For `our` lexicals, `PadnameOURSTASH` points at the stash of the associated global (so that duplicate `our` declarations in the same package can be detected). `PadnameGEN` is sometimes used to store the generation number during compilation.
If `PadnameOUTER` is set on the pad name, then that slot in the frame AV is a REFCNT'ed reference to a lexical from "outside". Such entries are sometimes referred to as 'fake'. In this case, the name does not use 'low' and 'high' to store a cop\_seq range, since it is in scope throughout. Instead 'high' stores some flags containing info about the real lexical (is it declared in an anon, and is it capable of being instantiated multiple times?), and for fake ANONs, 'low' contains the index within the parent's pad where the lexical's value is stored, to make cloning quicker.
If the 'name' is `&` the corresponding entry in the PAD is a CV representing a possible closure.
Note that formats are treated as anon subs, and are cloned each time write is called (if necessary).
The flag `SVs_PADSTALE` is cleared on lexicals each time the `my()` is executed, and set on scope exit. This allows the `"Variable $x is not available"` warning to be generated in evals, such as
```
{ my $x = 1; sub f { eval '$x'} } f();
```
For state vars, `SVs_PADSTALE` is overloaded to mean 'not yet initialised', but this internal state is stored in a separate pad entry.
```
PADLIST * CvPADLIST(CV *cv)
```
`pad_add_name_pvs` Exactly like ["pad\_add\_name\_pvn"](#pad_add_name_pvn), but takes a literal string instead of a string/length pair.
```
PADOFFSET pad_add_name_pvs("name", U32 flags, HV *typestash,
HV *ourstash)
```
`PadARRAY` NOTE: `PadARRAY` is **experimental** and may change or be removed without notice.
The C array of pad entries.
```
SV ** PadARRAY(PAD * pad)
```
`pad_compname_type` `**DEPRECATED!**` It is planned to remove `pad_compname_type` from a future release of Perl. Do not use it for new code; remove it from existing code.
Looks up the type of the lexical variable at position `po` in the currently-compiling pad. If the variable is typed, the stash of the class to which it is typed is returned. If not, `NULL` is returned.
Use ["`PAD_COMPNAME_TYPE`" in perlintern](perlintern#PAD_COMPNAME_TYPE) instead.
```
HV* pad_compname_type(const PADOFFSET po)
```
`pad_findmy_pvs` Exactly like ["pad\_findmy\_pvn"](#pad_findmy_pvn), but takes a literal string instead of a string/length pair.
```
PADOFFSET pad_findmy_pvs("name", U32 flags)
```
`PadlistARRAY` NOTE: `PadlistARRAY` is **experimental** and may change or be removed without notice.
The C array of a padlist, containing the pads. Only subscript it with numbers >= 1, as the 0th entry is not guaranteed to remain usable.
```
PAD ** PadlistARRAY(PADLIST * padlist)
```
`PadlistMAX` NOTE: `PadlistMAX` is **experimental** and may change or be removed without notice.
The index of the last allocated space in the padlist. Note that the last pad may be in an earlier slot. Any entries following it will be `NULL` in that case.
```
SSize_t PadlistMAX(PADLIST * padlist)
```
`PadlistNAMES` NOTE: `PadlistNAMES` is **experimental** and may change or be removed without notice.
The names associated with pad entries.
```
PADNAMELIST * PadlistNAMES(PADLIST * padlist)
```
`PadlistNAMESARRAY` NOTE: `PadlistNAMESARRAY` is **experimental** and may change or be removed without notice.
The C array of pad names.
```
PADNAME ** PadlistNAMESARRAY(PADLIST * padlist)
```
`PadlistNAMESMAX` NOTE: `PadlistNAMESMAX` is **experimental** and may change or be removed without notice.
The index of the last pad name.
```
SSize_t PadlistNAMESMAX(PADLIST * padlist)
```
`PadlistREFCNT` NOTE: `PadlistREFCNT` is **experimental** and may change or be removed without notice.
The reference count of the padlist. Currently this is always 1.
```
U32 PadlistREFCNT(PADLIST * padlist)
```
`PadMAX` NOTE: `PadMAX` is **experimental** and may change or be removed without notice.
The index of the last pad entry.
```
SSize_t PadMAX(PAD * pad)
```
`PadnameLEN` NOTE: `PadnameLEN` is **experimental** and may change or be removed without notice.
The length of the name.
```
STRLEN PadnameLEN(PADNAME * pn)
```
`PadnamelistARRAY` NOTE: `PadnamelistARRAY` is **experimental** and may change or be removed without notice.
The C array of pad names.
```
PADNAME ** PadnamelistARRAY(PADNAMELIST * pnl)
```
`PadnamelistMAX` NOTE: `PadnamelistMAX` is **experimental** and may change or be removed without notice.
The index of the last pad name.
```
SSize_t PadnamelistMAX(PADNAMELIST * pnl)
```
`PadnamelistREFCNT` NOTE: `PadnamelistREFCNT` is **experimental** and may change or be removed without notice.
The reference count of the pad name list.
```
SSize_t PadnamelistREFCNT(PADNAMELIST * pnl)
```
`PadnamelistREFCNT_dec` NOTE: `PadnamelistREFCNT_dec` is **experimental** and may change or be removed without notice.
Lowers the reference count of the pad name list.
```
void PadnamelistREFCNT_dec(PADNAMELIST * pnl)
```
`PadnamePV` NOTE: `PadnamePV` is **experimental** and may change or be removed without notice.
The name stored in the pad name struct. This returns `NULL` for a target slot.
```
char * PadnamePV(PADNAME * pn)
```
`PadnameREFCNT` NOTE: `PadnameREFCNT` is **experimental** and may change or be removed without notice.
The reference count of the pad name.
```
SSize_t PadnameREFCNT(PADNAME * pn)
```
`PadnameREFCNT_dec` NOTE: `PadnameREFCNT_dec` is **experimental** and may change or be removed without notice.
Lowers the reference count of the pad name.
```
void PadnameREFCNT_dec(PADNAME * pn)
```
`PadnameSV` NOTE: `PadnameSV` is **experimental** and may change or be removed without notice.
Returns the pad name as a mortal SV.
```
SV * PadnameSV(PADNAME * pn)
```
`PadnameUTF8` NOTE: `PadnameUTF8` is **experimental** and may change or be removed without notice.
Whether PadnamePV is in UTF-8. Currently, this is always true.
```
bool PadnameUTF8(PADNAME * pn)
```
`pad_new` Create a new padlist, updating the global variables for the currently-compiling padlist to point to the new padlist. The following flags can be OR'ed together:
```
padnew_CLONE this pad is for a cloned CV
padnew_SAVE save old globals on the save stack
padnew_SAVESUB also save extra stuff for start of sub
```
```
PADLIST* pad_new(int flags)
```
`PL_comppad` NOTE: `PL_comppad` is **experimental** and may change or be removed without notice.
During compilation, this points to the array containing the values part of the pad for the currently-compiling code. (At runtime a CV may have many such value arrays; at compile time just one is constructed.) At runtime, this points to the array containing the currently-relevant values for the pad for the currently-executing code.
`PL_comppad_name` NOTE: `PL_comppad_name` is **experimental** and may change or be removed without notice.
During compilation, this points to the array containing the names part of the pad for the currently-compiling code.
`PL_curpad` NOTE: `PL_curpad` is **experimental** and may change or be removed without notice.
Points directly to the body of the ["PL\_comppad"](#PL_comppad) array. (I.e., this is `PadARRAY(PL_comppad)`.)
`SVs_PADMY` `**DEPRECATED!**` It is planned to remove `SVs_PADMY` from a future release of Perl. Do not use it for new code; remove it from existing code.
Described in <perlguts>.
`SVs_PADTMP` Described in <perlguts>.
Password and Group access
--------------------------
`GRPASSWD` This symbol, if defined, indicates to the C program that `struct group` in *grp.h* contains `gr_passwd`.
`HAS_ENDGRENT` This symbol, if defined, indicates that the getgrent routine is available for finalizing sequential access of the group database.
`HAS_ENDGRENT_R` This symbol, if defined, indicates that the `endgrent_r` routine is available to endgrent re-entrantly.
`HAS_ENDPWENT` This symbol, if defined, indicates that the `endpwent` routine is available for finalizing sequential access of the passwd database.
`HAS_ENDPWENT_R` This symbol, if defined, indicates that the `endpwent_r` routine is available to endpwent re-entrantly.
`HAS_GETGRENT` This symbol, if defined, indicates that the `getgrent` routine is available for sequential access of the group database.
`HAS_GETGRENT_R` This symbol, if defined, indicates that the `getgrent_r` routine is available to getgrent re-entrantly.
`HAS_GETPWENT` This symbol, if defined, indicates that the `getpwent` routine is available for sequential access of the passwd database. If this is not available, the older `getpw()` function may be available.
`HAS_GETPWENT_R` This symbol, if defined, indicates that the `getpwent_r` routine is available to getpwent re-entrantly.
`HAS_SETGRENT` This symbol, if defined, indicates that the `setgrent` routine is available for initializing sequential access of the group database.
`HAS_SETGRENT_R` This symbol, if defined, indicates that the `setgrent_r` routine is available to setgrent re-entrantly.
`HAS_SETPWENT` This symbol, if defined, indicates that the `setpwent` routine is available for initializing sequential access of the passwd database.
`HAS_SETPWENT_R` This symbol, if defined, indicates that the `setpwent_r` routine is available to setpwent re-entrantly.
`PWAGE` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_age`.
`PWCHANGE` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_change`.
`PWCLASS` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_class`.
`PWCOMMENT` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_comment`.
`PWEXPIRE` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_expire`.
`PWGECOS` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_gecos`.
`PWPASSWD` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_passwd`.
`PWQUOTA` This symbol, if defined, indicates to the C program that `struct passwd` contains `pw_quota`.
Paths to system commands
-------------------------
`CSH` This symbol, if defined, contains the full pathname of csh.
`LOC_SED` This symbol holds the complete pathname to the sed program.
`SH_PATH` This symbol contains the full pathname to the shell used on this on this system to execute Bourne shell scripts. Usually, this will be */bin/sh*, though it's possible that some systems will have */bin/ksh*, */bin/pdksh*, */bin/ash*, */bin/bash*, or even something such as D:*/bin/sh.exe*.
Prototype information
----------------------
`CRYPT_R_PROTO` This symbol encodes the prototype of `crypt_r`. It is zero if `d_crypt_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_crypt_r` is defined.
`CTERMID_R_PROTO` This symbol encodes the prototype of `ctermid_r`. It is zero if `d_ctermid_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_ctermid_r` is defined.
`DRAND48_R_PROTO` This symbol encodes the prototype of `drand48_r`. It is zero if `d_drand48_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_drand48_r` is defined.
`ENDGRENT_R_PROTO` This symbol encodes the prototype of `endgrent_r`. It is zero if `d_endgrent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endgrent_r` is defined.
`ENDHOSTENT_R_PROTO` This symbol encodes the prototype of `endhostent_r`. It is zero if `d_endhostent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endhostent_r` is defined.
`ENDNETENT_R_PROTO` This symbol encodes the prototype of `endnetent_r`. It is zero if `d_endnetent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endnetent_r` is defined.
`ENDPROTOENT_R_PROTO` This symbol encodes the prototype of `endprotoent_r`. It is zero if `d_endprotoent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endprotoent_r` is defined.
`ENDPWENT_R_PROTO` This symbol encodes the prototype of `endpwent_r`. It is zero if `d_endpwent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endpwent_r` is defined.
`ENDSERVENT_R_PROTO` This symbol encodes the prototype of `endservent_r`. It is zero if `d_endservent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_endservent_r` is defined.
`GDBMNDBM_H_USES_PROTOTYPES` This symbol, if defined, indicates that *gdbm/ndbm.h* uses real `ANSI` C prototypes instead of K&R style function declarations without any parameter information. While `ANSI` C prototypes are supported in C++, K&R style function declarations will yield errors.
`GDBM_NDBM_H_USES_PROTOTYPES` This symbol, if defined, indicates that <gdbm-*ndbm.h*> uses real `ANSI` C prototypes instead of K&R style function declarations without any parameter information. While `ANSI` C prototypes are supported in C++, K&R style function declarations will yield errors.
`GETGRENT_R_PROTO` This symbol encodes the prototype of `getgrent_r`. It is zero if `d_getgrent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getgrent_r` is defined.
`GETGRGID_R_PROTO` This symbol encodes the prototype of `getgrgid_r`. It is zero if `d_getgrgid_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getgrgid_r` is defined.
`GETGRNAM_R_PROTO` This symbol encodes the prototype of `getgrnam_r`. It is zero if `d_getgrnam_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getgrnam_r` is defined.
`GETHOSTBYADDR_R_PROTO` This symbol encodes the prototype of `gethostbyaddr_r`. It is zero if `d_gethostbyaddr_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_gethostbyaddr_r` is defined.
`GETHOSTBYNAME_R_PROTO` This symbol encodes the prototype of `gethostbyname_r`. It is zero if `d_gethostbyname_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_gethostbyname_r` is defined.
`GETHOSTENT_R_PROTO` This symbol encodes the prototype of `gethostent_r`. It is zero if `d_gethostent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_gethostent_r` is defined.
`GETLOGIN_R_PROTO` This symbol encodes the prototype of `getlogin_r`. It is zero if `d_getlogin_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getlogin_r` is defined.
`GETNETBYADDR_R_PROTO` This symbol encodes the prototype of `getnetbyaddr_r`. It is zero if `d_getnetbyaddr_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getnetbyaddr_r` is defined.
`GETNETBYNAME_R_PROTO` This symbol encodes the prototype of `getnetbyname_r`. It is zero if `d_getnetbyname_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getnetbyname_r` is defined.
`GETNETENT_R_PROTO` This symbol encodes the prototype of `getnetent_r`. It is zero if `d_getnetent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getnetent_r` is defined.
`GETPROTOBYNAME_R_PROTO` This symbol encodes the prototype of `getprotobyname_r`. It is zero if `d_getprotobyname_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getprotobyname_r` is defined.
`GETPROTOBYNUMBER_R_PROTO` This symbol encodes the prototype of `getprotobynumber_r`. It is zero if `d_getprotobynumber_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getprotobynumber_r` is defined.
`GETPROTOENT_R_PROTO` This symbol encodes the prototype of `getprotoent_r`. It is zero if `d_getprotoent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getprotoent_r` is defined.
`GETPWENT_R_PROTO` This symbol encodes the prototype of `getpwent_r`. It is zero if `d_getpwent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getpwent_r` is defined.
`GETPWNAM_R_PROTO` This symbol encodes the prototype of `getpwnam_r`. It is zero if `d_getpwnam_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getpwnam_r` is defined.
`GETPWUID_R_PROTO` This symbol encodes the prototype of `getpwuid_r`. It is zero if `d_getpwuid_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getpwuid_r` is defined.
`GETSERVBYNAME_R_PROTO` This symbol encodes the prototype of `getservbyname_r`. It is zero if `d_getservbyname_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getservbyname_r` is defined.
`GETSERVBYPORT_R_PROTO` This symbol encodes the prototype of `getservbyport_r`. It is zero if `d_getservbyport_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getservbyport_r` is defined.
`GETSERVENT_R_PROTO` This symbol encodes the prototype of `getservent_r`. It is zero if `d_getservent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getservent_r` is defined.
`GETSPNAM_R_PROTO` This symbol encodes the prototype of `getspnam_r`. It is zero if `d_getspnam_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_getspnam_r` is defined.
`HAS_DBMINIT_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `dbminit()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern int dbminit(char *);
```
`HAS_DRAND48_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `drand48()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern double drand48(void);
```
`HAS_FLOCK_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `flock()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern int flock(int, int);
```
`HAS_GETHOST_PROTOS` This symbol, if defined, indicates that *netdb.h* includes prototypes for `gethostent()`, `gethostbyname()`, and `gethostbyaddr()`. Otherwise, it is up to the program to guess them. See netdbtype.U (part of metaconfig) for probing for various `Netdb_xxx_t` types.
`HAS_GETNET_PROTOS` This symbol, if defined, indicates that *netdb.h* includes prototypes for `getnetent()`, `getnetbyname()`, and `getnetbyaddr()`. Otherwise, it is up to the program to guess them. See netdbtype.U (part of metaconfig) for probing for various `Netdb_xxx_t` types.
`HAS_GETPROTO_PROTOS` This symbol, if defined, indicates that *netdb.h* includes prototypes for `getprotoent()`, `getprotobyname()`, and `getprotobyaddr()`. Otherwise, it is up to the program to guess them. See netdbtype.U (part of metaconfig) for probing for various `Netdb_xxx_t` types.
`HAS_GETSERV_PROTOS` This symbol, if defined, indicates that *netdb.h* includes prototypes for `getservent()`, `getservbyname()`, and `getservbyaddr()`. Otherwise, it is up to the program to guess them. See netdbtype.U (part of metaconfig) for probing for various `Netdb_xxx_t` types.
`HAS_MODFL_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `modfl()` function. Otherwise, it is up to the program to supply one.
`HAS_SBRK_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `sbrk()` function. Otherwise, it is up to the program to supply one. Good guesses are
```
extern void* sbrk(int);
extern void* sbrk(size_t);
```
`HAS_SETRESGID_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `setresgid()` function. Otherwise, it is up to the program to supply one. Good guesses are
```
extern int setresgid(uid_t ruid, uid_t euid, uid_t suid);
```
`HAS_SETRESUID_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `setresuid()` function. Otherwise, it is up to the program to supply one. Good guesses are
```
extern int setresuid(uid_t ruid, uid_t euid, uid_t suid);
```
`HAS_SHMAT_PROTOTYPE` This symbol, if defined, indicates that the *sys/shm.h* includes a prototype for `shmat()`. Otherwise, it is up to the program to guess one. `Shmat_t` `shmat(int, Shmat_t, int)` is a good guess, but not always right so it should be emitted by the program only when `HAS_SHMAT_PROTOTYPE` is not defined to avoid conflicting defs.
`HAS_SOCKATMARK_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `sockatmark()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern int sockatmark(int);
```
`HAS_SYSCALL_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `syscall()` function. Otherwise, it is up to the program to supply one. Good guesses are
```
extern int syscall(int, ...);
extern int syscall(long, ...);
```
`HAS_TELLDIR_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `telldir()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern long telldir(DIR*);
```
`NDBM_H_USES_PROTOTYPES` This symbol, if defined, indicates that *ndbm.h* uses real `ANSI` C prototypes instead of K&R style function declarations without any parameter information. While `ANSI` C prototypes are supported in C++, K&R style function declarations will yield errors.
`RANDOM_R_PROTO` This symbol encodes the prototype of `random_r`. It is zero if `d_random_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_random_r` is defined.
`READDIR_R_PROTO` This symbol encodes the prototype of `readdir_r`. It is zero if `d_readdir_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_readdir_r` is defined.
`SETGRENT_R_PROTO` This symbol encodes the prototype of `setgrent_r`. It is zero if `d_setgrent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setgrent_r` is defined.
`SETHOSTENT_R_PROTO` This symbol encodes the prototype of `sethostent_r`. It is zero if `d_sethostent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_sethostent_r` is defined.
`SETLOCALE_R_PROTO` This symbol encodes the prototype of `setlocale_r`. It is zero if `d_setlocale_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setlocale_r` is defined.
`SETNETENT_R_PROTO` This symbol encodes the prototype of `setnetent_r`. It is zero if `d_setnetent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setnetent_r` is defined.
`SETPROTOENT_R_PROTO` This symbol encodes the prototype of `setprotoent_r`. It is zero if `d_setprotoent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setprotoent_r` is defined.
`SETPWENT_R_PROTO` This symbol encodes the prototype of `setpwent_r`. It is zero if `d_setpwent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setpwent_r` is defined.
`SETSERVENT_R_PROTO` This symbol encodes the prototype of `setservent_r`. It is zero if `d_setservent_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_setservent_r` is defined.
`SRAND48_R_PROTO` This symbol encodes the prototype of `srand48_r`. It is zero if `d_srand48_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_srand48_r` is defined.
`SRANDOM_R_PROTO` This symbol encodes the prototype of `srandom_r`. It is zero if `d_srandom_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_srandom_r` is defined.
`STRERROR_R_PROTO` This symbol encodes the prototype of `strerror_r`. It is zero if `d_strerror_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_strerror_r` is defined.
`TMPNAM_R_PROTO` This symbol encodes the prototype of `tmpnam_r`. It is zero if `d_tmpnam_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_tmpnam_r` is defined.
`TTYNAME_R_PROTO` This symbol encodes the prototype of `ttyname_r`. It is zero if `d_ttyname_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_ttyname_r` is defined.
REGEXP Functions
-----------------
`pregcomp` Described in <perlreguts>.
```
REGEXP* pregcomp(SV * const pattern, const U32 flags)
```
`pregexec` Described in <perlreguts>.
```
I32 pregexec(REGEXP * const prog, char* stringarg, char* strend,
char* strbeg, SSize_t minend, SV* screamer,
U32 nosave)
```
`re_compile` Compile the regular expression pattern `pattern`, returning a pointer to the compiled object for later matching with the internal regex engine.
This function is typically used by a custom regexp engine `.comp()` function to hand off to the core regexp engine those patterns it doesn't want to handle itself (typically passing through the same flags it was called with). In almost all other cases, a regexp should be compiled by calling ["`pregcomp`"](#pregcomp) to compile using the currently active regexp engine.
If `pattern` is already a `REGEXP`, this function does nothing but return a pointer to the input. Otherwise the PV is extracted and treated like a string representing a pattern. See <perlre>.
The possible flags for `rx_flags` are documented in <perlreapi>. Their names all begin with `RXf_`.
```
REGEXP* re_compile(SV * const pattern, U32 orig_rx_flags)
```
`re_dup_guts` Duplicate a regexp.
This routine is expected to clone a given regexp structure. It is only compiled under USE\_ITHREADS.
After all of the core data stored in struct regexp is duplicated the `regexp_engine.dupe` method is used to copy any private data stored in the \*pprivate pointer. This allows extensions to handle any duplication they need to do.
```
void re_dup_guts(const REGEXP *sstr, REGEXP *dstr,
CLONE_PARAMS* param)
```
`REGEX_LOCALE_CHARSET` Described in <perlreapi>.
`REGEXP` Described in <perlreapi>.
`regexp_engine` When a regexp is compiled, its `engine` field is then set to point at the appropriate structure, so that when it needs to be used Perl can find the right routines to do so.
In order to install a new regexp handler, `$^H{regcomp}` is set to an integer which (when casted appropriately) resolves to one of these structures. When compiling, the `comp` method is executed, and the resulting `regexp` structure's engine field is expected to point back at the same structure.
The pTHX\_ symbol in the definition is a macro used by Perl under threading to provide an extra argument to the routine holding a pointer back to the interpreter that is executing the regexp. So under threading all routines get an extra argument.
`regexp_paren_pair` Described in <perlreapi>.
`regmatch_info` Some basic information about the current match that is created by Perl\_regexec\_flags and then passed to regtry(), regmatch() etc. It is allocated as a local var on the stack, so nothing should be stored in it that needs preserving or clearing up on croak(). For that, see the aux\_info and aux\_info\_eval members of the regmatch\_state union.
`REXEC_COPY_STR` `REXEC_COPY_SKIP_PRE` `REXEC_COPY_SKIP_POST` Described in <perlreapi>.
`RXapif_CLEAR` `RXapif_DELETE` `RXapif_EXISTS` `RXapif_FETCH` `RXapif_FIRSTKEY` `RXapif_NEXTKEY` `RXapif_SCALAR` `RXapif_STORE` `RXapif_ALL` `RXapif_ONE` `RXapif_REGNAME` `RXapif_REGNAMES` `RXapif_REGNAMES_COUNT` Described in <perlreapi>.
`RX_BUFF_IDX_CARET_FULLMATCH` `RX_BUFF_IDX_CARET_POSTMATCH` `RX_BUFF_IDX_CARET_PREMATCH` `RX_BUFF_IDX_FULLMATCH` `RX_BUFF_IDX_POSTMATCH` `RX_BUFF_IDX_PREMATCH` Described in <perlreapi>.
`RXf_PMf_MULTILINE` `RXf_PMf_SINGLELINE` `RXf_PMf_FOLD` `RXf_PMf_EXTENDED` `RXf_PMf_KEEPCOPY` Described in <perlreapi>.
`RXf_SPLIT` `RXf_SKIPWHITE` `RXf_START_ONLY` `RXf_WHITE` `RXf_NULL` `RXf_NO_INPLACE_SUBST` Described in <perlreapi>.
`RX_MATCH_COPIED` Described in <perlreapi>.
```
RX_MATCH_COPIED(const REGEXP * rx)
```
`RX_OFFS` Described in <perlreapi>.
```
RX_OFFS(const REGEXP * rx_sv)
```
`SvRX` Convenience macro to get the REGEXP from a SV. This is approximately equivalent to the following snippet:
```
if (SvMAGICAL(sv))
mg_get(sv);
if (SvROK(sv))
sv = MUTABLE_SV(SvRV(sv));
if (SvTYPE(sv) == SVt_REGEXP)
return (REGEXP*) sv;
```
`NULL` will be returned if a REGEXP\* is not found.
```
REGEXP * SvRX(SV *sv)
```
`SvRXOK` Returns a boolean indicating whether the SV (or the one it references) is a REGEXP.
If you want to do something with the REGEXP\* later use SvRX instead and check for NULL.
```
bool SvRXOK(SV* sv)
```
`SV_SAVED_COPY` Described in <perlreapi>.
Reports and Formats
--------------------
These are used in the simple report generation feature of Perl. See <perlform>.
`IoBOTTOM_GV` Described in <perlguts>.
```
GV * IoBOTTOM_GV(IO *io)
```
`IoBOTTOM_NAME` Described in <perlguts>.
```
char * IoBOTTOM_NAME(IO *io)
```
`IoFMT_GV` Described in <perlguts>.
```
GV * IoFMT_GV(IO *io)
```
`IoFMT_NAME` Described in <perlguts>.
```
char * IoFMT_NAME(IO *io)
```
`IoLINES` Described in <perlguts>.
```
IV IoLINES(IO *io)
```
`IoLINES_LEFT` Described in <perlguts>.
```
IV IoLINES_LEFT(IO *io)
```
`IoPAGE` Described in <perlguts>.
```
IV IoPAGE(IO *io)
```
`IoPAGE_LEN` Described in <perlguts>.
```
IV IoPAGE_LEN(IO *io)
```
`IoTOP_GV` Described in <perlguts>.
```
GV * IoTOP_GV(IO *io)
```
`IoTOP_NAME` Described in <perlguts>.
```
char * IoTOP_NAME(IO *io)
```
Signals
-------
`HAS_SIGINFO_SI_ADDR` This symbol, if defined, indicates that `siginfo_t` has the `si_addr` member
`HAS_SIGINFO_SI_BAND` This symbol, if defined, indicates that `siginfo_t` has the `si_band` member
`HAS_SIGINFO_SI_ERRNO` This symbol, if defined, indicates that `siginfo_t` has the `si_errno` member
`HAS_SIGINFO_SI_PID` This symbol, if defined, indicates that `siginfo_t` has the `si_pid` member
`HAS_SIGINFO_SI_STATUS` This symbol, if defined, indicates that `siginfo_t` has the `si_status` member
`HAS_SIGINFO_SI_UID` This symbol, if defined, indicates that `siginfo_t` has the `si_uid` member
`HAS_SIGINFO_SI_VALUE` This symbol, if defined, indicates that `siginfo_t` has the `si_value` member
`PERL_SIGNALS_UNSAFE_FLAG` If this bit in `PL_signals` is set, the system is uing the pre-Perl 5.8 unsafe signals. See ["PERL\_SIGNALS" in perlrun](perlrun#PERL_SIGNALS) and ["Deferred Signals (Safe Signals)" in perlipc](perlipc#Deferred-Signals-%28Safe-Signals%29).
```
U32 PERL_SIGNALS_UNSAFE_FLAG
```
`rsignal` A wrapper for the C library functions [sigaction(2)](http://man.he.net/man2/sigaction) or [signal(2)](http://man.he.net/man2/signal). Use this instead of those libc functions, as the Perl version gives the safest available implementation, and knows things that interact with the rest of the perl interpreter.
```
Sighandler_t rsignal(int i, Sighandler_t t)
```
`rsignal_state` Returns a the current signal handler for signal `signo`. See ["`rsignal`"](#rsignal).
```
Sighandler_t rsignal_state(int i)
```
`Sigjmp_buf` This is the buffer type to be used with Sigsetjmp and Siglongjmp.
`Siglongjmp` This macro is used in the same way as `siglongjmp()`, but will invoke traditional `longjmp()` if siglongjmp isn't available. See `["HAS\_SIGSETJMP"](#HAS_SIGSETJMP)`.
```
void Siglongjmp(jmp_buf env, int val)
```
`SIG_NAME` This symbol contains a list of signal names in order of signal number. This is intended to be used as a static array initialization, like this:
```
char *sig_name[] = { SIG_NAME };
```
The signals in the list are separated with commas, and each signal is surrounded by double quotes. There is no leading `SIG` in the signal name, i.e. `SIGQUIT` is known as "`QUIT`". Gaps in the signal numbers (up to `NSIG`) are filled in with `NUMnn`, etc., where nn is the actual signal number (e.g. `NUM37`). The signal number for `sig_name[i]` is stored in `sig_num[i]`. The last element is 0 to terminate the list with a `NULL`. This corresponds to the 0 at the end of the `sig_name_init` list. Note that this variable is initialized from the `sig_name_init`, not from `sig_name` (which is unused).
`SIG_NUM` This symbol contains a list of signal numbers, in the same order as the `SIG_NAME` list. It is suitable for static array initialization, as in:
```
int sig_num[] = { SIG_NUM };
```
The signals in the list are separated with commas, and the indices within that list and the `SIG_NAME` list match, so it's easy to compute the signal name from a number or vice versa at the price of a small dynamic linear lookup. Duplicates are allowed, but are moved to the end of the list. The signal number corresponding to `sig_name[i]` is `sig_number[i]`. if (i < `NSIG`) then `sig_number[i]` == i. The last element is 0, corresponding to the 0 at the end of the `sig_name_init` list. Note that this variable is initialized from the `sig_num_init`, not from `sig_num` (which is unused).
`Sigsetjmp` This macro is used in the same way as `sigsetjmp()`, but will invoke traditional `setjmp()` if sigsetjmp isn't available. See `["HAS\_SIGSETJMP"](#HAS_SIGSETJMP)`.
```
int Sigsetjmp(jmp_buf env, int savesigs)
```
`SIG_SIZE` This variable contains the number of elements of the `SIG_NAME` and `SIG_NUM` arrays, excluding the final `NULL` entry.
`whichsig` `whichsig_pv` `whichsig_pvn`
`whichsig_sv` These all convert a signal name into its corresponding signal number; returning -1 if no corresponding number was found.
They differ only in the source of the signal name:
`whichsig_pv` takes the name from the `NUL`-terminated string starting at `sig`.
`whichsig` is merely a different spelling, a synonym, of `whichsig_pv`.
`whichsig_pvn` takes the name from the string starting at `sig`, with length `len` bytes.
`whichsig_sv` takes the name from the PV stored in the SV `sigsv`.
```
I32 whichsig (const char* sig)
I32 whichsig_pv (const char* sig)
I32 whichsig_pvn(const char* sig, STRLEN len)
I32 whichsig_sv (SV* sigsv)
```
Site configuration
-------------------
These variables give details as to where various libraries, installation destinations, *etc.*, go, as well as what various installation options were selected
`ARCHLIB` This variable, if defined, holds the name of the directory in which the user wants to put architecture-dependent public library files for perl5. It is most often a local directory such as */usr/local/lib*. Programs using this variable must be prepared to deal with filename expansion. If `ARCHLIB` is the same as `PRIVLIB`, it is not defined, since presumably the program already searches `PRIVLIB`.
`ARCHLIB_EXP` This symbol contains the ~name expanded version of `ARCHLIB`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`ARCHNAME` This symbol holds a string representing the architecture name. It may be used to construct an architecture-dependant pathname where library files may be held under a private library, for instance.
`BIN` This symbol holds the path of the bin directory where the package will be installed. Program must be prepared to deal with ~name substitution.
`BIN_EXP` This symbol is the filename expanded version of the `BIN` symbol, for programs that do not want to deal with that at run-time.
`INSTALL_USR_BIN_PERL` This symbol, if defined, indicates that Perl is to be installed also as */usr/bin/perl*.
`MULTIARCH` This symbol, if defined, signifies that the build process will produce some binary files that are going to be used in a cross-platform environment. This is the case for example with the NeXT "fat" binaries that contain executables for several `CPUs`.
`PERL_INC_VERSION_LIST` This variable specifies the list of subdirectories in over which *perl.c*:`incpush()` and *lib/lib.pm* will automatically search when adding directories to @`INC`, in a format suitable for a C initialization string. See the `inc_version_list` entry in Porting/Glossary for more details.
`PERL_OTHERLIBDIRS` This variable contains a colon-separated set of paths for the perl binary to search for additional library files or modules. These directories will be tacked to the end of @`INC`. Perl will automatically search below each path for version- and architecture-specific directories. See `["PERL\_INC\_VERSION\_LIST"](#PERL_INC_VERSION_LIST)` for more details.
`PERL_RELOCATABLE_INC` This symbol, if defined, indicates that we'd like to relocate entries in @`INC` at run time based on the location of the perl binary.
`PERL_TARGETARCH` This symbol, if defined, indicates the target architecture Perl has been cross-compiled to. Undefined if not a cross-compile.
`PERL_USE_DEVEL` This symbol, if defined, indicates that Perl was configured with `-Dusedevel`, to enable development features. This should not be done for production builds.
`PERL_VENDORARCH` If defined, this symbol contains the name of a private library. The library is private in the sense that it needn't be in anyone's execution path, but it should be accessible by the world. It may have a ~ on the front. The standard distribution will put nothing in this directory. Vendors who distribute perl may wish to place their own architecture-dependent modules and extensions in this directory with
```
MakeMaker Makefile.PL INSTALLDIRS=vendor
```
or equivalent. See `[INSTALL](install)` for details.
`PERL_VENDORARCH_EXP` This symbol contains the ~name expanded version of `PERL_VENDORARCH`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`PERL_VENDORLIB_EXP` This symbol contains the ~name expanded version of `VENDORLIB`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`PERL_VENDORLIB_STEM` This define is `PERL_VENDORLIB_EXP` with any trailing version-specific component removed. The elements in `inc_version_list` (`inc_version_list`.U (part of metaconfig)) can be tacked onto this variable to generate a list of directories to search.
`PRIVLIB` This symbol contains the name of the private library for this package. The library is private in the sense that it needn't be in anyone's execution path, but it should be accessible by the world. The program should be prepared to do ~ expansion.
`PRIVLIB_EXP` This symbol contains the ~name expanded version of `PRIVLIB`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`SITEARCH` This symbol contains the name of the private library for this package. The library is private in the sense that it needn't be in anyone's execution path, but it should be accessible by the world. The program should be prepared to do ~ expansion. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local architecture-dependent modules in this directory with
```
MakeMaker Makefile.PL
```
or equivalent. See `[INSTALL](install)` for details.
`SITEARCH_EXP` This symbol contains the ~name expanded version of `SITEARCH`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`SITELIB` This symbol contains the name of the private library for this package. The library is private in the sense that it needn't be in anyone's execution path, but it should be accessible by the world. The program should be prepared to do ~ expansion. The standard distribution will put nothing in this directory. After perl has been installed, users may install their own local architecture-independent modules in this directory with
```
MakeMaker Makefile.PL
```
or equivalent. See `[INSTALL](install)` for details.
`SITELIB_EXP` This symbol contains the ~name expanded version of `SITELIB`, to be used in programs that are not prepared to deal with ~ expansion at run-time.
`SITELIB_STEM` This define is `SITELIB_EXP` with any trailing version-specific component removed. The elements in `inc_version_list` (`inc_version_list`.U (part of metaconfig)) can be tacked onto this variable to generate a list of directories to search.
`STARTPERL` This variable contains the string to put in front of a perl script to make sure (one hopes) that it runs with perl and not some shell.
`USE_64_BIT_ALL` This symbol, if defined, indicates that 64-bit integers should be used when available. If not defined, the native integers will be used (be they 32 or 64 bits). The maximal possible 64-bitness is employed: LP64 or `ILP64`, meaning that you will be able to use more than 2 gigabytes of memory. This mode is even more binary incompatible than `USE_64_BIT_INT`. You may not be able to run the resulting executable in a 32-bit `CPU` at all or you may need at least to reboot your OS to 64-bit mode.
`USE_64_BIT_INT` This symbol, if defined, indicates that 64-bit integers should be used when available. If not defined, the native integers will be employed (be they 32 or 64 bits). The minimal possible 64-bitness is used, just enough to get 64-bit integers into Perl. This may mean using for example "long longs", while your memory may still be limited to 2 gigabytes.
`USE_BSD_GETPGRP` This symbol, if defined, indicates that getpgrp needs one arguments whereas `USG` one needs none.
`USE_BSD_SETPGRP` This symbol, if defined, indicates that setpgrp needs two arguments whereas `USG` one needs none. See also `["HAS\_SETPGID"](#HAS_SETPGID)` for a `POSIX` interface.
`USE_CPLUSPLUS` This symbol, if defined, indicates that a C++ compiler was used to compiled Perl and will be used to compile extensions.
`USE_CROSS_COMPILE` This symbol, if defined, indicates that Perl is being cross-compiled.
`USE_C_BACKTRACE` This symbol, if defined, indicates that Perl should be built with support for backtrace.
`USE_DTRACE` This symbol, if defined, indicates that Perl should be built with support for DTrace.
`USE_DYNAMIC_LOADING` This symbol, if defined, indicates that dynamic loading of some sort is available.
`USE_FAST_STDIO` This symbol, if defined, indicates that Perl should be built to use 'fast stdio'. Defaults to define in Perls 5.8 and earlier, to undef later.
`USE_ITHREADS` This symbol, if defined, indicates that Perl should be built to use the interpreter-based threading implementation.
`USE_KERN_PROC_PATHNAME` This symbol, if defined, indicates that we can use sysctl with `KERN_PROC_PATHNAME` to get a full path for the executable, and hence convert $^X to an absolute path.
`USE_LARGE_FILES` This symbol, if defined, indicates that large file support should be used when available.
`USE_LONG_DOUBLE` This symbol, if defined, indicates that long doubles should be used when available.
`USE_MORE_BITS` This symbol, if defined, indicates that 64-bit interfaces and long doubles should be used when available.
`USE_NSGETEXECUTABLEPATH` This symbol, if defined, indicates that we can use `_NSGetExecutablePath` and realpath to get a full path for the executable, and hence convert $^X to an absolute path.
`USE_PERLIO` This symbol, if defined, indicates that the PerlIO abstraction should be used throughout. If not defined, stdio should be used in a fully backward compatible manner.
`USE_QUADMATH` This symbol, if defined, indicates that the quadmath library should be used when available.
`USE_REENTRANT_API` This symbol, if defined, indicates that Perl should try to use the various `_r` versions of library functions. This is extremely experimental.
`USE_SEMCTL_SEMID_DS` This symbol, if defined, indicates that `struct semid_ds` \* is used for semctl `IPC_STAT`.
`USE_SEMCTL_SEMUN` This symbol, if defined, indicates that `union semun` is used for semctl `IPC_STAT`.
`USE_SITECUSTOMIZE` This symbol, if defined, indicates that sitecustomize should be used.
`USE_SOCKS` This symbol, if defined, indicates that Perl should be built to use socks.
`USE_STAT_BLOCKS` This symbol is defined if this system has a stat structure declaring `st_blksize` and `st_blocks`.
`USE_STDIO_BASE` This symbol is defined if the `_base` field (or similar) of the stdio `FILE` structure can be used to access the stdio buffer for a file handle. If this is defined, then the `FILE_base(fp)` macro will also be defined and should be used to access this field. Also, the `FILE_bufsiz(fp)` macro will be defined and should be used to determine the number of bytes in the buffer. `USE_STDIO_BASE` will never be defined unless `USE_STDIO_PTR` is.
`USE_STDIO_PTR` This symbol is defined if the `_ptr` and `_cnt` fields (or similar) of the stdio `FILE` structure can be used to access the stdio buffer for a file handle. If this is defined, then the `FILE_ptr(fp)` and `FILE_cnt(fp)` macros will also be defined and should be used to access these fields.
`USE_STRICT_BY_DEFAULT` This symbol, if defined, enables additional defaults. At this time it only enables implicit strict by default.
`USE_THREADS` This symbol, if defined, indicates that Perl should be built to use threads. At present, it is a synonym for and `USE_ITHREADS`, but eventually the source ought to be changed to use this to mean `_any_` threading implementation.
Sockets configuration values
-----------------------------
`HAS_SOCKADDR_IN6` This symbol, if defined, indicates the availability of `struct sockaddr_in6`;
`HAS_SOCKADDR_SA_LEN` This symbol, if defined, indicates that the `struct sockaddr` structure has a member called `sa_len`, indicating the length of the structure.
`HAS_SOCKADDR_STORAGE` This symbol, if defined, indicates the availability of `struct sockaddr_storage`;
`HAS_SOCKATMARK` This symbol, if defined, indicates that the `sockatmark` routine is available to test whether a socket is at the out-of-band mark.
`HAS_SOCKET` This symbol, if defined, indicates that the `BSD` `socket` interface is supported.
`HAS_SOCKETPAIR` This symbol, if defined, indicates that the `BSD` `socketpair()` call is supported.
`HAS_SOCKS5_INIT` This symbol, if defined, indicates that the `socks5_init` routine is available to initialize `SOCKS` 5.
`I_SOCKS` This symbol, if defined, indicates that *socks.h* exists and should be included.
```
#ifdef I_SOCKS
#include <socks.h>
#endif
```
`I_SYS_SOCKIO` This symbol, if defined, indicates the *sys/sockio.h* should be included to get socket ioctl options, like `SIOCATMARK`.
```
#ifdef I_SYS_SOCKIO
#include <sys_sockio.h>
#endif
```
Source Filters
---------------
`filter_add` Described in <perlfilter>.
```
SV* filter_add(filter_t funcp, SV* datasv)
```
`filter_del` Delete most recently added instance of the filter function argument
```
void filter_del(filter_t funcp)
```
`filter_read` Described in <perlfilter>.
```
I32 filter_read(int idx, SV *buf_sv, int maxlen)
```
`scan_vstring` Returns a pointer to the next character after the parsed vstring, as well as updating the passed in sv.
Function must be called like
```
sv = sv_2mortal(newSV(5));
s = scan_vstring(s,e,sv);
```
where s and e are the start and end of the string. The sv should already be large enough to store the vstring passed in, for performance reasons.
This function may croak if fatal warnings are enabled in the calling scope, hence the sv\_2mortal in the example (to prevent a leak). Make sure to do SvREFCNT\_inc afterwards if you use sv\_2mortal.
```
char* scan_vstring(const char *s, const char *const e, SV *sv)
```
Stack Manipulation Macros
--------------------------
`dMARK` Declare a stack marker variable, `mark`, for the XSUB. See `["MARK"](#MARK)` and `["dORIGMARK"](#dORIGMARK)`.
```
dMARK;
```
`dORIGMARK` Saves the original stack mark for the XSUB. See `["ORIGMARK"](#ORIGMARK)`.
```
dORIGMARK;
```
`dSP` Declares a local copy of perl's stack pointer for the XSUB, available via the `SP` macro. See `["SP"](#SP)`.
```
dSP;
```
`dTARGET` Declare that this function uses `TARG`
```
dTARGET;
```
`EXTEND` Used to extend the argument stack for an XSUB's return values. Once used, guarantees that there is room for at least `nitems` to be pushed onto the stack.
```
void EXTEND(SP, SSize_t nitems)
```
`MARK` Stack marker variable for the XSUB. See `["dMARK"](#dMARK)`.
`mPUSHi` Push an integer onto the stack. The stack must have room for this element. Does not use `TARG`. See also `["PUSHi"](#PUSHi)`, `["mXPUSHi"](#mXPUSHi)` and `["XPUSHi"](#XPUSHi)`.
```
void mPUSHi(IV iv)
```
`mPUSHn` Push a double onto the stack. The stack must have room for this element. Does not use `TARG`. See also `["PUSHn"](#PUSHn)`, `["mXPUSHn"](#mXPUSHn)` and `["XPUSHn"](#XPUSHn)`.
```
void mPUSHn(NV nv)
```
`mPUSHp` Push a string onto the stack. The stack must have room for this element. The `len` indicates the length of the string. Does not use `TARG`. See also `["PUSHp"](#PUSHp)`, `["mXPUSHp"](#mXPUSHp)` and `["XPUSHp"](#XPUSHp)`.
```
void mPUSHp(char* str, STRLEN len)
```
`mPUSHs` Push an SV onto the stack and mortalizes the SV. The stack must have room for this element. Does not use `TARG`. See also `["PUSHs"](#PUSHs)` and `["mXPUSHs"](#mXPUSHs)`.
```
void mPUSHs(SV* sv)
```
`mPUSHu` Push an unsigned integer onto the stack. The stack must have room for this element. Does not use `TARG`. See also `["PUSHu"](#PUSHu)`, `["mXPUSHu"](#mXPUSHu)` and `["XPUSHu"](#XPUSHu)`.
```
void mPUSHu(UV uv)
```
`mXPUSHi` Push an integer onto the stack, extending the stack if necessary. Does not use `TARG`. See also `["XPUSHi"](#XPUSHi)`, `["mPUSHi"](#mPUSHi)` and `["PUSHi"](#PUSHi)`.
```
void mXPUSHi(IV iv)
```
`mXPUSHn` Push a double onto the stack, extending the stack if necessary. Does not use `TARG`. See also `["XPUSHn"](#XPUSHn)`, `["mPUSHn"](#mPUSHn)` and `["PUSHn"](#PUSHn)`.
```
void mXPUSHn(NV nv)
```
`mXPUSHp` Push a string onto the stack, extending the stack if necessary. The `len` indicates the length of the string. Does not use `TARG`. See also `["XPUSHp"](#XPUSHp)`, `mPUSHp` and `PUSHp`.
```
void mXPUSHp(char* str, STRLEN len)
```
`mXPUSHs` Push an SV onto the stack, extending the stack if necessary and mortalizes the SV. Does not use `TARG`. See also `["XPUSHs"](#XPUSHs)` and `["mPUSHs"](#mPUSHs)`.
```
void mXPUSHs(SV* sv)
```
`mXPUSHu` Push an unsigned integer onto the stack, extending the stack if necessary. Does not use `TARG`. See also `["XPUSHu"](#XPUSHu)`, `["mPUSHu"](#mPUSHu)` and `["PUSHu"](#PUSHu)`.
```
void mXPUSHu(UV uv)
```
`newXSproto` Used by `xsubpp` to hook up XSUBs as Perl subs. Adds Perl prototypes to the subs.
`ORIGMARK` The original stack mark for the XSUB. See `["dORIGMARK"](#dORIGMARK)`.
`PL_markstack` Described in <perlguts>.
`PL_markstack_ptr` Described in <perlguts>.
`PL_savestack` Described in <perlguts>.
`PL_savestack_ix` Described in <perlguts>.
`PL_scopestack` Described in <perlguts>.
`PL_scopestack_ix` Described in <perlguts>.
`PL_scopestack_name` Described in <perlguts>.
`PL_stack_base` Described in <perlguts>.
`PL_stack_sp` Described in <perlguts>.
`PL_tmps_floor` Described in <perlguts>.
`PL_tmps_ix` Described in <perlguts>.
`PL_tmps_stack` Described in <perlguts>.
`POPi` Pops an integer off the stack.
```
IV POPi
```
`POPl` Pops a long off the stack.
```
long POPl
```
`POPn` Pops a double off the stack.
```
NV POPn
```
`POPp` Pops a string off the stack.
```
char* POPp
```
`POPpbytex` Pops a string off the stack which must consist of bytes i.e. characters < 256.
```
char* POPpbytex
```
`POPpx` Pops a string off the stack. Identical to POPp. There are two names for historical reasons.
```
char* POPpx
```
`POPs` Pops an SV off the stack.
```
SV* POPs
```
`POPu` Pops an unsigned integer off the stack.
```
UV POPu
```
`POPul` Pops an unsigned long off the stack.
```
long POPul
```
`PUSHi` Push an integer onto the stack. The stack must have room for this element. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mPUSHi"](#mPUSHi)` instead. See also `["XPUSHi"](#XPUSHi)` and `["mXPUSHi"](#mXPUSHi)`.
```
void PUSHi(IV iv)
```
`PUSHMARK` Opening bracket for arguments on a callback. See `["PUTBACK"](#PUTBACK)` and <perlcall>.
```
void PUSHMARK(SP)
```
`PUSHmortal` Push a new mortal SV onto the stack. The stack must have room for this element. Does not use `TARG`. See also `["PUSHs"](#PUSHs)`, `["XPUSHmortal"](#XPUSHmortal)` and `["XPUSHs"](#XPUSHs)`.
```
void PUSHmortal
```
`PUSHn` Push a double onto the stack. The stack must have room for this element. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mPUSHn"](#mPUSHn)` instead. See also `["XPUSHn"](#XPUSHn)` and `["mXPUSHn"](#mXPUSHn)`.
```
void PUSHn(NV nv)
```
`PUSHp` Push a string onto the stack. The stack must have room for this element. The `len` indicates the length of the string. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mPUSHp"](#mPUSHp)` instead. See also `["XPUSHp"](#XPUSHp)` and `["mXPUSHp"](#mXPUSHp)`.
```
void PUSHp(char* str, STRLEN len)
```
`PUSHs` Push an SV onto the stack. The stack must have room for this element. Does not handle 'set' magic. Does not use `TARG`. See also `["PUSHmortal"](#PUSHmortal)`, `["XPUSHs"](#XPUSHs)`, and `["XPUSHmortal"](#XPUSHmortal)`.
```
void PUSHs(SV* sv)
```
`PUSHu` Push an unsigned integer onto the stack. The stack must have room for this element. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mPUSHu"](#mPUSHu)` instead. See also `["XPUSHu"](#XPUSHu)` and `["mXPUSHu"](#mXPUSHu)`.
```
void PUSHu(UV uv)
```
`PUTBACK` Closing bracket for XSUB arguments. This is usually handled by `xsubpp`. See `["PUSHMARK"](#PUSHMARK)` and <perlcall> for other uses.
```
PUTBACK;
```
`SAVEt_INT` Described in <perlguts>.
`SP` Stack pointer. This is usually handled by `xsubpp`. See `["dSP"](#dSP)` and `SPAGAIN`.
`SPAGAIN` Refetch the stack pointer. Used after a callback. See <perlcall>.
```
SPAGAIN;
```
`SSNEW` `SSNEWa` `SSNEWt`
`SSNEWat` These temporarily allocates data on the savestack, returning an I32 index into the savestack, because a pointer would get broken if the savestack is moved on reallocation. Use ["`SSPTR`"](#SSPTR) to convert the returned index into a pointer.
The forms differ in that plain `SSNEW` allocates `size` bytes; `SSNEWt` and `SSNEWat` allocate `size` objects, each of which is type `type`; and <SSNEWa> and `SSNEWat` make sure to align the new data to an `align` boundary. The most useful value for the alignment is likely to be ["`MEM_ALIGNBYTES`"](#MEM_ALIGNBYTES). The alignment will be preserved through savestack reallocation **only** if realloc returns data aligned to a size divisible by "align"!
```
I32 SSNEW (Size_t size)
I32 SSNEWa (Size_t_size, Size_t align)
I32 SSNEWt (Size_t size, type)
I32 SSNEWat(Size_t_size, type, Size_t align)
```
`SSPTR`
`SSPTRt` These convert the `index` returned by L/<`SSNEW`> and kin into actual pointers.
The difference is that `SSPTR` casts the result to `type`, and `SSPTRt` casts it to a pointer of that `type`.
```
type SSPTR (I32 index, type)
type * SSPTRt(I32 index, type)
```
`TARG` `TARG` is short for "target". It is an entry in the pad that an OPs `op_targ` refers to. It is scratchpad space, often used as a return value for the OP, but some use it for other purposes.
```
TARG;
```
`TOPs` Described in <perlguts>.
`XPUSHi` Push an integer onto the stack, extending the stack if necessary. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mXPUSHi"](#mXPUSHi)` instead. See also `["PUSHi"](#PUSHi)` and `["mPUSHi"](#mPUSHi)`.
```
void XPUSHi(IV iv)
```
`XPUSHmortal` Push a new mortal SV onto the stack, extending the stack if necessary. Does not use `TARG`. See also `["XPUSHs"](#XPUSHs)`, `["PUSHmortal"](#PUSHmortal)` and `["PUSHs"](#PUSHs)`.
```
void XPUSHmortal
```
`XPUSHn` Push a double onto the stack, extending the stack if necessary. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mXPUSHn"](#mXPUSHn)` instead. See also `["PUSHn"](#PUSHn)` and `["mPUSHn"](#mPUSHn)`.
```
void XPUSHn(NV nv)
```
`XPUSHp` Push a string onto the stack, extending the stack if necessary. The `len` indicates the length of the string. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mXPUSHp"](#mXPUSHp)` instead. See also `["PUSHp"](#PUSHp)` and `["mPUSHp"](#mPUSHp)`.
```
void XPUSHp(char* str, STRLEN len)
```
`XPUSHs` Push an SV onto the stack, extending the stack if necessary. Does not handle 'set' magic. Does not use `TARG`. See also `["XPUSHmortal"](#XPUSHmortal)`, `PUSHs` and `PUSHmortal`.
```
void XPUSHs(SV* sv)
```
`XPUSHu` Push an unsigned integer onto the stack, extending the stack if necessary. Handles 'set' magic. Uses `TARG`, so `dTARGET` or `dXSTARG` should be called to declare it. Do not call multiple `TARG`-oriented macros to return lists from XSUB's - see `["mXPUSHu"](#mXPUSHu)` instead. See also `["PUSHu"](#PUSHu)` and `["mPUSHu"](#mPUSHu)`.
```
void XPUSHu(UV uv)
```
`XS_APIVERSION_BOOTCHECK` Macro to verify that the perl api version an XS module has been compiled against matches the api version of the perl interpreter it's being loaded into.
```
XS_APIVERSION_BOOTCHECK;
```
`XSRETURN` Return from XSUB, indicating number of items on the stack. This is usually handled by `xsubpp`.
```
void XSRETURN(int nitems)
```
`XSRETURN_EMPTY` Return an empty list from an XSUB immediately.
```
XSRETURN_EMPTY;
```
`XSRETURN_IV` Return an integer from an XSUB immediately. Uses `XST_mIV`.
```
void XSRETURN_IV(IV iv)
```
`XSRETURN_NO` Return `&PL_sv_no` from an XSUB immediately. Uses `XST_mNO`.
```
XSRETURN_NO;
```
`XSRETURN_NV` Return a double from an XSUB immediately. Uses `XST_mNV`.
```
void XSRETURN_NV(NV nv)
```
`XSRETURN_PV` Return a copy of a string from an XSUB immediately. Uses `XST_mPV`.
```
void XSRETURN_PV(char* str)
```
`XSRETURN_UNDEF` Return `&PL_sv_undef` from an XSUB immediately. Uses `XST_mUNDEF`.
```
XSRETURN_UNDEF;
```
`XSRETURN_UV` Return an integer from an XSUB immediately. Uses `XST_mUV`.
```
void XSRETURN_UV(IV uv)
```
`XSRETURN_YES` Return `&PL_sv_yes` from an XSUB immediately. Uses `XST_mYES`.
```
XSRETURN_YES;
```
`XST_mIV` Place an integer into the specified position `pos` on the stack. The value is stored in a new mortal SV.
```
void XST_mIV(int pos, IV iv)
```
`XST_mNO` Place `&PL_sv_no` into the specified position `pos` on the stack.
```
void XST_mNO(int pos)
```
`XST_mNV` Place a double into the specified position `pos` on the stack. The value is stored in a new mortal SV.
```
void XST_mNV(int pos, NV nv)
```
`XST_mPV` Place a copy of a string into the specified position `pos` on the stack. The value is stored in a new mortal SV.
```
void XST_mPV(int pos, char* str)
```
`XST_mUNDEF` Place `&PL_sv_undef` into the specified position `pos` on the stack.
```
void XST_mUNDEF(int pos)
```
`XST_mUV` Place an unsigned integer into the specified position `pos` on the stack. The value is stored in a new mortal SV.
```
void XST_mUV(int pos, UV uv)
```
`XST_mYES` Place `&PL_sv_yes` into the specified position `pos` on the stack.
```
void XST_mYES(int pos)
```
`XS_VERSION` The version identifier for an XS module. This is usually handled automatically by `ExtUtils::MakeMaker`. See `["XS\_VERSION\_BOOTCHECK"](#XS_VERSION_BOOTCHECK)`.
`XS_VERSION_BOOTCHECK` Macro to verify that a PM module's `$VERSION` variable matches the XS module's `XS_VERSION` variable. This is usually handled automatically by `xsubpp`. See ["The VERSIONCHECK: Keyword" in perlxs](perlxs#The-VERSIONCHECK%3A-Keyword).
```
XS_VERSION_BOOTCHECK;
```
String Handling
----------------
See also `["Unicode Support"](#Unicode-Support)`.
`CAT2` This macro concatenates 2 tokens together.
```
token CAT2(token x, token y)
```
`Copy`
`CopyD` The XSUB-writer's interface to the C `memcpy` function. The `src` is the source, `dest` is the destination, `nitems` is the number of items, and `type` is the type. May fail on overlapping copies. See also `["Move"](#Move)`.
`CopyD` is like `Copy` but returns `dest`. Useful for encouraging compilers to tail-call optimise.
```
void Copy (void* src, void* dest, int nitems, type)
void * CopyD(void* src, void* dest, int nitems, type)
```
`delimcpy` Copy a source buffer to a destination buffer, stopping at (but not including) the first occurrence in the source of an unescaped (defined below) delimiter byte, `delim`. The source is the bytes between `from` and `from_end` - 1. Similarly, the dest is `to` up to `to_end`.
The number of bytes copied is written to `*retlen`.
Returns the position of the first uncopied `delim` in the `from` buffer, but if there is no such occurrence before `from_end`, then `from_end` is returned, and the entire buffer `from` .. `from_end` - 1 is copied.
If there is room in the destination available after the copy, an extra terminating safety `NUL` byte is appended (not included in the returned length).
The error case is if the destination buffer is not large enough to accommodate everything that should be copied. In this situation, a value larger than `to_end` - `to` is written to `*retlen`, and as much of the source as fits will be written to the destination. Not having room for the safety `NUL` is not considered an error.
In the following examples, let `x` be the delimiter, and `0` represent a `NUL` byte (**NOT** the digit `0`). Then we would have
```
Source Destination
abcxdef abc0
```
provided the destination buffer is at least 4 bytes long.
An escaped delimiter is one which is immediately preceded by a single backslash. Escaped delimiters are copied, and the copy continues past the delimiter; the backslash is not copied:
```
Source Destination
abc\xdef abcxdef0
```
(provided the destination buffer is at least 8 bytes long).
It's actually somewhat more complicated than that. A sequence of any odd number of backslashes escapes the following delimiter, and the copy continues with exactly one of the backslashes stripped.
```
Source Destination
abc\xdef abcxdef0
abc\\\xdef abc\\xdef0
abc\\\\\xdef abc\\\\xdef0
```
(as always, if the destination is large enough)
An even number of preceding backslashes does not escape the delimiter, so that the copy stops just before it, and includes all the backslashes (no stripping; zero is considered even):
```
Source Destination
abcxdef abc0
abc\\xdef abc\\0
abc\\\\xdef abc\\\\0
```
```
char* delimcpy(char* to, const char* to_end, const char* from,
const char* from_end, const int delim,
I32* retlen)
```
`do_join` This performs a Perl [`join`](perlfunc#join), placing the joined output into `sv`.
The elements to join are in SVs, stored in a C array of pointers to SVs, from `**mark` to `**sp - 1`. Hence `*mark` is a reference to the first SV. Each SV will be coerced into a PV if not one already.
`delim` contains the string (or coerced into a string) that is to separate each of the joined elements.
If any component is in UTF-8, the result will be as well, and all non-UTF-8 components will be converted to UTF-8 as necessary.
Magic and tainting are handled.
```
void do_join(SV *sv, SV *delim, SV **mark, SV **sp)
```
`do_sprintf` This performs a Perl [`sprintf`](perlfunc#sprintf) placing the string output into `sv`.
The elements to format are in SVs, stored in a C array of pointers to SVs of length `len`> and beginning at `**sarg`. The element referenced by `*sarg` is the format.
Magic and tainting are handled.
```
void do_sprintf(SV* sv, SSize_t len, SV** sarg)
```
`fbm_compile` Analyzes the string in order to make fast searches on it using `fbm_instr()` -- the Boyer-Moore algorithm.
```
void fbm_compile(SV* sv, U32 flags)
```
`fbm_instr` Returns the location of the SV in the string delimited by `big` and `bigend` (`bigend`) is the char following the last char). It returns `NULL` if the string can't be found. The `sv` does not have to be `fbm_compiled`, but the search will not be as fast then.
```
char* fbm_instr(unsigned char* big, unsigned char* bigend,
SV* littlestr, U32 flags)
```
`foldEQ` Returns true if the leading `len` bytes of the strings `s1` and `s2` are the same case-insensitively; false otherwise. Uppercase and lowercase ASCII range bytes match themselves and their opposite case counterparts. Non-cased and non-ASCII range bytes match only themselves.
```
I32 foldEQ(const char* a, const char* b, I32 len)
```
`ibcmp` This is a synonym for `(! foldEQ())`
```
I32 ibcmp(const char* a, const char* b, I32 len)
```
`ibcmp_locale` This is a synonym for `(! foldEQ_locale())`
```
I32 ibcmp_locale(const char* a, const char* b, I32 len)
```
`ibcmp_utf8` This is a synonym for `(! foldEQ_utf8())`
```
I32 ibcmp_utf8(const char *s1, char **pe1, UV l1, bool u1,
const char *s2, char **pe2, UV l2, bool u2)
```
`instr` Same as [strstr(3)](http://man.he.net/man3/strstr), which finds and returns a pointer to the first occurrence of the NUL-terminated substring `little` in the NUL-terminated string `big`, returning NULL if not found. The terminating NUL bytes are not compared.
```
char* instr(const char* big, const char* little)
```
`memCHRs` Returns the position of the first occurence of the byte `c` in the literal string `"list"`, or NULL if `c` doesn't appear in `"list"`. All bytes are treated as unsigned char. Thus this macro can be used to determine if `c` is in a set of particular characters. Unlike [strchr(3)](http://man.he.net/man3/strchr), it works even if `c` is `NUL` (and the set doesn't include `NUL`).
```
bool memCHRs("list", char c)
```
`memEQ` Test two buffers (which may contain embedded `NUL` characters, to see if they are equal. The `len` parameter indicates the number of bytes to compare. Returns true or false. It is undefined behavior if either of the buffers doesn't contain at least `len` bytes.
```
bool memEQ(char* s1, char* s2, STRLEN len)
```
`memEQs` Like ["memEQ"](#memEQ), but the second string is a literal enclosed in double quotes, `l1` gives the number of bytes in `s1`. Returns true or false.
```
bool memEQs(char* s1, STRLEN l1, "s2")
```
`memNE` Test two buffers (which may contain embedded `NUL` characters, to see if they are not equal. The `len` parameter indicates the number of bytes to compare. Returns true or false. It is undefined behavior if either of the buffers doesn't contain at least `len` bytes.
```
bool memNE(char* s1, char* s2, STRLEN len)
```
`memNEs` Like ["memNE"](#memNE), but the second string is a literal enclosed in double quotes, `l1` gives the number of bytes in `s1`. Returns true or false.
```
bool memNEs(char* s1, STRLEN l1, "s2")
```
`Move`
`MoveD` The XSUB-writer's interface to the C `memmove` function. The `src` is the source, `dest` is the destination, `nitems` is the number of items, and `type` is the type. Can do overlapping moves. See also `["Copy"](#Copy)`.
`MoveD` is like `Move` but returns `dest`. Useful for encouraging compilers to tail-call optimise.
```
void Move (void* src, void* dest, int nitems, type)
void * MoveD(void* src, void* dest, int nitems, type)
```
`my_snprintf` The C library `snprintf` functionality, if available and standards-compliant (uses `vsnprintf`, actually). However, if the `vsnprintf` is not available, will unfortunately use the unsafe `vsprintf` which can overrun the buffer (there is an overrun check, but that may be too late). Consider using `sv_vcatpvf` instead, or getting `vsnprintf`.
```
int my_snprintf(char *buffer, const Size_t len,
const char *format, ...)
```
`my_sprintf` `**DEPRECATED!**` It is planned to remove `my_sprintf` from a future release of Perl. Do not use it for new code; remove it from existing code.
Do NOT use this due to the possibility of overflowing `buffer`. Instead use my\_snprintf()
```
int my_sprintf(NN char *buffer, NN const char *pat, ...)
```
`my_strlcat` The C library `strlcat` if available, or a Perl implementation of it. This operates on C `NUL`-terminated strings.
`my_strlcat()` appends string `src` to the end of `dst`. It will append at most `size - strlen(dst) - 1` characters. It will then `NUL`-terminate, unless `size` is 0 or the original `dst` string was longer than `size` (in practice this should not happen as it means that either `size` is incorrect or that `dst` is not a proper `NUL`-terminated string).
Note that `size` is the full size of the destination buffer and the result is guaranteed to be `NUL`-terminated if there is room. Note that room for the `NUL` should be included in `size`.
The return value is the total length that `dst` would have if `size` is sufficiently large. Thus it is the initial length of `dst` plus the length of `src`. If `size` is smaller than the return, the excess was not appended.
```
Size_t my_strlcat(char *dst, const char *src, Size_t size)
```
`my_strlcpy` The C library `strlcpy` if available, or a Perl implementation of it. This operates on C `NUL`-terminated strings.
`my_strlcpy()` copies up to `size - 1` characters from the string `src` to `dst`, `NUL`-terminating the result if `size` is not 0.
The return value is the total length `src` would be if the copy completely succeeded. If it is larger than `size`, the excess was not copied.
```
Size_t my_strlcpy(char *dst, const char *src, Size_t size)
```
`my_strnlen` The C library `strnlen` if available, or a Perl implementation of it.
`my_strnlen()` computes the length of the string, up to `maxlen` characters. It will never attempt to address more than `maxlen` characters, making it suitable for use with strings that are not guaranteed to be NUL-terminated.
```
Size_t my_strnlen(const char *str, Size_t maxlen)
```
`my_vsnprintf` The C library `vsnprintf` if available and standards-compliant. However, if the `vsnprintf` is not available, will unfortunately use the unsafe `vsprintf` which can overrun the buffer (there is an overrun check, but that may be too late). Consider using `sv_vcatpvf` instead, or getting `vsnprintf`.
```
int my_vsnprintf(char *buffer, const Size_t len,
const char *format, va_list ap)
```
`ninstr` Find the first (leftmost) occurrence of a sequence of bytes within another sequence. This is the Perl version of `strstr()`, extended to handle arbitrary sequences, potentially containing embedded `NUL` characters (`NUL` is what the initial `n` in the function name stands for; some systems have an equivalent, `memmem()`, but with a somewhat different API).
Another way of thinking about this function is finding a needle in a haystack. `big` points to the first byte in the haystack. `big_end` points to one byte beyond the final byte in the haystack. `little` points to the first byte in the needle. `little_end` points to one byte beyond the final byte in the needle. All the parameters must be non-`NULL`.
The function returns `NULL` if there is no occurrence of `little` within `big`. If `little` is the empty string, `big` is returned.
Because this function operates at the byte level, and because of the inherent characteristics of UTF-8 (or UTF-EBCDIC), it will work properly if both the needle and the haystack are strings with the same UTF-8ness, but not if the UTF-8ness differs.
```
char* ninstr(const char* big, const char* bigend,
const char* little, const char* lend)
```
`Nullch` Null character pointer. (No longer available when `PERL_CORE` is defined.)
`PL_na` A scratch pad variable in which to store a `STRLEN` value. If would have been better named something like `PL_temp_strlen`.
It is is typically used with `SvPV` when one is actually planning to discard the returned length, (hence the length is "Not Applicable", which is how this variable got its name).
It is usually more efficient to either declare a local variable and use that instead, or to use the `SvPV_nolen` macro.
```
STRLEN PL_na
```
`rninstr` Like `["ninstr"](#ninstr)`, but instead finds the final (rightmost) occurrence of a sequence of bytes within another sequence, returning `NULL` if there is no such occurrence.
```
char* rninstr(const char* big, const char* bigend,
const char* little, const char* lend)
```
`savepv` Perl's version of `strdup()`. Returns a pointer to a newly allocated string which is a duplicate of `pv`. The size of the string is determined by `strlen()`, which means it may not contain embedded `NUL` characters and must have a trailing `NUL`. To prevent memory leaks, the memory allocated for the new string needs to be freed when no longer needed. This can be done with the `["Safefree"](#Safefree)` function, or [`SAVEFREEPV`](perlguts#SAVEFREEPV%28p%29).
On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as `["savesharedpv"](#savesharedpv)`.
```
char* savepv(const char* pv)
```
`savepvn` Perl's version of what `strndup()` would be if it existed. Returns a pointer to a newly allocated string which is a duplicate of the first `len` bytes from `pv`, plus a trailing `NUL` byte. The memory allocated for the new string can be freed with the `Safefree()` function.
On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as `["savesharedpvn"](#savesharedpvn)`.
```
char* savepvn(const char* pv, Size_t len)
```
`savepvs` Like `savepvn`, but takes a literal string instead of a string/length pair.
```
char* savepvs("literal string")
```
`savesharedpv` A version of `savepv()` which allocates the duplicate string in memory which is shared between threads.
```
char* savesharedpv(const char* pv)
```
`savesharedpvn` A version of `savepvn()` which allocates the duplicate string in memory which is shared between threads. (With the specific difference that a `NULL` pointer is not acceptable)
```
char* savesharedpvn(const char *const pv, const STRLEN len)
```
`savesharedpvs` A version of `savepvs()` which allocates the duplicate string in memory which is shared between threads.
```
char* savesharedpvs("literal string")
```
`savesharedsvpv` A version of `savesharedpv()` which allocates the duplicate string in memory which is shared between threads.
```
char* savesharedsvpv(SV *sv)
```
`savesvpv` A version of `savepv()`/`savepvn()` which gets the string to duplicate from the passed in SV using `SvPV()`
On some platforms, Windows for example, all allocated memory owned by a thread is deallocated when that thread ends. So if you need that not to happen, you need to use the shared memory functions, such as `["savesharedsvpv"](#savesharedsvpv)`.
```
char* savesvpv(SV* sv)
```
`strEQ` Test two `NUL`-terminated strings to see if they are equal. Returns true or false.
```
bool strEQ(char* s1, char* s2)
```
`strGE` Test two `NUL`-terminated strings to see if the first, `s1`, is greater than or equal to the second, `s2`. Returns true or false.
```
bool strGE(char* s1, char* s2)
```
`strGT` Test two `NUL`-terminated strings to see if the first, `s1`, is greater than the second, `s2`. Returns true or false.
```
bool strGT(char* s1, char* s2)
```
`STRINGIFY` This macro surrounds its token with double quotes.
```
string STRINGIFY(token x)
```
`strLE` Test two `NUL`-terminated strings to see if the first, `s1`, is less than or equal to the second, `s2`. Returns true or false.
```
bool strLE(char* s1, char* s2)
```
`STRLEN` Described in <perlguts>.
`strLT` Test two `NUL`-terminated strings to see if the first, `s1`, is less than the second, `s2`. Returns true or false.
```
bool strLT(char* s1, char* s2)
```
`strNE` Test two `NUL`-terminated strings to see if they are different. Returns true or false.
```
bool strNE(char* s1, char* s2)
```
`strnEQ` Test two `NUL`-terminated strings to see if they are equal. The `len` parameter indicates the number of bytes to compare. Returns true or false. (A wrapper for `strncmp`).
```
bool strnEQ(char* s1, char* s2, STRLEN len)
```
`strnNE` Test two `NUL`-terminated strings to see if they are different. The `len` parameter indicates the number of bytes to compare. Returns true or false. (A wrapper for `strncmp`).
```
bool strnNE(char* s1, char* s2, STRLEN len)
```
`STR_WITH_LEN` Returns two comma separated tokens of the input literal string, and its length. This is convenience macro which helps out in some API calls. Note that it can't be used as an argument to macros or functions that under some configurations might be macros, which means that it requires the full Perl\_xxx(aTHX\_ ...) form for any API calls where it's used.
```
pair STR_WITH_LEN("literal string")
```
`Zero`
`ZeroD` The XSUB-writer's interface to the C `memzero` function. The `dest` is the destination, `nitems` is the number of items, and `type` is the type.
`ZeroD` is like `Zero` but returns `dest`. Useful for encouraging compilers to tail-call optimise.
```
void Zero (void* dest, int nitems, type)
void * ZeroD(void* dest, int nitems, type)
```
SV Flags
---------
`SVt_IV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_NULL` Type flag for scalars. See ["svtype"](#svtype).
`SVt_NV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_PV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_PVAV` Type flag for arrays. See ["svtype"](#svtype).
`SVt_PVCV` Type flag for subroutines. See ["svtype"](#svtype).
`SVt_PVFM` Type flag for formats. See ["svtype"](#svtype).
`SVt_PVGV` Type flag for typeglobs. See ["svtype"](#svtype).
`SVt_PVHV` Type flag for hashes. See ["svtype"](#svtype).
`SVt_PVIO` Type flag for I/O objects. See ["svtype"](#svtype).
`SVt_PVIV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_PVLV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_PVMG` Type flag for scalars. See ["svtype"](#svtype).
`SVt_PVNV` Type flag for scalars. See ["svtype"](#svtype).
`SVt_REGEXP` Type flag for regular expressions. See ["svtype"](#svtype).
`svtype` An enum of flags for Perl types. These are found in the file *sv.h* in the `svtype` enum. Test these flags with the `SvTYPE` macro.
The types are:
```
SVt_NULL
SVt_IV
SVt_NV
SVt_RV
SVt_PV
SVt_PVIV
SVt_PVNV
SVt_PVMG
SVt_INVLIST
SVt_REGEXP
SVt_PVGV
SVt_PVLV
SVt_PVAV
SVt_PVHV
SVt_PVCV
SVt_PVFM
SVt_PVIO
```
These are most easily explained from the bottom up.
`SVt_PVIO` is for I/O objects, `SVt_PVFM` for formats, `SVt_PVCV` for subroutines, `SVt_PVHV` for hashes and `SVt_PVAV` for arrays.
All the others are scalar types, that is, things that can be bound to a `$` variable. For these, the internal types are mostly orthogonal to types in the Perl language.
Hence, checking `SvTYPE(sv) < SVt_PVAV` is the best way to see whether something is a scalar.
`SVt_PVGV` represents a typeglob. If `!SvFAKE(sv)`, then it is a real, incoercible typeglob. If `SvFAKE(sv)`, then it is a scalar to which a typeglob has been assigned. Assigning to it again will stop it from being a typeglob. `SVt_PVLV` represents a scalar that delegates to another scalar behind the scenes. It is used, e.g., for the return value of `substr` and for tied hash and array elements. It can hold any scalar value, including a typeglob. `SVt_REGEXP` is for regular expressions. `SVt_INVLIST` is for Perl core internal use only.
`SVt_PVMG` represents a "normal" scalar (not a typeglob, regular expression, or delegate). Since most scalars do not need all the internal fields of a PVMG, we save memory by allocating smaller structs when possible. All the other types are just simpler forms of `SVt_PVMG`, with fewer internal fields. `SVt_NULL` can only hold undef. `SVt_IV` can hold undef, an integer, or a reference. (`SVt_RV` is an alias for `SVt_IV`, which exists for backward compatibility.) `SVt_NV` can hold any of those or a double. `SVt_PV` can only hold `undef` or a string. `SVt_PVIV` is a superset of `SVt_PV` and `SVt_IV`. `SVt_PVNV` is similar. `SVt_PVMG` can hold anything `SVt_PVNV` can hold, but it can, but does not have to, be blessed or magical.
SV Handling
------------
`boolSV` Returns a true SV if `b` is a true value, or a false SV if `b` is 0.
See also `["PL\_sv\_yes"](#PL_sv_yes)` and `["PL\_sv\_no"](#PL_sv_no)`.
```
SV * boolSV(bool b)
```
`croak_xs_usage` A specialised variant of `croak()` for emitting the usage message for xsubs
```
croak_xs_usage(cv, "eee_yow");
```
works out the package name and subroutine name from `cv`, and then calls `croak()`. Hence if `cv` is `&ouch::awk`, it would call `croak` as:
```
Perl_croak(aTHX_ "Usage: %" SVf "::%" SVf "(%s)", "ouch" "awk",
"eee_yow");
```
```
void croak_xs_usage(const CV *const cv, const char *const params)
```
`DEFSV` Returns the SV associated with `$_`
```
SV * DEFSV
```
`DEFSV_set` Associate `sv` with `$_`
```
void DEFSV_set(SV * sv)
```
`get_sv` Returns the SV of the specified Perl scalar. `flags` are passed to ["`gv_fetchpv`"](#gv_fetchpv). If `GV_ADD` is set and the Perl variable does not exist then it will be created. If `flags` is zero and the variable does not exist then NULL is returned.
NOTE: the `perl_get_sv()` form is **deprecated**.
```
SV* get_sv(const char *name, I32 flags)
```
`isGV_with_GP` Returns a boolean as to whether or not `sv` is a GV with a pointer to a GP (glob pointer).
```
bool isGV_with_GP(SV * sv)
```
`looks_like_number` Test if the content of an SV looks like a number (or is a number). `Inf` and `Infinity` are treated as numbers (so will not issue a non-numeric warning), even if your `atof()` doesn't grok them. Get-magic is ignored.
```
I32 looks_like_number(SV *const sv)
```
`MUTABLE_PTR` `MUTABLE_AV` `MUTABLE_CV` `MUTABLE_GV` `MUTABLE_HV` `MUTABLE_IO`
`MUTABLE_SV` The `MUTABLE_*\**`() macros cast pointers to the types shown, in such a way (compiler permitting) that casting away const-ness will give a warning; e.g.:
```
const SV *sv = ...;
AV *av1 = (AV*)sv; <== BAD: the const has been silently
cast away
AV *av2 = MUTABLE_AV(sv); <== GOOD: it may warn
```
`MUTABLE_PTR` is the base macro used to derive new casts. The other already-built-in ones return pointers to what their names indicate.
```
void * MUTABLE_PTR(void * p)
AV * MUTABLE_AV (AV * p)
CV * MUTABLE_CV (CV * p)
GV * MUTABLE_GV (GV * p)
HV * MUTABLE_HV (HV * p)
IO * MUTABLE_IO (IO * p)
SV * MUTABLE_SV (SV * p)
```
`newRV`
`newRV_inc` These are identical. They create an RV wrapper for an SV. The reference count for the original SV is incremented.
```
SV* newRV(SV *const sv)
```
`newRV_noinc` Creates an RV wrapper for an SV. The reference count for the original SV is **not** incremented.
```
SV* newRV_noinc(SV *const tmpRef)
```
`newSV` Creates a new SV. A non-zero `len` parameter indicates the number of bytes of preallocated string space the SV should have. An extra byte for a trailing `NUL` is also reserved. (`SvPOK` is not set for the SV even if string space is allocated.) The reference count for the new SV is set to 1.
In 5.9.3, `newSV()` replaces the older `NEWSV()` API, and drops the first parameter, *x*, a debug aid which allowed callers to identify themselves. This aid has been superseded by a new build option, `PERL_MEM_LOG` (see ["PERL\_MEM\_LOG" in perlhacktips](perlhacktips#PERL_MEM_LOG)). The older API is still there for use in XS modules supporting older perls.
```
SV* newSV(const STRLEN len)
```
`newSVhek` Creates a new SV from the hash key structure. It will generate scalars that point to the shared string table where possible. Returns a new (undefined) SV if `hek` is NULL.
```
SV* newSVhek(const HEK *const hek)
```
`newSViv` Creates a new SV and copies an integer into it. The reference count for the SV is set to 1.
```
SV* newSViv(const IV i)
```
`newSVnv` Creates a new SV and copies a floating point value into it. The reference count for the SV is set to 1.
```
SV* newSVnv(const NV n)
```
`newSVpadname` NOTE: `newSVpadname` is **experimental** and may change or be removed without notice.
Creates a new SV containing the pad name.
```
SV* newSVpadname(PADNAME *pn)
```
`newSVpv` Creates a new SV and copies a string (which may contain `NUL` (`\0`) characters) into it. The reference count for the SV is set to 1. If `len` is zero, Perl will compute the length using `strlen()`, (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte).
This function can cause reliability issues if you are likely to pass in empty strings that are not null terminated, because it will run strlen on the string and potentially run past valid memory.
Using ["newSVpvn"](#newSVpvn) is a safer alternative for non `NUL` terminated strings. For string literals use ["newSVpvs"](#newSVpvs) instead. This function will work fine for `NUL` terminated strings, but if you want to avoid the if statement on whether to call `strlen` use `newSVpvn` instead (calling `strlen` yourself).
```
SV* newSVpv(const char *const s, const STRLEN len)
```
`newSVpvf` Creates a new SV and initializes it with the string formatted like `sv_catpvf`.
NOTE: `newSVpvf` must be explicitly called as `Perl_newSVpvf` with an `aTHX_` parameter.
```
SV* Perl_newSVpvf(pTHX_ const char *const pat, ...)
```
`newSVpvf_nocontext` Like `["newSVpvf"](#newSVpvf)` but does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
```
SV* newSVpvf_nocontext(const char *const pat, ...)
```
`newSVpvn` Creates a new SV and copies a string into it, which may contain `NUL` characters (`\0`) and other binary data. The reference count for the SV is set to 1. Note that if `len` is zero, Perl will create a zero length (Perl) string. You are responsible for ensuring that the source buffer is at least `len` bytes long. If the `buffer` argument is NULL the new SV will be undefined.
```
SV* newSVpvn(const char *const buffer, const STRLEN len)
```
`newSVpvn_flags` Creates a new SV and copies a string (which may contain `NUL` (`\0`) characters) into it. The reference count for the SV is set to 1. Note that if `len` is zero, Perl will create a zero length string. You are responsible for ensuring that the source string is at least `len` bytes long. If the `s` argument is NULL the new SV will be undefined. Currently the only flag bits accepted are `SVf_UTF8` and `SVs_TEMP`. If `SVs_TEMP` is set, then `sv_2mortal()` is called on the result before returning. If `SVf_UTF8` is set, `s` is considered to be in UTF-8 and the `SVf_UTF8` flag will be set on the new SV. `newSVpvn_utf8()` is a convenience wrapper for this function, defined as
```
#define newSVpvn_utf8(s, len, u) \
newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0)
```
```
SV* newSVpvn_flags(const char *const s, const STRLEN len,
const U32 flags)
```
`newSVpvn_share` Creates a new SV with its `SvPVX_const` pointing to a shared string in the string table. If the string does not already exist in the table, it is created first. Turns on the `SvIsCOW` flag (or `READONLY` and `FAKE` in 5.16 and earlier). If the `hash` parameter is non-zero, that value is used; otherwise the hash is computed. The string's hash can later be retrieved from the SV with the `["SvSHARED\_HASH"](#SvSHARED_HASH)` macro. The idea here is that as the string table is used for shared hash keys these strings will have `SvPVX_const == HeKEY` and hash lookup will avoid string compare.
```
SV* newSVpvn_share(const char* s, I32 len, U32 hash)
```
`newSVpvn_utf8` Creates a new SV and copies a string (which may contain `NUL` (`\0`) characters) into it. If `utf8` is true, calls `SvUTF8_on` on the new SV. Implemented as a wrapper around `newSVpvn_flags`.
```
SV* newSVpvn_utf8(const char* s, STRLEN len, U32 utf8)
```
`newSVpvs` Like `newSVpvn`, but takes a literal string instead of a string/length pair.
```
SV* newSVpvs("literal string")
```
`newSVpvs_flags` Like `newSVpvn_flags`, but takes a literal string instead of a string/length pair.
```
SV* newSVpvs_flags("literal string", U32 flags)
```
`newSVpv_share` Like `newSVpvn_share`, but takes a `NUL`-terminated string instead of a string/length pair.
```
SV* newSVpv_share(const char* s, U32 hash)
```
`newSVpvs_share` Like `newSVpvn_share`, but takes a literal string instead of a string/length pair and omits the hash parameter.
```
SV* newSVpvs_share("literal string")
```
`newSVrv` Creates a new SV for the existing RV, `rv`, to point to. If `rv` is not an RV then it will be upgraded to one. If `classname` is non-null then the new SV will be blessed in the specified package. The new SV is returned and its reference count is 1. The reference count 1 is owned by `rv`. See also newRV\_inc() and newRV\_noinc() for creating a new RV properly.
```
SV* newSVrv(SV *const rv, const char *const classname)
```
`newSVsv` `newSVsv_nomg`
`newSVsv_flags` These create a new SV which is an exact duplicate of the original SV (using `sv_setsv`.)
They differ only in that `newSVsv` performs 'get' magic; `newSVsv_nomg` skips any magic; and `newSVsv_flags` allows you to explicitly set a `flags` parameter.
```
SV* newSVsv (SV *const old)
SV* newSVsv_nomg (SV *const old)
SV* newSVsv_flags(SV *const old, I32 flags)
```
`newSV_type` Creates a new SV, of the type specified. The reference count for the new SV is set to 1.
```
SV* newSV_type(const svtype type)
```
`newSV_type_mortal` Creates a new mortal SV, of the type specified. The reference count for the new SV is set to 1.
This is equivalent to SV\* sv = sv\_2mortal(newSV\_type(<some type>)) and SV\* sv = sv\_newmortal(); sv\_upgrade(sv, <some\_type>) but should be more efficient than both of them. (Unless sv\_2mortal is inlined at some point in the future.)
```
SV* newSV_type_mortal(const svtype type)
```
`newSVuv` Creates a new SV and copies an unsigned integer into it. The reference count for the SV is set to 1.
```
SV* newSVuv(const UV u)
```
`Nullsv` Null SV pointer. (No longer available when `PERL_CORE` is defined.)
`PL_sv_no` This is the `false` SV. It is readonly. See `["PL\_sv\_yes"](#PL_sv_yes)`. Always refer to this as `&PL_sv_no`.
```
SV PL_sv_no
```
`PL_sv_undef` This is the `undef` SV. It is readonly. Always refer to this as `&PL_sv_undef`.
```
SV PL_sv_undef
```
`PL_sv_yes` This is the `true` SV. It is readonly. See `["PL\_sv\_no"](#PL_sv_no)`. Always refer to this as `&PL_sv_yes`.
```
SV PL_sv_yes
```
`PL_sv_zero` This readonly SV has a zero numeric value and a `"0"` string value. It's similar to `["PL\_sv\_no"](#PL_sv_no)` except for its string value. Can be used as a cheap alternative to `mXPUSHi(0)` for example. Always refer to this as `&PL_sv_zero`. Introduced in 5.28.
```
SV PL_sv_zero
```
`SAVE_DEFSV` Localize `$_`. See ["Localizing changes" in perlguts](perlguts#Localizing-changes).
```
void SAVE_DEFSV
```
`sortsv` In-place sort an array of SV pointers with the given comparison routine.
Currently this always uses mergesort. See `["sortsv\_flags"](#sortsv_flags)` for a more flexible routine.
```
void sortsv(SV** array, size_t num_elts, SVCOMPARE_t cmp)
```
`sortsv_flags` In-place sort an array of SV pointers with the given comparison routine, with various SORTf\_\* flag options.
```
void sortsv_flags(SV** array, size_t num_elts, SVCOMPARE_t cmp,
U32 flags)
```
`SV` Described in <perlguts>.
`sv_2cv` Using various gambits, try to get a CV from an SV; in addition, try if possible to set `*st` and `*gvp` to the stash and GV associated with it. The flags in `lref` are passed to `gv_fetchsv`.
```
CV* sv_2cv(SV* sv, HV **const st, GV **const gvp, const I32 lref)
```
`sv_2io` Using various gambits, try to get an IO from an SV: the IO slot if its a GV; or the recursive result if we're an RV; or the IO slot of the symbol named after the PV if we're a string.
'Get' magic is ignored on the `sv` passed in, but will be called on `SvRV(sv)` if `sv` is an RV.
```
IO* sv_2io(SV *const sv)
```
`sv_2iv_flags` Return the integer value of an SV, doing any necessary string conversion. If `flags` has the `SV_GMAGIC` bit set, does an `mg_get()` first. Normally used via the `SvIV(sv)` and `SvIVx(sv)` macros.
```
IV sv_2iv_flags(SV *const sv, const I32 flags)
```
`sv_2mortal` Marks an existing SV as mortal. The SV will be destroyed "soon", either by an explicit call to `FREETMPS`, or by an implicit call at places such as statement boundaries. `SvTEMP()` is turned on which means that the SV's string buffer can be "stolen" if this SV is copied. See also `["sv\_newmortal"](#sv_newmortal)` and `["sv\_mortalcopy"](#sv_mortalcopy)`.
```
SV* sv_2mortal(SV *const sv)
```
`sv_2nv_flags` Return the num value of an SV, doing any necessary string or integer conversion. If `flags` has the `SV_GMAGIC` bit set, does an `mg_get()` first. Normally used via the `SvNV(sv)` and `SvNVx(sv)` macros.
```
NV sv_2nv_flags(SV *const sv, const I32 flags)
```
`sv_2pv`
`sv_2pv_flags` These implement the various forms of the ["`SvPV`" in perlapi](perlapi#SvPV) macros. The macros are the preferred interface.
These return a pointer to the string value of an SV (coercing it to a string if necessary), and set `*lp` to its length in bytes.
The forms differ in that plain `sv_2pvbyte` always processes 'get' magic; and `sv_2pvbyte_flags` processes 'get' magic if and only if `flags` contains `SV_GMAGIC`.
```
char* sv_2pv (SV *sv, STRLEN *lp)
char* sv_2pv_flags(SV *const sv, STRLEN *const lp,
const U32 flags)
```
`sv_2pvbyte`
`sv_2pvbyte_flags` These implement the various forms of the ["`SvPVbyte`" in perlapi](perlapi#SvPVbyte) macros. The macros are the preferred interface.
These return a pointer to the byte-encoded representation of the SV, and set `*lp` to its length. If the SV is marked as being encoded as UTF-8, it will be downgraded, if possible, to a byte string. If the SV cannot be downgraded, they croak.
The forms differ in that plain `sv_2pvbyte` always processes 'get' magic; and `sv_2pvbyte_flags` processes 'get' magic if and only if `flags` contains `SV_GMAGIC`.
```
char* sv_2pvbyte (SV *sv, STRLEN *const lp)
char* sv_2pvbyte_flags(SV *sv, STRLEN *const lp, const U32 flags)
```
`sv_2pvutf8`
`sv_2pvutf8_flags` These implement the various forms of the ["`SvPVutf8`" in perlapi](perlapi#SvPVutf8) macros. The macros are the preferred interface.
These return a pointer to the UTF-8-encoded representation of the SV, and set `*lp` to its length in bytes. They may cause the SV to be upgraded to UTF-8 as a side-effect.
The forms differ in that plain `sv_2pvutf8` always processes 'get' magic; and `sv_2pvutf8_flags` processes 'get' magic if and only if `flags` contains `SV_GMAGIC`.
```
char* sv_2pvutf8 (SV *sv, STRLEN *const lp)
char* sv_2pvutf8_flags(SV *sv, STRLEN *const lp, const U32 flags)
```
`sv_2uv_flags` Return the unsigned integer value of an SV, doing any necessary string conversion. If `flags` has the `SV_GMAGIC` bit set, does an `mg_get()` first. Normally used via the `SvUV(sv)` and `SvUVx(sv)` macros.
```
UV sv_2uv_flags(SV *const sv, const I32 flags)
```
`SvAMAGIC` Returns a boolean as to whether `sv` has overloading (active magic) enabled or not.
```
bool SvAMAGIC(SV * sv)
```
`sv_backoff` Remove any string offset. You should normally use the `SvOOK_off` macro wrapper instead.
```
void sv_backoff(SV *const sv)
```
`sv_bless` Blesses an SV into a specified package. The SV must be an RV. The package must be designated by its stash (see `["gv\_stashpv"](#gv_stashpv)`). The reference count of the SV is unaffected.
```
SV* sv_bless(SV *const sv, HV *const stash)
```
`sv_catpv` `sv_catpv_flags` `sv_catpv_mg`
`sv_catpv_nomg` These concatenate the `NUL`-terminated string `sstr` onto the end of the string which is in the SV. If the SV has the UTF-8 status set, then the bytes appended should be valid UTF-8.
They differ only in how they handle magic:
`sv_catpv_mg` performs both 'get' and 'set' magic.
`sv_catpv` performs only 'get' magic.
`sv_catpv_nomg` skips all magic.
`sv_catpv_flags` has an extra `flags` parameter which allows you to specify any combination of magic handling (using `SV_GMAGIC` and/or `SV_SMAGIC`), and to also override the UTF-8 handling. By supplying the `SV_CATUTF8` flag, the appended string is forced to be interpreted as UTF-8; by supplying instead the `SV_CATBYTES` flag, it will be interpreted as just bytes. Either the SV or the string appended will be upgraded to UTF-8 if necessary.
```
void sv_catpv (SV *const dsv, const char* sstr)
void sv_catpv_flags(SV *dsv, const char *sstr, const I32 flags)
void sv_catpv_mg (SV *const dsv, const char *const sstr)
void sv_catpv_nomg (SV *const dsv, const char* sstr)
```
`sv_catpvf` `sv_catpvf_nocontext` `sv_catpvf_mg`
`sv_catpvf_mg_nocontext` These process their arguments like `sprintf`, and append the formatted output to an SV. As with `sv_vcatpvfn`, argument reordering is not supporte when called with a non-null C-style variable argument list.
If the appended data contains "wide" characters (including, but not limited to, SVs with a UTF-8 PV formatted with `%s`, and characters >255 formatted with `%c`), the original SV might get upgraded to UTF-8.
If the original SV was UTF-8, the pattern should be valid UTF-8; if the original SV was bytes, the pattern should be too.
All perform 'get' magic, but only `sv_catpvf_mg` and `sv_catpvf_mg_nocontext` perform 'set' magic.
`sv_catpvf_nocontext` and `sv_catpvf_mg_nocontext` do not take a thread context (`aTHX`) parameter, so are used in situations where the caller doesn't already have the thread context.
NOTE: `sv_catpvf` must be explicitly called as `Perl_sv_catpvf` with an `aTHX_` parameter.
NOTE: `sv_catpvf_mg` must be explicitly called as `Perl_sv_catpvf_mg` with an `aTHX_` parameter.
```
void Perl_sv_catpvf (pTHX_ SV *const sv,
const char *const pat, ...)
void sv_catpvf_nocontext (SV *const sv, const char *const pat,
...)
void Perl_sv_catpvf_mg (pTHX_ SV *const sv,
const char *const pat, ...)
void sv_catpvf_mg_nocontext(SV *const sv, const char *const pat,
...)
```
`sv_catpvn` `sv_catpvn_flags` `sv_catpvn_mg`
`sv_catpvn_nomg` These concatenate the `len` bytes of the string beginning at `ptr` onto the end of the string which is in `dsv`. The caller must make sure `ptr` contains at least `len` bytes.
For all but `sv_catpvn_flags`, the string appended is assumed to be valid UTF-8 if the SV has the UTF-8 status set, and a string of bytes otherwise.
They differ in that:
`sv_catpvn_mg` performs both 'get' and 'set' magic on `dsv`.
`sv_catpvn` performs only 'get' magic.
`sv_catpvn_nomg` skips all magic.
`sv_catpvn_flags` has an extra `flags` parameter which allows you to specify any combination of magic handling (using `SV_GMAGIC` and/or `SV_SMAGIC`) and to also override the UTF-8 handling. By supplying the `SV_CATBYTES` flag, the appended string is interpreted as plain bytes; by supplying instead the `SV_CATUTF8` flag, it will be interpreted as UTF-8, and the `dsv` will be upgraded to UTF-8 if necessary.
`sv_catpvn`, `sv_catpvn_mg`, and `sv_catpvn_nomg` are implemented in terms of `sv_catpvn_flags`.
```
void sv_catpvn (SV *dsv, const char *sstr, STRLEN len)
void sv_catpvn_flags(SV *const dsv, const char *sstr,
const STRLEN len, const I32 flags)
void sv_catpvn_mg (SV *dsv, const char *sstr, STRLEN len)
void sv_catpvn_nomg (SV *dsv, const char *sstr, STRLEN len)
```
`sv_catpvs` Like `sv_catpvn`, but takes a literal string instead of a string/length pair.
```
void sv_catpvs(SV* sv, "literal string")
```
`sv_catpvs_flags` Like `sv_catpvn_flags`, but takes a literal string instead of a string/length pair.
```
void sv_catpvs_flags(SV* sv, "literal string", I32 flags)
```
`sv_catpvs_mg` Like `sv_catpvn_mg`, but takes a literal string instead of a string/length pair.
```
void sv_catpvs_mg(SV* sv, "literal string")
```
`sv_catpvs_nomg` Like `sv_catpvn_nomg`, but takes a literal string instead of a string/length pair.
```
void sv_catpvs_nomg(SV* sv, "literal string")
```
`sv_catsv` `sv_catsv_flags` `sv_catsv_mg`
`sv_catsv_nomg` These concatenate the string from SV `sstr` onto the end of the string in SV `dsv`. If `sstr` is null, these are no-ops; otherwise only `dsv` is modified.
They differ only in what magic they perform:
`sv_catsv_mg` performs 'get' magic on both SVs before the copy, and 'set' magic on `dsv` afterwards.
`sv_catsv` performs just 'get' magic, on both SVs.
`sv_catsv_nomg` skips all magic.
`sv_catsv_flags` has an extra `flags` parameter which allows you to use `SV_GMAGIC` and/or `SV_SMAGIC` to specify any combination of magic handling (although either both or neither SV will have 'get' magic applied to it.)
`sv_catsv`, `sv_catsv_mg`, and `sv_catsv_nomg` are implemented in terms of `sv_catsv_flags`.
```
void sv_catsv (SV *dsv, SV *sstr)
void sv_catsv_flags(SV *const dsv, SV *const sstr,
const I32 flags)
void sv_catsv_mg (SV *dsv, SV *sstr)
void sv_catsv_nomg (SV *dsv, SV *sstr)
```
`sv_chop` Efficient removal of characters from the beginning of the string buffer. `SvPOK(sv)`, or at least `SvPOKp(sv)`, must be true and `ptr` must be a pointer to somewhere inside the string buffer. `ptr` becomes the first character of the adjusted string. Uses the `OOK` hack. On return, only `SvPOK(sv)` and `SvPOKp(sv)` among the `OK` flags will be true.
Beware: after this function returns, `ptr` and SvPVX\_const(sv) may no longer refer to the same chunk of data.
The unfortunate similarity of this function's name to that of Perl's `chop` operator is strictly coincidental. This function works from the left; `chop` works from the right.
```
void sv_chop(SV *const sv, const char *const ptr)
```
`sv_clear` Clear an SV: call any destructors, free up any memory used by the body, and free the body itself. The SV's head is *not* freed, although its type is set to all 1's so that it won't inadvertently be assumed to be live during global destruction etc. This function should only be called when `REFCNT` is zero. Most of the time you'll want to call `sv_free()` (or its macro wrapper `SvREFCNT_dec`) instead.
```
void sv_clear(SV *const orig_sv)
```
`sv_cmp` Compares the strings in two SVs. Returns -1, 0, or 1 indicating whether the string in `sv1` is less than, equal to, or greater than the string in `sv2`. Is UTF-8 and `'use bytes'` aware, handles get magic, and will coerce its args to strings if necessary. See also `["sv\_cmp\_locale"](#sv_cmp_locale)`.
```
I32 sv_cmp(SV *const sv1, SV *const sv2)
```
`sv_cmp_flags` Compares the strings in two SVs. Returns -1, 0, or 1 indicating whether the string in `sv1` is less than, equal to, or greater than the string in `sv2`. Is UTF-8 and `'use bytes'` aware and will coerce its args to strings if necessary. If the flags has the `SV_GMAGIC` bit set, it handles get magic. See also `["sv\_cmp\_locale\_flags"](#sv_cmp_locale_flags)`.
```
I32 sv_cmp_flags(SV *const sv1, SV *const sv2, const U32 flags)
```
`sv_cmp_locale` Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and `'use bytes'` aware, handles get magic, and will coerce its args to strings if necessary. See also `["sv\_cmp"](#sv_cmp)`.
```
I32 sv_cmp_locale(SV *const sv1, SV *const sv2)
```
`sv_cmp_locale_flags` Compares the strings in two SVs in a locale-aware manner. Is UTF-8 and `'use bytes'` aware and will coerce its args to strings if necessary. If the flags contain `SV_GMAGIC`, it handles get magic. See also `["sv\_cmp\_flags"](#sv_cmp_flags)`.
```
I32 sv_cmp_locale_flags(SV *const sv1, SV *const sv2,
const U32 flags)
```
`sv_collxfrm` This calls `sv_collxfrm_flags` with the SV\_GMAGIC flag. See `["sv\_collxfrm\_flags"](#sv_collxfrm_flags)`.
```
char* sv_collxfrm(SV *const sv, STRLEN *const nxp)
```
`sv_collxfrm_flags` Add Collate Transform magic to an SV if it doesn't already have it. If the flags contain `SV_GMAGIC`, it handles get-magic.
Any scalar variable may carry `PERL_MAGIC_collxfrm` magic that contains the scalar data of the variable, but transformed to such a format that a normal memory comparison can be used to compare the data according to the locale settings.
```
char* sv_collxfrm_flags(SV *const sv, STRLEN *const nxp,
I32 const flags)
```
`sv_copypv` `sv_copypv_nomg`
`sv_copypv_flags` These copy a stringified representation of the source SV into the destination SV. They automatically perform coercion of numeric values into strings. Guaranteed to preserve the `UTF8` flag even from overloaded objects. Similar in nature to `sv_2pv[_flags]` but they operate directly on an SV instead of just the string. Mostly they use ["`sv_2pv_flags`"](#sv_2pv_flags) to do the work, except when that would lose the UTF-8'ness of the PV.
The three forms differ only in whether or not they perform 'get magic' on `sv`. `sv_copypv_nomg` skips 'get magic'; `sv_copypv` performs it; and `sv_copypv_flags` either performs it (if the `SV_GMAGIC` bit is set in `flags`) or doesn't (if that bit is cleared).
```
void sv_copypv (SV *const dsv, SV *const ssv)
void sv_copypv_nomg (SV *const dsv, SV *const ssv)
void sv_copypv_flags(SV *const dsv, SV *const ssv,
const I32 flags)
```
`SvCUR` Returns the length, in bytes, of the PV inside the SV. Note that this may not match Perl's `length`; for that, use `sv_len_utf8(sv)`. See `["SvLEN"](#SvLEN)` also.
```
STRLEN SvCUR(SV* sv)
```
`SvCUR_set` Sets the current length, in bytes, of the C string which is in the SV. See `["SvCUR"](#SvCUR)` and `SvIV_set`>.
```
void SvCUR_set(SV* sv, STRLEN len)
```
`sv_dec`
`sv_dec_nomg` These auto-decrement the value in the SV, doing string to numeric conversion if necessary. They both handle operator overloading.
They differ only in that:
`sv_dec` handles 'get' magic; `sv_dec_nomg` skips 'get' magic.
```
void sv_dec(SV *const sv)
```
`sv_derived_from` Exactly like ["sv\_derived\_from\_pv"](#sv_derived_from_pv), but doesn't take a `flags` parameter.
```
bool sv_derived_from(SV* sv, const char *const name)
```
`sv_derived_from_pv` Exactly like ["sv\_derived\_from\_pvn"](#sv_derived_from_pvn), but takes a nul-terminated string instead of a string/length pair.
```
bool sv_derived_from_pv(SV* sv, const char *const name,
U32 flags)
```
`sv_derived_from_pvn` Returns a boolean indicating whether the SV is derived from the specified class *at the C level*. To check derivation at the Perl level, call `isa()` as a normal Perl method.
Currently, the only significant value for `flags` is SVf\_UTF8.
```
bool sv_derived_from_pvn(SV* sv, const char *const name,
const STRLEN len, U32 flags)
```
`sv_derived_from_sv` Exactly like ["sv\_derived\_from\_pvn"](#sv_derived_from_pvn), but takes the name string in the form of an SV instead of a string/length pair. This is the advised form.
```
bool sv_derived_from_sv(SV* sv, SV *namesv, U32 flags)
```
`sv_does` Like ["sv\_does\_pv"](#sv_does_pv), but doesn't take a `flags` parameter.
```
bool sv_does(SV* sv, const char *const name)
```
`sv_does_pv` Like ["sv\_does\_sv"](#sv_does_sv), but takes a nul-terminated string instead of an SV.
```
bool sv_does_pv(SV* sv, const char *const name, U32 flags)
```
`sv_does_pvn` Like ["sv\_does\_sv"](#sv_does_sv), but takes a string/length pair instead of an SV.
```
bool sv_does_pvn(SV* sv, const char *const name,
const STRLEN len, U32 flags)
```
`sv_does_sv` Returns a boolean indicating whether the SV performs a specific, named role. The SV can be a Perl object or the name of a Perl class.
```
bool sv_does_sv(SV* sv, SV* namesv, U32 flags)
```
`SvEND` Returns a pointer to the spot just after the last character in the string which is in the SV, where there is usually a trailing `NUL` character (even though Perl scalars do not strictly require it). See `["SvCUR"](#SvCUR)`. Access the character as `*(SvEND(sv))`.
Warning: If `SvCUR` is equal to `SvLEN`, then `SvEND` points to unallocated memory.
```
char* SvEND(SV* sv)
```
`sv_eq` Returns a boolean indicating whether the strings in the two SVs are identical. Is UTF-8 and `'use bytes'` aware, handles get magic, and will coerce its args to strings if necessary.
This function does not handle operator overloading. For a version that does, see instead `sv_streq`.
```
I32 sv_eq(SV* sv1, SV* sv2)
```
`sv_eq_flags` Returns a boolean indicating whether the strings in the two SVs are identical. Is UTF-8 and `'use bytes'` aware and coerces its args to strings if necessary. If the flags has the `SV_GMAGIC` bit set, it handles get-magic, too.
This function does not handle operator overloading. For a version that does, see instead `sv_streq_flags`.
```
I32 sv_eq_flags(SV* sv1, SV* sv2, const U32 flags)
```
`sv_force_normal` Undo various types of fakery on an SV: if the PV is a shared string, make a private copy; if we're a ref, stop refing; if we're a glob, downgrade to an `xpvmg`. See also `["sv\_force\_normal\_flags"](#sv_force_normal_flags)`.
```
void sv_force_normal(SV *sv)
```
`sv_force_normal_flags` Undo various types of fakery on an SV, where fakery means "more than" a string: if the PV is a shared string, make a private copy; if we're a ref, stop refing; if we're a glob, downgrade to an `xpvmg`; if we're a copy-on-write scalar, this is the on-write time when we do the copy, and is also used locally; if this is a vstring, drop the vstring magic. If `SV_COW_DROP_PV` is set then a copy-on-write scalar drops its PV buffer (if any) and becomes `SvPOK_off` rather than making a copy. (Used where this scalar is about to be set to some other value.) In addition, the `flags` parameter gets passed to `sv_unref_flags()` when unreffing. `sv_force_normal` calls this function with flags set to 0.
This function is expected to be used to signal to perl that this SV is about to be written to, and any extra book-keeping needs to be taken care of. Hence, it croaks on read-only values.
```
void sv_force_normal_flags(SV *const sv, const U32 flags)
```
`sv_free` Decrement an SV's reference count, and if it drops to zero, call `sv_clear` to invoke destructors and free up any memory used by the body; finally, deallocating the SV's head itself. Normally called via a wrapper macro `SvREFCNT_dec`.
```
void sv_free(SV *const sv)
```
`SvGAMAGIC` Returns true if the SV has get magic or overloading. If either is true then the scalar is active data, and has the potential to return a new value every time it is accessed. Hence you must be careful to only read it once per user logical operation and work with that returned value. If neither is true then the scalar's value cannot change unless written to.
```
U32 SvGAMAGIC(SV* sv)
```
`SvGETMAGIC` Invokes `["mg\_get"](#mg_get)` on an SV if it has 'get' magic. For example, this will call `FETCH` on a tied variable. This macro evaluates its argument more than once.
```
void SvGETMAGIC(SV* sv)
```
`sv_gets` Get a line from the filehandle and store it into the SV, optionally appending to the currently-stored string. If `append` is not 0, the line is appended to the SV instead of overwriting it. `append` should be set to the byte offset that the appended string should start at in the SV (typically, `SvCUR(sv)` is a suitable choice).
```
char* sv_gets(SV *const sv, PerlIO *const fp, I32 append)
```
`sv_get_backrefs` NOTE: `sv_get_backrefs` is **experimental** and may change or be removed without notice.
If `sv` is the target of a weak reference then it returns the back references structure associated with the sv; otherwise return `NULL`.
When returning a non-null result the type of the return is relevant. If it is an AV then the elements of the AV are the weak reference RVs which point at this item. If it is any other type then the item itself is the weak reference.
See also `Perl_sv_add_backref()`, `Perl_sv_del_backref()`, `Perl_sv_kill_backrefs()`
```
SV* sv_get_backrefs(SV *const sv)
```
`SvGROW` Expands the character buffer in the SV so that it has room for the indicated number of bytes (remember to reserve space for an extra trailing `NUL` character). Calls `sv_grow` to perform the expansion if necessary. Returns a pointer to the character buffer. SV must be of type >= `SVt_PV`. One alternative is to call `sv_grow` if you are not sure of the type of SV.
You might mistakenly think that `len` is the number of bytes to add to the existing size, but instead it is the total size `sv` should be.
```
char * SvGROW(SV* sv, STRLEN len)
```
`sv_inc`
`sv_inc_nomg` These auto-increment the value in the SV, doing string to numeric conversion if necessary. They both handle operator overloading.
They differ only in that `sv_inc` performs 'get' magic; `sv_inc_nomg` skips any magic.
```
void sv_inc(SV *const sv)
```
`sv_insert` Inserts and/or replaces a string at the specified offset/length within the SV. Similar to the Perl `substr()` function, with `littlelen` bytes starting at `little` replacing `len` bytes of the string in `bigstr` starting at `offset`. Handles get magic.
```
void sv_insert(SV *const bigstr, const STRLEN offset,
const STRLEN len, const char *const little,
const STRLEN littlelen)
```
`sv_insert_flags` Same as `sv_insert`, but the extra `flags` are passed to the `SvPV_force_flags` that applies to `bigstr`.
```
void sv_insert_flags(SV *const bigstr, const STRLEN offset,
const STRLEN len, const char *little,
const STRLEN littlelen, const U32 flags)
```
`SvIOK` Returns a U32 value indicating whether the SV contains an integer.
```
U32 SvIOK(SV* sv)
```
`SvIOK_notUV` Returns a boolean indicating whether the SV contains a signed integer.
```
bool SvIOK_notUV(SV* sv)
```
`SvIOK_off` Unsets the IV status of an SV.
```
void SvIOK_off(SV* sv)
```
`SvIOK_on` Tells an SV that it is an integer.
```
void SvIOK_on(SV* sv)
```
`SvIOK_only` Tells an SV that it is an integer and disables all other `OK` bits.
```
void SvIOK_only(SV* sv)
```
`SvIOK_only_UV` Tells an SV that it is an unsigned integer and disables all other `OK` bits.
```
void SvIOK_only_UV(SV* sv)
```
`SvIOKp` Returns a U32 value indicating whether the SV contains an integer. Checks the **private** setting. Use `SvIOK` instead.
```
U32 SvIOKp(SV* sv)
```
`SvIOK_UV` Returns a boolean indicating whether the SV contains an integer that must be interpreted as unsigned. A non-negative integer whose value is within the range of both an IV and a UV may be flagged as either `SvUOK` or `SvIOK`.
```
bool SvIOK_UV(SV* sv)
```
`sv_isa` Returns a boolean indicating whether the SV is blessed into the specified class.
This does not check for subtypes or method overloading. Use `sv_isa_sv` to verify an inheritance relationship in the same way as the `isa` operator by respecting any `isa()` method overloading; or `sv_derived_from_sv` to test directly on the actual object type.
```
int sv_isa(SV* sv, const char *const name)
```
`sv_isa_sv` NOTE: `sv_isa_sv` is **experimental** and may change or be removed without notice.
Returns a boolean indicating whether the SV is an object reference and is derived from the specified class, respecting any `isa()` method overloading it may have. Returns false if `sv` is not a reference to an object, or is not derived from the specified class.
This is the function used to implement the behaviour of the `isa` operator.
Does not invoke magic on `sv`.
Not to be confused with the older `sv_isa` function, which does not use an overloaded `isa()` method, nor will check subclassing.
```
bool sv_isa_sv(SV* sv, SV* namesv)
```
`SvIsBOOL` Returns true if the SV is one of the special boolean constants (PL\_sv\_yes or PL\_sv\_no), or is a regular SV whose last assignment stored a copy of one.
```
bool SvIsBOOL(SV* sv)
```
`SvIsCOW` Returns a U32 value indicating whether the SV is Copy-On-Write (either shared hash key scalars, or full Copy On Write scalars if 5.9.0 is configured for COW).
```
U32 SvIsCOW(SV* sv)
```
`SvIsCOW_shared_hash` Returns a boolean indicating whether the SV is Copy-On-Write shared hash key scalar.
```
bool SvIsCOW_shared_hash(SV* sv)
```
`sv_isobject` Returns a boolean indicating whether the SV is an RV pointing to a blessed object. If the SV is not an RV, or if the object is not blessed, then this will return false.
```
int sv_isobject(SV* sv)
```
`SvIV` `SvIVx`
`SvIV_nomg` These coerce the given SV to IV and return it. The returned value in many circumstances will get stored in `sv`'s IV slot, but not in all cases. (Use `["sv\_setiv"](#sv_setiv)` to make sure it does).
`SvIVx` is different from the others in that it is guaranteed to evaluate `sv` exactly once; the others may evaluate it multiple times. Only use this form if `sv` is an expression with side effects, otherwise use the more efficient `SvIV`.
`SvIV_nomg` is the same as `SvIV`, but does not perform 'get' magic.
```
IV SvIV(SV* sv)
```
`SvIV_set` Set the value of the IV pointer in sv to val. It is possible to perform the same function of this macro with an lvalue assignment to `SvIVX`. With future Perls, however, it will be more efficient to use `SvIV_set` instead of the lvalue assignment to `SvIVX`.
```
void SvIV_set(SV* sv, IV val)
```
`SvIVX` Returns the raw value in the SV's IV slot, without checks or conversions. Only use when you are sure `SvIOK` is true. See also `["SvIV"](#SvIV)`.
```
IV SvIVX(SV* sv)
```
`SvLEN` Returns the size of the string buffer in the SV, not including any part attributable to `SvOOK`. See `["SvCUR"](#SvCUR)`.
```
STRLEN SvLEN(SV* sv)
```
`sv_len` Returns the length of the string in the SV. Handles magic and type coercion and sets the UTF8 flag appropriately. See also `["SvCUR"](#SvCUR)`, which gives raw access to the `xpv_cur` slot.
```
STRLEN sv_len(SV *const sv)
```
`SvLEN_set` Set the size of the string buffer for the SV. See `["SvLEN"](#SvLEN)`.
```
void SvLEN_set(SV* sv, STRLEN len)
```
`sv_len_utf8`
`sv_len_utf8_nomg` These return the number of characters in the string in an SV, counting wide UTF-8 bytes as a single character. Both handle type coercion. They differ only in that `sv_len_utf8` performs 'get' magic; `sv_len_utf8_nomg` skips any magic.
```
STRLEN sv_len_utf8(SV *const sv)
```
`SvLOCK` Arranges for a mutual exclusion lock to be obtained on `sv` if a suitable module has been loaded.
```
void SvLOCK(SV* sv)
```
`sv_magic` Adds magic to an SV. First upgrades `sv` to type `SVt_PVMG` if necessary, then adds a new magic item of type `how` to the head of the magic list.
See `["sv\_magicext"](#sv_magicext)` (which `sv_magic` now calls) for a description of the handling of the `name` and `namlen` arguments.
You need to use `sv_magicext` to add magic to `SvREADONLY` SVs and also to add more than one instance of the same `how`.
```
void sv_magic(SV *const sv, SV *const obj, const int how,
const char *const name, const I32 namlen)
```
`sv_magicext` Adds magic to an SV, upgrading it if necessary. Applies the supplied `vtable` and returns a pointer to the magic added.
Note that `sv_magicext` will allow things that `sv_magic` will not. In particular, you can add magic to `SvREADONLY` SVs, and add more than one instance of the same `how`.
If `namlen` is greater than zero then a `savepvn` *copy* of `name` is stored, if `namlen` is zero then `name` is stored as-is and - as another special case - if `(name && namlen == HEf_SVKEY)` then `name` is assumed to contain an SV\* and is stored as-is with its `REFCNT` incremented.
(This is now used as a subroutine by `sv_magic`.)
```
MAGIC * sv_magicext(SV *const sv, SV *const obj, const int how,
const MGVTBL *const vtbl,
const char *const name, const I32 namlen)
```
`SvMAGIC_set` Set the value of the MAGIC pointer in `sv` to val. See `["SvIV\_set"](#SvIV_set)`.
```
void SvMAGIC_set(SV* sv, MAGIC* val)
```
`sv_mortalcopy` Creates a new SV which is a copy of the original SV (using `sv_setsv`). The new SV is marked as mortal. It will be destroyed "soon", either by an explicit call to `FREETMPS`, or by an implicit call at places such as statement boundaries. See also `["sv\_newmortal"](#sv_newmortal)` and `["sv\_2mortal"](#sv_2mortal)`.
```
SV* sv_mortalcopy(SV *const oldsv)
```
`sv_mortalcopy_flags` Like `sv_mortalcopy`, but the extra `flags` are passed to the `sv_setsv_flags`.
```
SV* sv_mortalcopy_flags(SV *const oldsv, U32 flags)
```
`sv_newmortal` Creates a new null SV which is mortal. The reference count of the SV is set to 1. It will be destroyed "soon", either by an explicit call to `FREETMPS`, or by an implicit call at places such as statement boundaries. See also `["sv\_mortalcopy"](#sv_mortalcopy)` and `["sv\_2mortal"](#sv_2mortal)`.
```
SV* sv_newmortal()
```
`SvNIOK` Returns a U32 value indicating whether the SV contains a number, integer or double.
```
U32 SvNIOK(SV* sv)
```
`SvNIOK_off` Unsets the NV/IV status of an SV.
```
void SvNIOK_off(SV* sv)
```
`SvNIOKp` Returns a U32 value indicating whether the SV contains a number, integer or double. Checks the **private** setting. Use `SvNIOK` instead.
```
U32 SvNIOKp(SV* sv)
```
`SvNOK` Returns a U32 value indicating whether the SV contains a double.
```
U32 SvNOK(SV* sv)
```
`SvNOK_off` Unsets the NV status of an SV.
```
void SvNOK_off(SV* sv)
```
`SvNOK_on` Tells an SV that it is a double.
```
void SvNOK_on(SV* sv)
```
`SvNOK_only` Tells an SV that it is a double and disables all other OK bits.
```
void SvNOK_only(SV* sv)
```
`SvNOKp` Returns a U32 value indicating whether the SV contains a double. Checks the **private** setting. Use `SvNOK` instead.
```
U32 SvNOKp(SV* sv)
```
`sv_nolocking` `**DEPRECATED!**` It is planned to remove `sv_nolocking` from a future release of Perl. Do not use it for new code; remove it from existing code.
Dummy routine which "locks" an SV when there is no locking module present. Exists to avoid test for a `NULL` function pointer and because it could potentially warn under some level of strict-ness.
"Superseded" by `sv_nosharing()`.
```
void sv_nolocking(SV *sv)
```
`sv_nounlocking` `**DEPRECATED!**` It is planned to remove `sv_nounlocking` from a future release of Perl. Do not use it for new code; remove it from existing code.
Dummy routine which "unlocks" an SV when there is no locking module present. Exists to avoid test for a `NULL` function pointer and because it could potentially warn under some level of strict-ness.
"Superseded" by `sv_nosharing()`.
```
void sv_nounlocking(SV *sv)
```
`sv_numeq` A convenient shortcut for calling `sv_numeq_flags` with the `SV_GMAGIC` flag. This function basically behaves like the Perl code `$sv1 == $sv2`.
```
bool sv_numeq(SV* sv1, SV* sv2)
```
`sv_numeq_flags` Returns a boolean indicating whether the numbers in the two SVs are identical. If the flags argument has the `SV_GMAGIC` bit set, it handles get-magic too. Will coerce its args to numbers if necessary. Treats `NULL` as undef.
If flags does not have the `SV_SKIP_OVERLOAD` bit set, an attempt to use `==` overloading will be made. If such overloading does not exist or the flag is set, then regular numerical comparison will be used instead.
```
bool sv_numeq_flags(SV* sv1, SV* sv2, const U32 flags)
```
`SvNV` `SvNVx`
`SvNV_nomg` These coerce the given SV to NV and return it. The returned value in many circumstances will get stored in `sv`'s NV slot, but not in all cases. (Use `["sv\_setnv"](#sv_setnv)` to make sure it does).
`SvNVx` is different from the others in that it is guaranteed to evaluate `sv` exactly once; the others may evaluate it multiple times. Only use this form if `sv` is an expression with side effects, otherwise use the more efficient `SvNV`.
`SvNV_nomg` is the same as `SvNV`, but does not perform 'get' magic.
```
NV SvNV(SV* sv)
```
`SvNV_set` Set the value of the NV pointer in `sv` to val. See `["SvIV\_set"](#SvIV_set)`.
```
void SvNV_set(SV* sv, NV val)
```
`SvNVX` Returns the raw value in the SV's NV slot, without checks or conversions. Only use when you are sure `SvNOK` is true. See also `["SvNV"](#SvNV)`.
```
NV SvNVX(SV* sv)
```
`SvOK` Returns a U32 value indicating whether the value is defined. This is only meaningful for scalars.
```
U32 SvOK(SV* sv)
```
`SvOOK` Returns a U32 indicating whether the pointer to the string buffer is offset. This hack is used internally to speed up removal of characters from the beginning of a `["SvPV"](#SvPV)`. When `SvOOK` is true, then the start of the allocated string buffer is actually `SvOOK_offset()` bytes before `SvPVX`. This offset used to be stored in `SvIVX`, but is now stored within the spare part of the buffer.
```
U32 SvOOK(SV* sv)
```
`SvOOK_off` Remove any string offset.
```
void SvOOK_off(SV * sv)
```
`SvOOK_offset` Reads into `len` the offset from `SvPVX` back to the true start of the allocated buffer, which will be non-zero if `sv_chop` has been used to efficiently remove characters from start of the buffer. Implemented as a macro, which takes the address of `len`, which must be of type `STRLEN`. Evaluates `sv` more than once. Sets `len` to 0 if `SvOOK(sv)` is false.
```
void SvOOK_offset(SV*sv, STRLEN len)
```
`SvPOK` Returns a U32 value indicating whether the SV contains a character string.
```
U32 SvPOK(SV* sv)
```
`SvPOK_off` Unsets the PV status of an SV.
```
void SvPOK_off(SV* sv)
```
`SvPOK_on` Tells an SV that it is a string.
```
void SvPOK_on(SV* sv)
```
`SvPOK_only` Tells an SV that it is a string and disables all other `OK` bits. Will also turn off the UTF-8 status.
```
void SvPOK_only(SV* sv)
```
`SvPOK_only_UTF8` Tells an SV that it is a string and disables all other `OK` bits, and leaves the UTF-8 status as it was.
```
void SvPOK_only_UTF8(SV* sv)
```
`SvPOKp` Returns a U32 value indicating whether the SV contains a character string. Checks the **private** setting. Use `SvPOK` instead.
```
U32 SvPOKp(SV* sv)
```
`sv_pos_b2u` Converts the value pointed to by `offsetp` from a count of bytes from the start of the string, to a count of the equivalent number of UTF-8 chars. Handles magic and type coercion.
Use `sv_pos_b2u_flags` in preference, which correctly handles strings longer than 2Gb.
```
void sv_pos_b2u(SV *const sv, I32 *const offsetp)
```
`sv_pos_b2u_flags` Converts `offset` from a count of bytes from the start of the string, to a count of the equivalent number of UTF-8 chars. Handles type coercion. `flags` is passed to `SvPV_flags`, and usually should be `SV_GMAGIC|SV_CONST_RETURN` to handle magic.
```
STRLEN sv_pos_b2u_flags(SV *const sv, STRLEN const offset,
U32 flags)
```
`sv_pos_u2b` Converts the value pointed to by `offsetp` from a count of UTF-8 chars from the start of the string, to a count of the equivalent number of bytes; if `lenp` is non-zero, it does the same to `lenp`, but this time starting from the offset, rather than from the start of the string. Handles magic and type coercion.
Use `sv_pos_u2b_flags` in preference, which correctly handles strings longer than 2Gb.
```
void sv_pos_u2b(SV *const sv, I32 *const offsetp,
I32 *const lenp)
```
`sv_pos_u2b_flags` Converts the offset from a count of UTF-8 chars from the start of the string, to a count of the equivalent number of bytes; if `lenp` is non-zero, it does the same to `lenp`, but this time starting from `offset`, rather than from the start of the string. Handles type coercion. `flags` is passed to `SvPV_flags`, and usually should be `SV_GMAGIC|SV_CONST_RETURN` to handle magic.
```
STRLEN sv_pos_u2b_flags(SV *const sv, STRLEN uoffset,
STRLEN *const lenp, U32 flags)
```
`SvPV` `SvPVx` `SvPV_nomg` `SvPV_nolen` `SvPVx_nolen` `SvPV_nomg_nolen` `SvPV_mutable` `SvPV_const` `SvPVx_const` `SvPV_nolen_const` `SvPVx_nolen_const` `SvPV_nomg_const` `SvPV_nomg_const_nolen` `SvPV_flags` `SvPV_flags_const` `SvPV_flags_mutable` `SvPVbyte` `SvPVbyte_nomg` `SvPVbyte_nolen` `SvPVbytex_nolen` `SvPVbytex` `SvPVbyte_or_null` `SvPVbyte_or_null_nomg` `SvPVutf8` `SvPVutf8x` `SvPVutf8_nomg` `SvPVutf8_nolen` `SvPVutf8_or_null`
`SvPVutf8_or_null_nomg` All these return a pointer to the string in `sv`, or a stringified form of `sv` if it does not contain a string. The SV may cache the stringified version becoming `SvPOK`.
This is a very basic and common operation, so there are lots of slightly different versions of it.
Note that there is no guarantee that the return value of `SvPV(sv)`, for example, is equal to `SvPVX(sv)`, or that `SvPVX(sv)` contains valid data, or that successive calls to `SvPV(sv)` (or another of these forms) will return the same pointer value each time. This is due to the way that things like overloading and Copy-On-Write are handled. In these cases, the return value may point to a temporary buffer or similar. If you absolutely need the `SvPVX` field to be valid (for example, if you intend to write to it), then see `["SvPV\_force"](#SvPV_force)`.
The differences between the forms are:
The forms with neither `byte` nor `utf8` in their names (e.g., `SvPV` or `SvPV_nolen`) can expose the SV's internal string buffer. If that buffer consists entirely of bytes 0-255 and includes any bytes above 127, then you **MUST** consult `SvUTF8` to determine the actual code points the string is meant to contain. Generally speaking, it is probably safer to prefer `SvPVbyte`, `SvPVutf8`, and the like. See ["How do I pass a Perl string to a C library?" in perlguts](perlguts#How-do-I-pass-a-Perl-string-to-a-C-library%3F) for more details.
The forms with `flags` in their names allow you to use the `flags` parameter to specify to process 'get' magic (by setting the `SV_GMAGIC` flag) or to skip 'get' magic (by clearing it). The other forms process 'get' magic, except for the ones with `nomg` in their names, which skip 'get' magic.
The forms that take a `len` parameter will set that variable to the byte length of the resultant string (these are macros, so don't use `&len`).
The forms with `nolen` in their names indicate they don't have a `len` parameter. They should be used only when it is known that the PV is a C string, terminated by a NUL byte, and without intermediate NUL characters; or when you don't care about its length.
The forms with `const` in their names return `const char *` so that the compiler will hopefully complain if you were to try to modify the contents of the string (unless you cast away const yourself).
The other forms return a mutable pointer so that the string is modifiable by the caller; this is emphasized for the ones with `mutable` in their names.
The forms whose name ends in `x` are the same as the corresponding form without the `x`, but the `x` form is guaranteed to evaluate `sv` exactly once, with a slight loss of efficiency. Use this if `sv` is an expression with side effects.
`SvPVutf8` is like `SvPV`, but converts `sv` to UTF-8 first if not already UTF-8. Similiarly, the other forms with `utf8` in their names correspond to their respective forms without.
`SvPVutf8_or_null` and `SvPVutf8_or_null_nomg` don't have corresponding non-`utf8` forms. Instead they are like `SvPVutf8_nomg`, but when `sv` is undef, they return `NULL`.
`SvPVbyte` is like `SvPV`, but converts `sv` to byte representation first if currently encoded as UTF-8. If `sv` cannot be downgraded from UTF-8, it croaks. Similiarly, the other forms with `byte` in their names correspond to their respective forms without.
`SvPVbyte_or_null` doesn't have a corresponding non-`byte` form. Instead it is like `SvPVbyte`, but when `sv` is undef, it returns `NULL`.
```
char* SvPV (SV* sv, STRLEN len)
char* SvPVx (SV* sv, STRLEN len)
char* SvPV_nomg (SV* sv, STRLEN len)
char* SvPV_nolen (SV* sv)
char* SvPVx_nolen (SV* sv)
char* SvPV_nomg_nolen (SV* sv)
char* SvPV_mutable (SV* sv, STRLEN len)
const char* SvPV_const (SV* sv, STRLEN len)
const char* SvPVx_const (SV* sv, STRLEN len)
const char* SvPV_nolen_const (SV* sv)
const char* SvPVx_nolen_const (SV* sv)
const char* SvPV_nomg_const (SV* sv, STRLEN len)
const char* SvPV_nomg_const_nolen(SV* sv)
char * SvPV_flags (SV * sv, STRLEN len,
U32 flags)
const char * SvPV_flags_const (SV * sv, STRLEN len,
U32 flags)
char * SvPV_flags_mutable (SV * sv, STRLEN len,
U32 flags)
char* SvPVbyte (SV* sv, STRLEN len)
char* SvPVbyte_nomg (SV* sv, STRLEN len)
char* SvPVbyte_nolen (SV* sv)
char* SvPVbytex_nolen (SV* sv)
char* SvPVbytex (SV* sv, STRLEN len)
char* SvPVbyte_or_null (SV* sv, STRLEN len)
char* SvPVbyte_or_null_nomg(SV* sv, STRLEN len)
char* SvPVutf8 (SV* sv, STRLEN len)
char* SvPVutf8x (SV* sv, STRLEN len)
char* SvPVutf8_nomg (SV* sv, STRLEN len)
char* SvPVutf8_nolen (SV* sv)
char* SvPVutf8_or_null (SV* sv, STRLEN len)
char* SvPVutf8_or_null_nomg(SV* sv, STRLEN len)
```
`SvPVCLEAR` Ensures that sv is a SVt\_PV and that its SvCUR is 0, and that it is properly null terminated. Equivalent to sv\_setpvs(""), but more efficient.
```
char * SvPVCLEAR(SV* sv)
```
`SvPV_force` `SvPV_force_nolen` `SvPVx_force` `SvPV_force_nomg` `SvPV_force_nomg_nolen` `SvPV_force_mutable` `SvPV_force_flags` `SvPV_force_flags_nolen` `SvPV_force_flags_mutable` `SvPVbyte_force` `SvPVbytex_force` `SvPVutf8_force`
`SvPVutf8x_force` These are like `["SvPV"](#SvPV)`, returning the string in the SV, but will force the SV into containing a string (`["SvPOK"](#SvPOK)`), and only a string (`["SvPOK\_only"](#SvPOK_only)`), by hook or by crook. You need to use one of these `force` routines if you are going to update the `["SvPVX"](#SvPVX)` directly.
Note that coercing an arbitrary scalar into a plain PV will potentially strip useful data from it. For example if the SV was `SvROK`, then the referent will have its reference count decremented, and the SV itself may be converted to an `SvPOK` scalar with a string buffer containing a value such as `"ARRAY(0x1234)"`.
The differences between the forms are:
The forms with `flags` in their names allow you to use the `flags` parameter to specify to perform 'get' magic (by setting the `SV_GMAGIC` flag) or to skip 'get' magic (by clearing it). The other forms do perform 'get' magic, except for the ones with `nomg` in their names, which skip 'get' magic.
The forms that take a `len` parameter will set that variable to the byte length of the resultant string (these are macros, so don't use `&len`).
The forms with `nolen` in their names indicate they don't have a `len` parameter. They should be used only when it is known that the PV is a C string, terminated by a NUL byte, and without intermediate NUL characters; or when you don't care about its length.
The forms with `mutable` in their names are effectively the same as those without, but the name emphasizes that the string is modifiable by the caller, which it is in all the forms.
`SvPVutf8_force` is like `SvPV_force`, but converts `sv` to UTF-8 first if not already UTF-8.
`SvPVutf8x_force` is like `SvPVutf8_force`, but guarantees to evaluate `sv` only once; use the more efficient `SvPVutf8_force` otherwise.
`SvPVbyte_force` is like `SvPV_force`, but converts `sv` to byte representation first if currently encoded as UTF-8. If the SV cannot be downgraded from UTF-8, this croaks.
`SvPVbytex_force` is like `SvPVbyte_force`, but guarantees to evaluate `sv` only once; use the more efficient `SvPVbyte_force` otherwise.
```
char* SvPV_force (SV* sv, STRLEN len)
char* SvPV_force_nolen (SV* sv)
char* SvPVx_force (SV* sv, STRLEN len)
char* SvPV_force_nomg (SV* sv, STRLEN len)
char* SvPV_force_nomg_nolen (SV * sv)
char* SvPV_force_mutable (SV * sv, STRLEN len)
char* SvPV_force_flags (SV * sv, STRLEN len, U32 flags)
char* SvPV_force_flags_nolen (SV * sv, U32 flags)
char* SvPV_force_flags_mutable(SV * sv, STRLEN len, U32 flags)
char* SvPVbyte_force (SV* sv, STRLEN len)
char* SvPVbytex_force (SV* sv, STRLEN len)
char* SvPVutf8_force (SV* sv, STRLEN len)
char* SvPVutf8x_force (SV* sv, STRLEN len)
```
`SvPV_free` Frees the PV buffer in `sv`, leaving things in a precarious state, so should only be used as part of a larger operation
```
void SvPV_free(SV * sv)
```
`sv_pvn_force_flags` Get a sensible string out of the SV somehow. If `flags` has the `SV_GMAGIC` bit set, will `["mg\_get"](#mg_get)` on `sv` if appropriate, else not. `sv_pvn_force` and `sv_pvn_force_nomg` are implemented in terms of this function. You normally want to use the various wrapper macros instead: see `["SvPV\_force"](#SvPV_force)` and `["SvPV\_force\_nomg"](#SvPV_force_nomg)`.
```
char* sv_pvn_force_flags(SV *const sv, STRLEN *const lp,
const U32 flags)
```
`SvPV_renew` Low level micro optimization of `["SvGROW"](#SvGROW)`. It is generally better to use `SvGROW` instead. This is because `SvPV_renew` ignores potential issues that `SvGROW` handles. `sv` needs to have a real `PV` that is unencombered by things like COW. Using `SV_CHECK_THINKFIRST` or `SV_CHECK_THINKFIRST_COW_DROP` before calling this should clean it up, but why not just use `SvGROW` if you're not sure about the provenance?
```
void SvPV_renew(SV* sv, STRLEN len)
```
`SvPV_set` This is probably not what you want to use, you probably wanted ["sv\_usepvn\_flags"](#sv_usepvn_flags) or ["sv\_setpvn"](#sv_setpvn) or ["sv\_setpvs"](#sv_setpvs).
Set the value of the PV pointer in `sv` to the Perl allocated `NUL`-terminated string `val`. See also `["SvIV\_set"](#SvIV_set)`.
Remember to free the previous PV buffer. There are many things to check. Beware that the existing pointer may be involved in copy-on-write or other mischief, so do `SvOOK_off(sv)` and use `sv_force_normal` or `SvPV_force` (or check the `SvIsCOW` flag) first to make sure this modification is safe. Then finally, if it is not a COW, call `["SvPV\_free"](#SvPV_free)` to free the previous PV buffer.
```
void SvPV_set(SV* sv, char* val)
```
`SvPVX` `SvPVXx` `SvPVX_const`
`SvPVX_mutable` These return a pointer to the physical string in the SV. The SV must contain a string. Prior to 5.9.3 it is not safe to execute these unless the SV's type >= `SVt_PV`.
These are also used to store the name of an autoloaded subroutine in an XS AUTOLOAD routine. See ["Autoloading with XSUBs" in perlguts](perlguts#Autoloading-with-XSUBs).
`SvPVXx` is identical to `SvPVX`.
`SvPVX_mutable` is merely a synonym for `SvPVX`, but its name emphasizes that the string is modifiable by the caller.
`SvPVX_const` differs in that the return value has been cast so that the compiler will complain if you were to try to modify the contents of the string, (unless you cast away const yourself).
```
char* SvPVX (SV* sv)
char* SvPVXx (SV* sv)
const char* SvPVX_const (SV* sv)
char* SvPVX_mutable(SV* sv)
```
`SvPVXtrue` Note: This macro may evaluate `sv` more than once.
Returns a boolean as to whether or not `sv` contains a PV that is considered TRUE. FALSE is returned if `sv` doesn't contain a PV, or if the PV it does contain is zero length, or consists of just the single character '0'. Every other PV value is considered TRUE.
```
bool SvPVXtrue(SV * sv)
```
`SvREADONLY` Returns true if the argument is readonly, otherwise returns false. Exposed to perl code via Internals::SvREADONLY().
```
U32 SvREADONLY(SV* sv)
```
`SvREADONLY_off` Mark an object as not-readonly. Exactly what this mean depends on the object type. Exposed to perl code via Internals::SvREADONLY().
```
U32 SvREADONLY_off(SV* sv)
```
`SvREADONLY_on` Mark an object as readonly. Exactly what this means depends on the object type. Exposed to perl code via Internals::SvREADONLY().
```
U32 SvREADONLY_on(SV* sv)
```
`sv_ref` Returns a SV describing what the SV passed in is a reference to.
dst can be a SV to be set to the description or NULL, in which case a mortal SV is returned.
If ob is true and the SV is blessed, the description is the class name, otherwise it is the type of the SV, "SCALAR", "ARRAY" etc.
```
SV* sv_ref(SV *dst, const SV *const sv, const int ob)
```
`SvREFCNT` Returns the value of the object's reference count. Exposed to perl code via Internals::SvREFCNT().
```
U32 SvREFCNT(SV* sv)
```
`SvREFCNT_dec`
`SvREFCNT_dec_NN` These decrement the reference count of the given SV.
`SvREFCNT_dec_NN` may only be used when `sv` is known to not be `NULL`.
```
void SvREFCNT_dec(SV *sv)
```
`SvREFCNT_inc` `SvREFCNT_inc_NN` `SvREFCNT_inc_void` `SvREFCNT_inc_void_NN` `SvREFCNT_inc_simple` `SvREFCNT_inc_simple_NN` `SvREFCNT_inc_simple_void`
`SvREFCNT_inc_simple_void_NN` These all increment the reference count of the given SV. The ones without `void` in their names return the SV.
`SvREFCNT_inc` is the base operation; the rest are optimizations if various input constraints are known to be true; hence, all can be replaced with `SvREFCNT_inc`.
`SvREFCNT_inc_NN` can only be used if you know `sv` is not `NULL`. Since we don't have to check the NULLness, it's faster and smaller.
`SvREFCNT_inc_void` can only be used if you don't need the return value. The macro doesn't need to return a meaningful value.
`SvREFCNT_inc_void_NN` can only be used if you both don't need the return value, and you know that `sv` is not `NULL`. The macro doesn't need to return a meaningful value, or check for NULLness, so it's smaller and faster.
`SvREFCNT_inc_simple` can only be used with expressions without side effects. Since we don't have to store a temporary value, it's faster.
`SvREFCNT_inc_simple_NN` can only be used with expressions without side effects and you know `sv` is not `NULL`. Since we don't have to store a temporary value, nor check for NULLness, it's faster and smaller.
`SvREFCNT_inc_simple_void` can only be used with expressions without side effects and you don't need the return value.
`SvREFCNT_inc_simple_void_NN` can only be used with expressions without side effects, you don't need the return value, and you know `sv` is not `NULL`.
```
SV * SvREFCNT_inc (SV *sv)
SV * SvREFCNT_inc_NN (SV *sv)
void SvREFCNT_inc_void (SV *sv)
void SvREFCNT_inc_void_NN (SV* sv)
SV* SvREFCNT_inc_simple (SV* sv)
SV* SvREFCNT_inc_simple_NN (SV* sv)
void SvREFCNT_inc_simple_void (SV* sv)
void SvREFCNT_inc_simple_void_NN(SV* sv)
```
`sv_reftype` Returns a string describing what the SV is a reference to.
If ob is true and the SV is blessed, the string is the class name, otherwise it is the type of the SV, "SCALAR", "ARRAY" etc.
```
const char* sv_reftype(const SV *const sv, const int ob)
```
`sv_replace` Make the first argument a copy of the second, then delete the original. The target SV physically takes over ownership of the body of the source SV and inherits its flags; however, the target keeps any magic it owns, and any magic in the source is discarded. Note that this is a rather specialist SV copying operation; most of the time you'll want to use `sv_setsv` or one of its many macro front-ends.
```
void sv_replace(SV *const sv, SV *const nsv)
```
`sv_report_used` Dump the contents of all SVs not yet freed (debugging aid).
```
void sv_report_used()
```
`sv_reset` Underlying implementation for the `reset` Perl function. Note that the perl-level function is vaguely deprecated.
```
void sv_reset(const char* s, HV *const stash)
```
`SvROK` Tests if the SV is an RV.
```
U32 SvROK(SV* sv)
```
`SvROK_off` Unsets the RV status of an SV.
```
void SvROK_off(SV* sv)
```
`SvROK_on` Tells an SV that it is an RV.
```
void SvROK_on(SV* sv)
```
`SvRV` Dereferences an RV to return the SV.
```
SV* SvRV(SV* sv)
```
`SvRV_set` Set the value of the RV pointer in `sv` to val. See `["SvIV\_set"](#SvIV_set)`.
```
void SvRV_set(SV* sv, SV* val)
```
`sv_rvunweaken` Unweaken a reference: Clear the `SvWEAKREF` flag on this RV; remove the backreference to this RV from the array of backreferences associated with the target SV, increment the refcount of the target. Silently ignores `undef` and warns on non-weak references.
```
SV* sv_rvunweaken(SV *const sv)
```
`sv_rvweaken` Weaken a reference: set the `SvWEAKREF` flag on this RV; give the referred-to SV `PERL_MAGIC_backref` magic if it hasn't already; and push a back-reference to this RV onto the array of backreferences associated with that magic. If the RV is magical, set magic will be called after the RV is cleared. Silently ignores `undef` and warns on already-weak references.
```
SV* sv_rvweaken(SV *const sv)
```
`sv_setbool`
`sv_setbool_mg` These set an SV to a true or false boolean value, upgrading first if necessary.
They differ only in that `sv_setbool_mg` handles 'set' magic; `sv_setbool` does not.
```
void sv_setbool(SV *sv, bool b)
```
`sv_setiv`
`sv_setiv_mg` These copy an integer into the given SV, upgrading first if necessary.
They differ only in that `sv_setiv_mg` handles 'set' magic; `sv_setiv` does not.
```
void sv_setiv (SV *const sv, const IV num)
void sv_setiv_mg(SV *const sv, const IV i)
```
`SvSETMAGIC` Invokes `["mg\_set"](#mg_set)` on an SV if it has 'set' magic. This is necessary after modifying a scalar, in case it is a magical variable like `$|` or a tied variable (it calls `STORE`). This macro evaluates its argument more than once.
```
void SvSETMAGIC(SV* sv)
```
`sv_setnv`
`sv_setnv_mg` These copy a double into the given SV, upgrading first if necessary.
They differ only in that `sv_setnv_mg` handles 'set' magic; `sv_setnv` does not.
```
void sv_setnv(SV *const sv, const NV num)
```
`sv_setpv` `sv_setpv_mg` `sv_setpvn` `sv_setpvn_fresh` `sv_setpvn_mg` `sv_setpvs`
`sv_setpvs_mg` These copy a string into the SV `sv`, making sure it is `["SvPOK\_only"](#SvPOK_only)`.
In the `pvs` forms, the string must be a C literal string, enclosed in double quotes.
In the `pvn` forms, the first byte of the string is pointed to by `ptr`, and `len` indicates the number of bytes to be copied, potentially including embedded `NUL` characters.
In the plain `pv` forms, `ptr` points to a NUL-terminated C string. That is, it points to the first byte of the string, and the copy proceeds up through the first enountered `NUL` byte.
In the forms that take a `ptr` argument, if it is NULL, the SV will become undefined.
The UTF-8 flag is not changed by these functions. A terminating NUL byte is guaranteed in the result.
The `_mg` forms handle 'set' magic; the other forms skip all magic.
`sv_setpvn_fresh` is a cut-down alternative to `sv_setpvn`, intended ONLY to be used with a fresh sv that has been upgraded to a SVt\_PV, SVt\_PVIV, SVt\_PVNV, or SVt\_PVMG.
```
void sv_setpv (SV *const sv, const char *const ptr)
void sv_setpv_mg (SV *const sv, const char *const ptr)
void sv_setpvn (SV *const sv, const char *const ptr,
const STRLEN len)
void sv_setpvn_fresh(SV *const sv, const char *const ptr,
const STRLEN len)
void sv_setpvn_mg (SV *const sv, const char *const ptr,
const STRLEN len)
void sv_setpvs (SV* sv, "literal string")
void sv_setpvs_mg (SV* sv, "literal string")
```
`sv_setpvf` `sv_setpvf_nocontext` `sv_setpvf_mg`
`sv_setpvf_mg_nocontext` These work like `["sv\_catpvf"](#sv_catpvf)` but copy the text into the SV instead of appending it.
The differences between these are:
`sv_setpvf_mg` and `sv_setpvf_mg_nocontext` perform 'set' magic; `sv_setpvf` and `sv_setpvf_nocontext` skip all magic.
`sv_setpvf_nocontext` and `sv_setpvf_mg_nocontext` do not take a thread context (`aTHX`) parameter, so are used in situations where the caller doesn't already have the thread context.
NOTE: `sv_setpvf` must be explicitly called as `Perl_sv_setpvf` with an `aTHX_` parameter.
NOTE: `sv_setpvf_mg` must be explicitly called as `Perl_sv_setpvf_mg` with an `aTHX_` parameter.
```
void Perl_sv_setpvf (pTHX_ SV *const sv,
const char *const pat, ...)
void sv_setpvf_nocontext (SV *const sv, const char *const pat,
...)
void Perl_sv_setpvf_mg (pTHX_ SV *const sv,
const char *const pat, ...)
void sv_setpvf_mg_nocontext(SV *const sv, const char *const pat,
...)
```
`sv_setpviv`
`sv_setpviv_mg` `**DEPRECATED!**` It is planned to remove both forms from a future release of Perl. Do not use them for new code; remove them from existing code.
These copy an integer into the given SV, also updating its string value.
They differ only in that `sv_setpviv_mg` performs 'set' magic; `sv_setpviv` skips any magic.
```
void sv_setpviv (SV *const sv, const IV num)
void sv_setpviv_mg(SV *const sv, const IV iv)
```
`sv_setpv_bufsize` Sets the SV to be a string of cur bytes length, with at least len bytes available. Ensures that there is a null byte at SvEND. Returns a char \* pointer to the SvPV buffer.
```
char * sv_setpv_bufsize(SV *const sv, const STRLEN cur,
const STRLEN len)
```
`sv_setref_iv` Copies an integer into a new SV, optionally blessing the SV. The `rv` argument will be upgraded to an RV. That RV will be modified to point to the new SV. The `classname` argument indicates the package for the blessing. Set `classname` to `NULL` to avoid the blessing. The new SV will have a reference count of 1, and the RV will be returned.
```
SV* sv_setref_iv(SV *const rv, const char *const classname,
const IV iv)
```
`sv_setref_nv` Copies a double into a new SV, optionally blessing the SV. The `rv` argument will be upgraded to an RV. That RV will be modified to point to the new SV. The `classname` argument indicates the package for the blessing. Set `classname` to `NULL` to avoid the blessing. The new SV will have a reference count of 1, and the RV will be returned.
```
SV* sv_setref_nv(SV *const rv, const char *const classname,
const NV nv)
```
`sv_setref_pv` Copies a pointer into a new SV, optionally blessing the SV. The `rv` argument will be upgraded to an RV. That RV will be modified to point to the new SV. If the `pv` argument is `NULL`, then `PL_sv_undef` will be placed into the SV. The `classname` argument indicates the package for the blessing. Set `classname` to `NULL` to avoid the blessing. The new SV will have a reference count of 1, and the RV will be returned.
Do not use with other Perl types such as HV, AV, SV, CV, because those objects will become corrupted by the pointer copy process.
Note that `sv_setref_pvn` copies the string while this copies the pointer.
```
SV* sv_setref_pv(SV *const rv, const char *const classname,
void *const pv)
```
`sv_setref_pvn` Copies a string into a new SV, optionally blessing the SV. The length of the string must be specified with `n`. The `rv` argument will be upgraded to an RV. That RV will be modified to point to the new SV. The `classname` argument indicates the package for the blessing. Set `classname` to `NULL` to avoid the blessing. The new SV will have a reference count of 1, and the RV will be returned.
Note that `sv_setref_pv` copies the pointer while this copies the string.
```
SV* sv_setref_pvn(SV *const rv, const char *const classname,
const char *const pv, const STRLEN n)
```
`sv_setref_pvs` Like `sv_setref_pvn`, but takes a literal string instead of a string/length pair.
```
SV * sv_setref_pvs(SV *const rv, const char *const classname,
"literal string")
```
`sv_setref_uv` Copies an unsigned integer into a new SV, optionally blessing the SV. The `rv` argument will be upgraded to an RV. That RV will be modified to point to the new SV. The `classname` argument indicates the package for the blessing. Set `classname` to `NULL` to avoid the blessing. The new SV will have a reference count of 1, and the RV will be returned.
```
SV* sv_setref_uv(SV *const rv, const char *const classname,
const UV uv)
```
`sv_setrv_inc`
`sv_setrv_inc_mg` As `sv_setrv_noinc` but increments the reference count of *ref*.
`sv_setrv_inc_mg` will invoke 'set' magic on the SV; `sv_setrv_inc` will not.
```
void sv_setrv_inc(SV *const sv, SV *const ref)
```
`sv_setrv_noinc`
`sv_setrv_noinc_mg` Copies an SV pointer into the given SV as an SV reference, upgrading it if necessary. After this, `SvRV(sv)` is equal to *ref*. This does not adjust the reference count of *ref*. The reference *ref* must not be NULL.
`sv_setrv_noinc_mg` will invoke 'set' magic on the SV; `sv_setrv_noinc` will not.
```
void sv_setrv_noinc(SV *const sv, SV *const ref)
```
`SvSetSV` `SvSetMagicSV` `SvSetSV_nosteal`
`SvSetMagicSV_nosteal` if `dsv` is the same as `ssv`, these do nothing. Otherwise they all call some form of `["sv\_setsv"](#sv_setsv)`. They may evaluate their arguments more than once.
The only differences are:
`SvSetMagicSV` and `SvSetMagicSV_nosteal` perform any required 'set' magic afterwards on the destination SV; `SvSetSV` and `SvSetSV_nosteal` do not.
`SvSetSV_nosteal` `SvSetMagicSV_nosteal` call a non-destructive version of `sv_setsv`.
```
void SvSetSV(SV* dsv, SV* ssv)
```
`sv_setsv` `sv_setsv_flags` `sv_setsv_mg`
`sv_setsv_nomg` These copy the contents of the source SV `ssv` into the destination SV `dsv`. `ssv` may be destroyed if it is mortal, so don't use these functions if the source SV needs to be reused. Loosely speaking, they perform a copy-by-value, obliterating any previous content of the destination.
They differ only in that:
`sv_setsv` calls 'get' magic on `ssv`, but skips 'set' magic on `dsv`.
`sv_setsv_mg` calls both 'get' magic on `ssv` and 'set' magic on `dsv`.
`sv_setsv_nomg` skips all magic.
`sv_setsv_flags` has a `flags` parameter which you can use to specify any combination of magic handling, and also you can specify `SV_NOSTEAL` so that the buffers of temps will not be stolen.
You probably want to instead use one of the assortment of wrappers, such as `["SvSetSV"](#SvSetSV)`, `["SvSetSV\_nosteal"](#SvSetSV_nosteal)`, `["SvSetMagicSV"](#SvSetMagicSV)` and `["SvSetMagicSV\_nosteal"](#SvSetMagicSV_nosteal)`.
`sv_setsv_flags` is the primary function for copying scalars, and most other copy-ish functions and macros use it underneath.
```
void sv_setsv (SV *dsv, SV *ssv)
void sv_setsv_flags(SV *dsv, SV *ssv, const I32 flags)
void sv_setsv_mg (SV *const dsv, SV *const ssv)
void sv_setsv_nomg (SV *dsv, SV *ssv)
```
`sv_setuv`
`sv_setuv_mg` These copy an unsigned integer into the given SV, upgrading first if necessary.
They differ only in that `sv_setuv_mg` handles 'set' magic; `sv_setuv` does not.
```
void sv_setuv (SV *const sv, const UV num)
void sv_setuv_mg(SV *const sv, const UV u)
```
`sv_set_undef` Equivalent to `sv_setsv(sv, &PL_sv_undef)`, but more efficient. Doesn't handle set magic.
The perl equivalent is `$sv = undef;`. Note that it doesn't free any string buffer, unlike `undef $sv`.
Introduced in perl 5.25.12.
```
void sv_set_undef(SV *sv)
```
`SvSHARE` Arranges for `sv` to be shared between threads if a suitable module has been loaded.
```
void SvSHARE(SV* sv)
```
`SvSHARED_HASH` Returns the hash for `sv` created by `["newSVpvn\_share"](#newSVpvn_share)`.
```
struct hek* SvSHARED_HASH(SV * sv)
```
`SvSTASH` Returns the stash of the SV.
```
HV* SvSTASH(SV* sv)
```
`SvSTASH_set` Set the value of the STASH pointer in `sv` to val. See `["SvIV\_set"](#SvIV_set)`.
```
void SvSTASH_set(SV* sv, HV* val)
```
`sv_streq` A convenient shortcut for calling `sv_streq_flags` with the `SV_GMAGIC` flag. This function basically behaves like the Perl code `$sv1 eq $sv2`.
```
bool sv_streq(SV* sv1, SV* sv2)
```
`sv_streq_flags` Returns a boolean indicating whether the strings in the two SVs are identical. If the flags argument has the `SV_GMAGIC` bit set, it handles get-magic too. Will coerce its args to strings if necessary. Treats `NULL` as undef. Correctly handles the UTF8 flag.
If flags does not have the `SV_SKIP_OVERLOAD` bit set, an attempt to use `eq` overloading will be made. If such overloading does not exist or the flag is set, then regular string comparison will be used instead.
```
bool sv_streq_flags(SV* sv1, SV* sv2, const U32 flags)
```
`SvTRUE` `SvTRUEx` `SvTRUE_nomg` `SvTRUE_NN`
`SvTRUE_nomg_NN` These return a boolean indicating whether Perl would evaluate the SV as true or false. See `["SvOK"](#SvOK)` for a defined/undefined test.
As of Perl 5.32, all are guaranteed to evaluate `sv` only once. Prior to that release, only `SvTRUEx` guaranteed single evaluation; now `SvTRUEx` is identical to `SvTRUE`.
`SvTRUE_nomg` and `TRUE_nomg_NN` do not perform 'get' magic; the others do unless the scalar is already `SvPOK`, `SvIOK`, or `SvNOK` (the public, not the private flags).
`SvTRUE_NN` is like `["SvTRUE"](#SvTRUE)`, but `sv` is assumed to be non-null (NN). If there is a possibility that it is NULL, use plain `SvTRUE`.
`SvTRUE_nomg_NN` is like `["SvTRUE\_nomg"](#SvTRUE_nomg)`, but `sv` is assumed to be non-null (NN). If there is a possibility that it is NULL, use plain `SvTRUE_nomg`.
```
bool SvTRUE(SV *sv)
```
`SvTYPE` Returns the type of the SV. See `["svtype"](#svtype)`.
```
svtype SvTYPE(SV* sv)
```
`SvUNLOCK` Releases a mutual exclusion lock on `sv` if a suitable module has been loaded.
```
void SvUNLOCK(SV* sv)
```
`sv_unmagic` Removes all magic of type `type` from an SV.
```
int sv_unmagic(SV *const sv, const int type)
```
`sv_unmagicext` Removes all magic of type `type` with the specified `vtbl` from an SV.
```
int sv_unmagicext(SV *const sv, const int type, MGVTBL *vtbl)
```
`sv_unref` Unsets the RV status of the SV, and decrements the reference count of whatever was being referenced by the RV. This can almost be thought of as a reversal of `newSVrv`. This is `sv_unref_flags` with the `flag` being zero. See `["SvROK\_off"](#SvROK_off)`.
```
void sv_unref(SV* sv)
```
`sv_unref_flags` Unsets the RV status of the SV, and decrements the reference count of whatever was being referenced by the RV. This can almost be thought of as a reversal of `newSVrv`. The `cflags` argument can contain `SV_IMMEDIATE_UNREF` to force the reference count to be decremented (otherwise the decrementing is conditional on the reference count being different from one or the reference being a readonly SV). See `["SvROK\_off"](#SvROK_off)`.
```
void sv_unref_flags(SV *const ref, const U32 flags)
```
`SvUOK` Returns a boolean indicating whether the SV contains an integer that must be interpreted as unsigned. A non-negative integer whose value is within the range of both an IV and a UV may be flagged as either `SvUOK` or `SvIOK`.
```
bool SvUOK(SV* sv)
```
`SvUPGRADE` Used to upgrade an SV to a more complex form. Uses `sv_upgrade` to perform the upgrade if necessary. See `["svtype"](#svtype)`.
```
void SvUPGRADE(SV* sv, svtype type)
```
`sv_upgrade` Upgrade an SV to a more complex form. Generally adds a new body type to the SV, then copies across as much information as possible from the old body. It croaks if the SV is already in a more complex form than requested. You generally want to use the `SvUPGRADE` macro wrapper, which checks the type before calling `sv_upgrade`, and hence does not croak. See also `["svtype"](#svtype)`.
```
void sv_upgrade(SV *const sv, svtype new_type)
```
`sv_usepvn` `sv_usepvn_mg`
`sv_usepvn_flags` These tell an SV to use `ptr` for its string value. Normally SVs have their string stored inside the SV, but these tell the SV to use an external string instead.
`ptr` should point to memory that was allocated by ["`Newx`"](#Newx). It must be the start of a `Newx`-ed block of memory, and not a pointer to the middle of it (beware of [`OOK`](perlguts#Offsets) and copy-on-write), and not be from a non-`Newx` memory allocator like `malloc`. The string length, `len`, must be supplied. By default this function will ["`Renew`"](#Renew) (i.e. realloc, move) the memory pointed to by `ptr`, so that the pointer should not be freed or used by the programmer after giving it to `sv_usepvn`, and neither should any pointers from "behind" that pointer (*e.g.*, `ptr` + 1) be used.
In the `sv_usepvn_flags` form, if `flags & SV_SMAGIC` is true, `SvSETMAGIC` is called before returning. And if `flags & SV_HAS_TRAILING_NUL` is true, then `ptr[len]` must be `NUL`, and the realloc will be skipped (*i.e.*, the buffer is actually at least 1 byte longer than `len`, and already meets the requirements for storing in `SvPVX`).
`sv_usepvn` is merely `sv_usepvn_flags` with `flags` set to 0, so 'set' magic is skipped.
`sv_usepvn_mg` is merely `sv_usepvn_flags` with `flags` set to `SV_SMAGIC`, so 'set' magic is performed.
```
void sv_usepvn (SV* sv, char* ptr, STRLEN len)
void sv_usepvn_mg (SV *sv, char *ptr, STRLEN len)
void sv_usepvn_flags(SV *const sv, char* ptr, const STRLEN len,
const U32 flags)
```
`SvUTF8` Returns a U32 value indicating the UTF-8 status of an SV. If things are set-up properly, this indicates whether or not the SV contains UTF-8 encoded data. You should use this *after* a call to `["SvPV"](#SvPV)` or one of its variants, in case any call to string overloading updates the internal flag.
If you want to take into account the <bytes> pragma, use `["DO\_UTF8"](#DO_UTF8)` instead.
```
U32 SvUTF8(SV* sv)
```
`sv_utf8_decode` If the PV of the SV is an octet sequence in Perl's extended UTF-8 and contains a multiple-byte character, the `SvUTF8` flag is turned on so that it looks like a character. If the PV contains only single-byte characters, the `SvUTF8` flag stays off. Scans PV for validity and returns FALSE if the PV is invalid UTF-8.
```
bool sv_utf8_decode(SV *const sv)
```
`sv_utf8_downgrade` `sv_utf8_downgrade_flags`
`sv_utf8_downgrade_nomg` These attempt to convert the PV of an SV from characters to bytes. If the PV contains a character that cannot fit in a byte, this conversion will fail; in this case, `FALSE` is returned if `fail_ok` is true; otherwise they croak.
They are not a general purpose Unicode to byte encoding interface: use the `Encode` extension for that.
They differ only in that:
`sv_utf8_downgrade` processes 'get' magic on `sv`.
`sv_utf8_downgrade_nomg` does not.
`sv_utf8_downgrade_flags` has an additional `flags` parameter in which you can specify `SV_GMAGIC` to process 'get' magic, or leave it cleared to not process 'get' magic.
```
bool sv_utf8_downgrade (SV *const sv, const bool fail_ok)
bool sv_utf8_downgrade_flags(SV *const sv, const bool fail_ok,
const U32 flags)
bool sv_utf8_downgrade_nomg (SV *const sv, const bool fail_ok)
```
`sv_utf8_encode` Converts the PV of an SV to UTF-8, but then turns the `SvUTF8` flag off so that it looks like octets again.
```
void sv_utf8_encode(SV *const sv)
```
`sv_utf8_upgrade` `sv_utf8_upgrade_nomg` `sv_utf8_upgrade_flags`
`sv_utf8_upgrade_flags_grow` These convert the PV of an SV to its UTF-8-encoded form. The SV is forced to string form if it is not already. They always set the `SvUTF8` flag to avoid future validity checks even if the whole string is the same in UTF-8 as not. They return the number of bytes in the converted string
The forms differ in just two ways. The main difference is whether or not they perform 'get magic' on `sv`. `sv_utf8_upgrade_nomg` skips 'get magic'; `sv_utf8_upgrade` performs it; and `sv_utf8_upgrade_flags` and `sv_utf8_upgrade_flags_grow` either perform it (if the `SV_GMAGIC` bit is set in `flags`) or don't (if that bit is cleared).
The other difference is that `sv_utf8_upgrade_flags_grow` has an additional parameter, `extra`, which allows the caller to specify an amount of space to be reserved as spare beyond what is needed for the actual conversion. This is used when the caller knows it will soon be needing yet more space, and it is more efficient to request space from the system in a single call. This form is otherwise identical to `sv_utf8_upgrade_flags`.
These are not a general purpose byte encoding to Unicode interface: use the Encode extension for that.
The `SV_FORCE_UTF8_UPGRADE` flag is now ignored.
```
STRLEN sv_utf8_upgrade (SV *sv)
STRLEN sv_utf8_upgrade_nomg (SV *sv)
STRLEN sv_utf8_upgrade_flags (SV *const sv, const I32 flags)
STRLEN sv_utf8_upgrade_flags_grow(SV *const sv, const I32 flags,
STRLEN extra)
```
`SvUTF8_off` Unsets the UTF-8 status of an SV (the data is not changed, just the flag). Do not use frivolously.
```
void SvUTF8_off(SV *sv)
```
`SvUTF8_on` Turn on the UTF-8 status of an SV (the data is not changed, just the flag). Do not use frivolously.
```
void SvUTF8_on(SV *sv)
```
`SvUV` `SvUVx`
`SvUV_nomg` These coerce the given SV to UV and return it. The returned value in many circumstances will get stored in `sv`'s UV slot, but not in all cases. (Use `["sv\_setuv"](#sv_setuv)` to make sure it does).
`SvUVx` is different from the others in that it is guaranteed to evaluate `sv` exactly once; the others may evaluate it multiple times. Only use this form if `sv` is an expression with side effects, otherwise use the more efficient `SvUV`.
`SvUV_nomg` is the same as `SvUV`, but does not perform 'get' magic.
```
UV SvUV(SV* sv)
```
`SvUV_set` Set the value of the UV pointer in `sv` to val. See `["SvIV\_set"](#SvIV_set)`.
```
void SvUV_set(SV* sv, UV val)
```
`SvUVX` Returns the raw value in the SV's UV slot, without checks or conversions. Only use when you are sure `SvIOK` is true. See also `["SvUV"](#SvUV)`.
```
UV SvUVX(SV* sv)
```
`SvUVXx` `**DEPRECATED!**` It is planned to remove `SvUVXx` from a future release of Perl. Do not use it for new code; remove it from existing code.
This is an unnecessary synonym for ["SvUVX"](#SvUVX)
```
UV SvUVXx(SV* sv)
```
`sv_vcatpvf`
`sv_vcatpvf_mg` These process their arguments like `sv_vcatpvfn` called with a non-null C-style variable argument list, and append the formatted output to `sv`.
They differ only in that `sv_vcatpvf_mg` performs 'set' magic; `sv_vcatpvf` skips 'set' magic.
Both perform 'get' magic.
They are usually accessed via their frontends `["sv\_catpvf"](#sv_catpvf)` and `["sv\_catpvf\_mg"](#sv_catpvf_mg)`.
```
void sv_vcatpvf(SV *const sv, const char *const pat,
va_list *const args)
```
`sv_vcatpvfn`
`sv_vcatpvfn_flags` These process their arguments like `[vsprintf(3)](http://man.he.net/man3/vsprintf)` and append the formatted output to an SV. They use an array of SVs if the C-style variable argument list is missing (`NULL`). Argument reordering (using format specifiers like `%2$d` or `%*2$d`) is supported only when using an array of SVs; using a C-style `va_list` argument list with a format string that uses argument reordering will yield an exception.
When running with taint checks enabled, they indicate via `maybe_tainted` if results are untrustworthy (often due to the use of locales).
They assume that `pat` has the same utf8-ness as `sv`. It's the caller's responsibility to ensure that this is so.
They differ in that `sv_vcatpvfn_flags` has a `flags` parameter in which you can set or clear the `SV_GMAGIC` and/or SV\_SMAGIC flags, to specify which magic to handle or not handle; whereas plain `sv_vcatpvfn` always specifies both 'get' and 'set' magic.
They are usually used via one of the frontends ["`sv_vcatpvf`"](#sv_vcatpvf) and ["`sv_vcatpvf_mg`"](#sv_vcatpvf_mg).
```
void sv_vcatpvfn (SV *const sv, const char *const pat,
const STRLEN patlen, va_list *const args,
SV **const svargs, const Size_t sv_count,
bool *const maybe_tainted)
void sv_vcatpvfn_flags(SV *const sv, const char *const pat,
const STRLEN patlen, va_list *const args,
SV **const svargs, const Size_t sv_count,
bool *const maybe_tainted,
const U32 flags)
```
`SvVOK` Returns a boolean indicating whether the SV contains a v-string.
```
bool SvVOK(SV* sv)
```
`sv_vsetpvf`
`sv_vsetpvf_mg` These work like `["sv\_vcatpvf"](#sv_vcatpvf)` but copy the text into the SV instead of appending it.
They differ only in that `sv_vsetpvf_mg` performs 'set' magic; `sv_vsetpvf` skips all magic.
They are usually used via their frontends, `["sv\_setpvf"](#sv_setpvf)` and `["sv\_setpvf\_mg"](#sv_setpvf_mg)`.
```
void sv_vsetpvf(SV *const sv, const char *const pat,
va_list *const args)
```
`sv_vsetpvfn` Works like `sv_vcatpvfn` but copies the text into the SV instead of appending it.
Usually used via one of its frontends ["`sv_vsetpvf`"](#sv_vsetpvf) and ["`sv_vsetpvf_mg`"](#sv_vsetpvf_mg).
```
void sv_vsetpvfn(SV *const sv, const char *const pat,
const STRLEN patlen, va_list *const args,
SV **const svargs, const Size_t sv_count,
bool *const maybe_tainted)
```
`SvVSTRING_mg` Returns the vstring magic, or NULL if none
```
MAGIC* SvVSTRING_mg(SV * sv)
```
`vnewSVpvf` Like `["newSVpvf"](#newSVpvf)` but the arguments are an encapsulated argument list.
```
SV* vnewSVpvf(const char *const pat, va_list *const args)
```
Tainting
--------
`SvTAINT` Taints an SV if tainting is enabled, and if some input to the current expression is tainted--usually a variable, but possibly also implicit inputs such as locale settings. `SvTAINT` propagates that taintedness to the outputs of an expression in a pessimistic fashion; i.e., without paying attention to precisely which outputs are influenced by which inputs.
```
void SvTAINT(SV* sv)
```
`SvTAINTED` Checks to see if an SV is tainted. Returns TRUE if it is, FALSE if not.
```
bool SvTAINTED(SV* sv)
```
`SvTAINTED_off` Untaints an SV. Be *very* careful with this routine, as it short-circuits some of Perl's fundamental security features. XS module authors should not use this function unless they fully understand all the implications of unconditionally untainting the value. Untainting should be done in the standard perl fashion, via a carefully crafted regexp, rather than directly untainting variables.
```
void SvTAINTED_off(SV* sv)
```
`SvTAINTED_on` Marks an SV as tainted if tainting is enabled.
```
void SvTAINTED_on(SV* sv)
```
Time
----
`ASCTIME_R_PROTO` This symbol encodes the prototype of `asctime_r`. It is zero if `d_asctime_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_asctime_r` is defined.
`CTIME_R_PROTO` This symbol encodes the prototype of `ctime_r`. It is zero if `d_ctime_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_ctime_r` is defined.
`GMTIME_MAX` This symbol contains the maximum value for the `time_t` offset that the system function gmtime () accepts, and defaults to 0
`GMTIME_MIN` This symbol contains the minimum value for the `time_t` offset that the system function gmtime () accepts, and defaults to 0
`GMTIME_R_PROTO` This symbol encodes the prototype of `gmtime_r`. It is zero if `d_gmtime_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_gmtime_r` is defined.
`HAS_ASCTIME64` This symbol, if defined, indicates that the `asctime64` () routine is available to do the 64bit variant of asctime ()
`HAS_ASCTIME_R` This symbol, if defined, indicates that the `asctime_r` routine is available to asctime re-entrantly.
`HAS_CTIME64` This symbol, if defined, indicates that the `ctime64` () routine is available to do the 64bit variant of ctime ()
`HAS_CTIME_R` This symbol, if defined, indicates that the `ctime_r` routine is available to ctime re-entrantly.
`HAS_DIFFTIME` This symbol, if defined, indicates that the `difftime` routine is available.
`HAS_DIFFTIME64` This symbol, if defined, indicates that the `difftime64` () routine is available to do the 64bit variant of difftime ()
`HAS_FUTIMES` This symbol, if defined, indicates that the `futimes` routine is available to change file descriptor time stamps with `struct timevals`.
`HAS_GETITIMER` This symbol, if defined, indicates that the `getitimer` routine is available to return interval timers.
`HAS_GETTIMEOFDAY` This symbol, if defined, indicates that the `gettimeofday()` system call is available for a sub-second accuracy clock. Usually, the file *sys/resource.h* needs to be included (see `["I\_SYS\_RESOURCE"](#I_SYS_RESOURCE)`). The type "Timeval" should be used to refer to "`struct timeval`".
`HAS_GMTIME64` This symbol, if defined, indicates that the `gmtime64` () routine is available to do the 64bit variant of gmtime ()
`HAS_GMTIME_R` This symbol, if defined, indicates that the `gmtime_r` routine is available to gmtime re-entrantly.
`HAS_LOCALTIME64` This symbol, if defined, indicates that the `localtime64` () routine is available to do the 64bit variant of localtime ()
`HAS_LOCALTIME_R` This symbol, if defined, indicates that the `localtime_r` routine is available to localtime re-entrantly.
`HAS_MKTIME` This symbol, if defined, indicates that the `mktime` routine is available.
`HAS_MKTIME64` This symbol, if defined, indicates that the `mktime64` () routine is available to do the 64bit variant of mktime ()
`HAS_NANOSLEEP` This symbol, if defined, indicates that the `nanosleep` system call is available to sleep with 1E-9 sec accuracy.
`HAS_SETITIMER` This symbol, if defined, indicates that the `setitimer` routine is available to set interval timers.
`HAS_STRFTIME` This symbol, if defined, indicates that the `strftime` routine is available to do time formatting.
`HAS_TIME` This symbol, if defined, indicates that the `time()` routine exists.
`HAS_TIMEGM` This symbol, if defined, indicates that the `timegm` routine is available to do the opposite of gmtime ()
`HAS_TIMES` This symbol, if defined, indicates that the `times()` routine exists. Note that this became obsolete on some systems (`SUNOS`), which now use `getrusage()`. It may be necessary to include *sys/times.h*.
`HAS_TM_TM_GMTOFF` This symbol, if defined, indicates to the C program that the `struct tm` has a `tm_gmtoff` field.
`HAS_TM_TM_ZONE` This symbol, if defined, indicates to the C program that the `struct tm` has a `tm_zone` field.
`HAS_TZNAME` This symbol, if defined, indicates that the `tzname[]` array is available to access timezone names.
`HAS_USLEEP` This symbol, if defined, indicates that the `usleep` routine is available to let the process sleep on a sub-second accuracy.
`HAS_USLEEP_PROTO` This symbol, if defined, indicates that the system provides a prototype for the `usleep()` function. Otherwise, it is up to the program to supply one. A good guess is
```
extern int usleep(useconds_t);
```
`I_TIME` This symbol is always defined, and indicates to the C program that it should include *time.h*.
```
#ifdef I_TIME
#include <time.h>
#endif
```
`I_UTIME` This symbol, if defined, indicates to the C program that it should include *utime.h*.
```
#ifdef I_UTIME
#include <utime.h>
#endif
```
`LOCALTIME_MAX` This symbol contains the maximum value for the `time_t` offset that the system function localtime () accepts, and defaults to 0
`LOCALTIME_MIN` This symbol contains the minimum value for the `time_t` offset that the system function localtime () accepts, and defaults to 0
`LOCALTIME_R_NEEDS_TZSET` Many libc's `localtime_r` implementations do not call tzset, making them differ from `localtime()`, and making timezone changes using $`ENV`{TZ} without explicitly calling tzset impossible. This symbol makes us call tzset before `localtime_r`
`LOCALTIME_R_PROTO` This symbol encodes the prototype of `localtime_r`. It is zero if `d_localtime_r` is undef, and one of the `REENTRANT_PROTO_T_ABC` macros of *reentr.h* if `d_localtime_r` is defined.
`L_R_TZSET` If `localtime_r()` needs tzset, it is defined in this define
`mini_mktime` normalise `struct tm` values without the localtime() semantics (and overhead) of mktime().
```
void mini_mktime(struct tm *ptm)
```
`my_strftime` strftime(), but with a different API so that the return value is a pointer to the formatted result (which MUST be arranged to be FREED BY THE CALLER). This allows this function to increase the buffer size as needed, so that the caller doesn't have to worry about that.
Note that yday and wday effectively are ignored by this function, as mini\_mktime() overwrites them
Also note that this is always executed in the underlying locale of the program, giving localized results.
NOTE: `my_strftime` must be explicitly called as `Perl_my_strftime` with an `aTHX_` parameter.
```
char * Perl_my_strftime(pTHX_ const char *fmt, int sec, int min,
int hour, int mday, int mon, int year,
int wday, int yday, int isdst)
```
Typedef names
--------------
`DB_Hash_t` This symbol contains the type of the prefix structure element in the *db.h* header file. In older versions of DB, it was int, while in newer ones it is `size_t`.
`DB_Prefix_t` This symbol contains the type of the prefix structure element in the *db.h* header file. In older versions of DB, it was int, while in newer ones it is `u_int32_t`.
`Direntry_t` This symbol is set to '`struct direct`' or '`struct dirent`' depending on whether dirent is available or not. You should use this pseudo type to portably declare your directory entries.
`Fpos_t` This symbol holds the type used to declare file positions in libc. It can be `fpos_t`, long, uint, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Free_t` This variable contains the return type of `free()`. It is usually void, but occasionally int.
`Gid_t` This symbol holds the return type of `getgid()` and the type of argument to `setrgid()` and related functions. Typically, it is the type of group ids in the kernel. It can be int, ushort, `gid_t`, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Gid_t_f` This symbol defines the format string used for printing a `Gid_t`.
`Gid_t_sign` This symbol holds the signedness of a `Gid_t`. 1 for unsigned, -1 for signed.
`Gid_t_size` This symbol holds the size of a `Gid_t` in bytes.
`Groups_t` This symbol holds the type used for the second argument to `getgroups()` and `setgroups()`. Usually, this is the same as gidtype (`gid_t`) , but sometimes it isn't. It can be int, ushort, `gid_t`, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information. This is only required if you have `getgroups()` or `setgroups()`..
`Malloc_t` This symbol is the type of pointer returned by malloc and realloc.
`Mmap_t` This symbol holds the return type of the `mmap()` system call (and simultaneously the type of the first argument). Usually set to 'void \*' or '`caddr_t`'.
`Mode_t` This symbol holds the type used to declare file modes for systems calls. It is usually `mode_t`, but may be int or unsigned short. It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Netdb_hlen_t` This symbol holds the type used for the 2nd argument to `gethostbyaddr()`.
`Netdb_host_t` This symbol holds the type used for the 1st argument to `gethostbyaddr()`.
`Netdb_name_t` This symbol holds the type used for the argument to `gethostbyname()`.
`Netdb_net_t` This symbol holds the type used for the 1st argument to `getnetbyaddr()`.
`Off_t` This symbol holds the type used to declare offsets in the kernel. It can be int, long, `off_t`, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Off_t_size` This symbol holds the number of bytes used by the `Off_t`.
`Pid_t` This symbol holds the type used to declare process ids in the kernel. It can be int, uint, `pid_t`, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Rand_seed_t` This symbol defines the type of the argument of the random seed function.
`Select_fd_set_t` This symbol holds the type used for the 2nd, 3rd, and 4th arguments to select. Usually, this is '`fd_set` \*', if `HAS_FD_SET` is defined, and 'int \*' otherwise. This is only useful if you have `select()`, of course.
`Shmat_t` This symbol holds the return type of the `shmat()` system call. Usually set to 'void \*' or 'char \*'.
`Signal_t` This symbol's value is either "void" or "int", corresponding to the appropriate return type of a signal handler. Thus, you can declare a signal handler using "`Signal_t` (\*handler)()", and define the handler using "`Signal_t` `handler(sig)`".
`Size_t` This symbol holds the type used to declare length parameters for string functions. It is usually `size_t`, but may be unsigned long, int, etc. It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Size_t_size` This symbol holds the size of a `Size_t` in bytes.
`Sock_size_t` This symbol holds the type used for the size argument of various socket calls (just the base type, not the pointer-to).
`SSize_t` This symbol holds the type used by functions that return a count of bytes or an error condition. It must be a signed type. It is usually `ssize_t`, but may be long or int, etc. It may be necessary to include *sys/types.h* or *unistd.h* to get any typedef'ed information. We will pick a type such that `sizeof(SSize_t)` == `sizeof(Size_t)`.
`Time_t` This symbol holds the type returned by `time()`. It can be long, or `time_t` on `BSD` sites (in which case *sys/types.h* should be included).
`Uid_t` This symbol holds the type used to declare user ids in the kernel. It can be int, ushort, `uid_t`, etc... It may be necessary to include *sys/types.h* to get any typedef'ed information.
`Uid_t_f` This symbol defines the format string used for printing a `Uid_t`.
`Uid_t_sign` This symbol holds the signedness of a `Uid_t`. 1 for unsigned, -1 for signed.
`Uid_t_size` This symbol holds the size of a `Uid_t` in bytes.
Unicode Support
----------------
["Unicode Support" in perlguts](perlguts#Unicode-Support) has an introduction to this API.
See also `["Character classification"](#Character-classification)`, `["Character case changing"](#Character-case-changing)`, and `["String Handling"](#String-Handling)`. Various functions outside this section also work specially with Unicode. Search for the string "utf8" in this document.
`BOM_UTF8` This is a macro that evaluates to a string constant of the UTF-8 bytes that define the Unicode BYTE ORDER MARK (U+FEFF) for the platform that perl is compiled on. This allows code to use a mnemonic for this character that works on both ASCII and EBCDIC platforms. `sizeof(BOM_UTF8) - 1` can be used to get its length in bytes.
`bytes_cmp_utf8` Compares the sequence of characters (stored as octets) in `b`, `blen` with the sequence of characters (stored as UTF-8) in `u`, `ulen`. Returns 0 if they are equal, -1 or -2 if the first string is less than the second string, +1 or +2 if the first string is greater than the second string.
-1 or +1 is returned if the shorter string was identical to the start of the longer string. -2 or +2 is returned if there was a difference between characters within the strings.
```
int bytes_cmp_utf8(const U8 *b, STRLEN blen, const U8 *u,
STRLEN ulen)
```
`bytes_from_utf8` NOTE: `bytes_from_utf8` is **experimental** and may change or be removed without notice.
Converts a potentially UTF-8 encoded string `s` of length `*lenp` into native byte encoding. On input, the boolean `*is_utf8p` gives whether or not `s` is actually encoded in UTF-8.
Unlike ["utf8\_to\_bytes"](#utf8_to_bytes) but like ["bytes\_to\_utf8"](#bytes_to_utf8), this is non-destructive of the input string.
Do nothing if `*is_utf8p` is 0, or if there are code points in the string not expressible in native byte encoding. In these cases, `*is_utf8p` and `*lenp` are unchanged, and the return value is the original `s`.
Otherwise, `*is_utf8p` is set to 0, and the return value is a pointer to a newly created string containing a downgraded copy of `s`, and whose length is returned in `*lenp`, updated. The new string is `NUL`-terminated. The caller is responsible for arranging for the memory used by this string to get freed.
Upon successful return, the number of variants in the string can be computed by having saved the value of `*lenp` before the call, and subtracting the after-call value of `*lenp` from it.
```
U8* bytes_from_utf8(const U8 *s, STRLEN *lenp, bool *is_utf8p)
```
`bytes_to_utf8` NOTE: `bytes_to_utf8` is **experimental** and may change or be removed without notice.
Converts a string `s` of length `*lenp` bytes from the native encoding into UTF-8. Returns a pointer to the newly-created string, and sets `*lenp` to reflect the new length in bytes. The caller is responsible for arranging for the memory used by this string to get freed.
Upon successful return, the number of variants in the string can be computed by having saved the value of `*lenp` before the call, and subtracting it from the after-call value of `*lenp`.
A `NUL` character will be written after the end of the string.
If you want to convert to UTF-8 from encodings other than the native (Latin1 or EBCDIC), see ["sv\_recode\_to\_utf8"](#sv_recode_to_utf8)().
```
U8* bytes_to_utf8(const U8 *s, STRLEN *lenp)
```
`DO_UTF8` Returns a bool giving whether or not the PV in `sv` is to be treated as being encoded in UTF-8.
You should use this *after* a call to `SvPV()` or one of its variants, in case any call to string overloading updates the internal UTF-8 encoding flag.
```
bool DO_UTF8(SV* sv)
```
`foldEQ_utf8` Returns true if the leading portions of the strings `s1` and `s2` (either or both of which may be in UTF-8) are the same case-insensitively; false otherwise. How far into the strings to compare is determined by other input parameters.
If `u1` is true, the string `s1` is assumed to be in UTF-8-encoded Unicode; otherwise it is assumed to be in native 8-bit encoding. Correspondingly for `u2` with respect to `s2`.
If the byte length `l1` is non-zero, it says how far into `s1` to check for fold equality. In other words, `s1`+`l1` will be used as a goal to reach. The scan will not be considered to be a match unless the goal is reached, and scanning won't continue past that goal. Correspondingly for `l2` with respect to `s2`.
If `pe1` is non-`NULL` and the pointer it points to is not `NULL`, that pointer is considered an end pointer to the position 1 byte past the maximum point in `s1` beyond which scanning will not continue under any circumstances. (This routine assumes that UTF-8 encoded input strings are not malformed; malformed input can cause it to read past `pe1`). This means that if both `l1` and `pe1` are specified, and `pe1` is less than `s1`+`l1`, the match will never be successful because it can never get as far as its goal (and in fact is asserted against). Correspondingly for `pe2` with respect to `s2`.
At least one of `s1` and `s2` must have a goal (at least one of `l1` and `l2` must be non-zero), and if both do, both have to be reached for a successful match. Also, if the fold of a character is multiple characters, all of them must be matched (see tr21 reference below for 'folding').
Upon a successful match, if `pe1` is non-`NULL`, it will be set to point to the beginning of the *next* character of `s1` beyond what was matched. Correspondingly for `pe2` and `s2`.
For case-insensitiveness, the "casefolding" of Unicode is used instead of upper/lowercasing both the characters, see <https://www.unicode.org/reports/tr21/> (Case Mappings).
```
I32 foldEQ_utf8(const char *s1, char **pe1, UV l1, bool u1,
const char *s2, char **pe2, UV l2, bool u2)
```
`is_ascii_string` This is a misleadingly-named synonym for ["is\_utf8\_invariant\_string"](#is_utf8_invariant_string). On ASCII-ish platforms, the name isn't misleading: the ASCII-range characters are exactly the UTF-8 invariants. But EBCDIC machines have more invariants than just the ASCII characters, so `is_utf8_invariant_string` is preferred.
```
bool is_ascii_string(const U8* const s, STRLEN len)
```
`is_c9strict_utf8_string` Returns TRUE if the first `len` bytes of string `s` form a valid UTF-8-encoded string that conforms to [Unicode Corrigendum #9](http://www.unicode.org/versions/corrigendum9.html); otherwise it returns FALSE. If `len` is 0, it will be calculated using `strlen(s)` (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte). Note that all characters being ASCII constitute 'a valid UTF-8 string'.
This function returns FALSE for strings containing any code points above the Unicode max of 0x10FFFF or surrogate code points, but accepts non-character code points per [Corrigendum #9](http://www.unicode.org/versions/corrigendum9.html).
See also `["is\_utf8\_invariant\_string"](#is_utf8_invariant_string)`, `["is\_utf8\_invariant\_string\_loc"](#is_utf8_invariant_string_loc)`, `["is\_utf8\_string"](#is_utf8_string)`, `["is\_utf8\_string\_flags"](#is_utf8_string_flags)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, `["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags)`, `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`, `["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags)`, `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)`, `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)`, `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`, `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`, `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`, `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)`, `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`, and `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)`.
```
bool is_c9strict_utf8_string(const U8 *s, STRLEN len)
```
`is_c9strict_utf8_string_loc` Like `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer.
See also `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)`.
```
bool is_c9strict_utf8_string_loc(const U8 *s, STRLEN len,
const U8 **ep)
```
`is_c9strict_utf8_string_loclen` Like `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer, and the number of UTF-8 encoded characters in the `el` pointer.
See also `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`.
```
bool is_c9strict_utf8_string_loclen(const U8 *s, STRLEN len,
const U8 **ep, STRLEN *el)
```
`isC9_STRICT_UTF8_CHAR` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8 that represents some Unicode non-surrogate code point; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation. Any bytes remaining before `e`, but beyond the ones needed to form the first code point in `s`, are not examined.
The largest acceptable code point is the Unicode maximum 0x10FFFF. This differs from `["isSTRICT\_UTF8\_CHAR"](#isSTRICT_UTF8_CHAR)` only in that it accepts non-character code points. This corresponds to [Unicode Corrigendum #9](http://www.unicode.org/versions/corrigendum9.html). which said that non-character code points are merely discouraged rather than completely forbidden in open interchange. See ["Noncharacter code points" in perlunicode](perlunicode#Noncharacter-code-points).
Use `["isUTF8\_CHAR"](#isUTF8_CHAR)` to check for Perl's extended UTF-8; and `["isUTF8\_CHAR\_flags"](#isUTF8_CHAR_flags)` for a more customized definition.
Use `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`, `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`, and `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)` to check entire strings.
```
Size_t isC9_STRICT_UTF8_CHAR(const U8 * const s0,
const U8 * const e)
```
`is_invariant_string` This is a somewhat misleadingly-named synonym for ["is\_utf8\_invariant\_string"](#is_utf8_invariant_string). `is_utf8_invariant_string` is preferred, as it indicates under what conditions the string is invariant.
```
bool is_invariant_string(const U8* const s, STRLEN len)
```
`isSTRICT_UTF8_CHAR` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8 that represents some Unicode code point completely acceptable for open interchange between all applications; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation. Any bytes remaining before `e`, but beyond the ones needed to form the first code point in `s`, are not examined.
The largest acceptable code point is the Unicode maximum 0x10FFFF, and must not be a surrogate nor a non-character code point. Thus this excludes any code point from Perl's extended UTF-8.
This is used to efficiently decide if the next few bytes in `s` is legal Unicode-acceptable UTF-8 for a single character.
Use `["isC9\_STRICT\_UTF8\_CHAR"](#isC9_STRICT_UTF8_CHAR)` to use the [Unicode Corrigendum #9](http://www.unicode.org/versions/corrigendum9.html) definition of allowable code points; `["isUTF8\_CHAR"](#isUTF8_CHAR)` to check for Perl's extended UTF-8; and `["isUTF8\_CHAR\_flags"](#isUTF8_CHAR_flags)` for a more customized definition.
Use `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`, `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`, and `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)` to check entire strings.
```
Size_t isSTRICT_UTF8_CHAR(const U8 * const s0,
const U8 * const e)
```
`is_strict_utf8_string` Returns TRUE if the first `len` bytes of string `s` form a valid UTF-8-encoded string that is fully interchangeable by any application using Unicode rules; otherwise it returns FALSE. If `len` is 0, it will be calculated using `strlen(s)` (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte). Note that all characters being ASCII constitute 'a valid UTF-8 string'.
This function returns FALSE for strings containing any code points above the Unicode max of 0x10FFFF, surrogate code points, or non-character code points.
See also `["is\_utf8\_invariant\_string"](#is_utf8_invariant_string)`, `["is\_utf8\_invariant\_string\_loc"](#is_utf8_invariant_string_loc)`, `["is\_utf8\_string"](#is_utf8_string)`, `["is\_utf8\_string\_flags"](#is_utf8_string_flags)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, `["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags)`, `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`, `["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags)`, `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)`, `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)`, `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`, `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`, `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)`, `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`, `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`, and `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)`.
```
bool is_strict_utf8_string(const U8 *s, STRLEN len)
```
`is_strict_utf8_string_loc` Like `["is\_strict\_utf8\_string"](#is_strict_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer.
See also `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)`.
```
bool is_strict_utf8_string_loc(const U8 *s, STRLEN len,
const U8 **ep)
```
`is_strict_utf8_string_loclen` Like `["is\_strict\_utf8\_string"](#is_strict_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer, and the number of UTF-8 encoded characters in the `el` pointer.
See also `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`.
```
bool is_strict_utf8_string_loclen(const U8 *s, STRLEN len,
const U8 **ep, STRLEN *el)
```
`is_utf8_char` `**DEPRECATED!**` It is planned to remove `is_utf8_char` from a future release of Perl. Do not use it for new code; remove it from existing code.
Tests if some arbitrary number of bytes begins in a valid UTF-8 character. Note that an INVARIANT (i.e. ASCII on non-EBCDIC machines) character is a valid UTF-8 character. The actual number of bytes in the UTF-8 character will be returned if it is valid, otherwise 0.
This function is deprecated due to the possibility that malformed input could cause reading beyond the end of the input buffer. Use ["isUTF8\_CHAR"](#isUTF8_CHAR) instead.
```
STRLEN is_utf8_char(const U8 *s)
```
`is_utf8_char_buf` This is identical to the macro ["isUTF8\_CHAR" in perlapi](perlapi#isUTF8_CHAR).
```
STRLEN is_utf8_char_buf(const U8 *buf, const U8 *buf_end)
```
`is_utf8_fixed_width_buf_flags` Returns TRUE if the fixed-width buffer starting at `s` with length `len` is entirely valid UTF-8, subject to the restrictions given by `flags`; otherwise it returns FALSE.
If `flags` is 0, any well-formed UTF-8, as extended by Perl, is accepted without restriction. If the final few bytes of the buffer do not form a complete code point, this will return TRUE anyway, provided that `["is\_utf8\_valid\_partial\_char\_flags"](#is_utf8_valid_partial_char_flags)` returns TRUE for them.
If `flags` in non-zero, it can be any combination of the `UTF8_DISALLOW_*foo*` flags accepted by `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)`, and with the same meanings.
This function differs from `["is\_utf8\_string\_flags"](#is_utf8_string_flags)` only in that the latter returns FALSE if the final few bytes of the string don't form a complete code point.
```
bool is_utf8_fixed_width_buf_flags(const U8 * const s,
STRLEN len, const U32 flags)
```
`is_utf8_fixed_width_buf_loclen_flags` Like `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)` but stores the number of complete, valid characters found in the `el` pointer.
```
bool is_utf8_fixed_width_buf_loclen_flags(const U8 * const s,
STRLEN len,
const U8 **ep,
STRLEN *el,
const U32 flags)
```
`is_utf8_fixed_width_buf_loc_flags` Like `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)` but stores the location of the failure in the `ep` pointer. If the function returns TRUE, `*ep` will point to the beginning of any partial character at the end of the buffer; if there is no partial character `*ep` will contain `s`+`len`.
See also `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`.
```
bool is_utf8_fixed_width_buf_loc_flags(const U8 * const s,
STRLEN len, const U8 **ep,
const U32 flags)
```
`is_utf8_invariant_string` Returns TRUE if the first `len` bytes of the string `s` are the same regardless of the UTF-8 encoding of the string (or UTF-EBCDIC encoding on EBCDIC machines); otherwise it returns FALSE. That is, it returns TRUE if they are UTF-8 invariant. On ASCII-ish machines, all the ASCII characters and only the ASCII characters fit this definition. On EBCDIC machines, the ASCII-range characters are invariant, but so also are the C1 controls.
If `len` is 0, it will be calculated using `strlen(s)`, (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte).
See also `["is\_utf8\_string"](#is_utf8_string)`, `["is\_utf8\_string\_flags"](#is_utf8_string_flags)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, `["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags)`, `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`, `["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags)`, `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)`, `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)`, `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`, `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`, `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`, `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)`, `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`, `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`, and `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)`.
```
bool is_utf8_invariant_string(const U8* const s, STRLEN len)
```
`is_utf8_invariant_string_loc` Like `["is\_utf8\_invariant\_string"](#is_utf8_invariant_string)` but upon failure, stores the location of the first UTF-8 variant character in the `ep` pointer; if all characters are UTF-8 invariant, this function does not change the contents of `*ep`.
```
bool is_utf8_invariant_string_loc(const U8* const s, STRLEN len,
const U8 ** ep)
```
`is_utf8_string` Returns TRUE if the first `len` bytes of string `s` form a valid Perl-extended-UTF-8 string; returns FALSE otherwise. If `len` is 0, it will be calculated using `strlen(s)` (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte). Note that all characters being ASCII constitute 'a valid UTF-8 string'.
This function considers Perl's extended UTF-8 to be valid. That means that code points above Unicode, surrogates, and non-character code points are considered valid by this function. Use `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`, `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`, or `["is\_utf8\_string\_flags"](#is_utf8_string_flags)` to restrict what code points are considered valid.
See also `["is\_utf8\_invariant\_string"](#is_utf8_invariant_string)`, `["is\_utf8\_invariant\_string\_loc"](#is_utf8_invariant_string_loc)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`, `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)`, `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)`, `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`,
```
bool is_utf8_string(const U8 *s, STRLEN len)
```
`is_utf8_string_flags` Returns TRUE if the first `len` bytes of string `s` form a valid UTF-8 string, subject to the restrictions imposed by `flags`; returns FALSE otherwise. If `len` is 0, it will be calculated using `strlen(s)` (which means if you use this option, that `s` can't have embedded `NUL` characters and has to have a terminating `NUL` byte). Note that all characters being ASCII constitute 'a valid UTF-8 string'.
If `flags` is 0, this gives the same results as `["is\_utf8\_string"](#is_utf8_string)`; if `flags` is `UTF8_DISALLOW_ILLEGAL_INTERCHANGE`, this gives the same results as `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`; and if `flags` is `UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE`, this gives the same results as `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`. Otherwise `flags` may be any combination of the `UTF8_DISALLOW_*foo*` flags understood by `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)`, with the same meanings.
See also `["is\_utf8\_invariant\_string"](#is_utf8_invariant_string)`, `["is\_utf8\_invariant\_string\_loc"](#is_utf8_invariant_string_loc)`, `["is\_utf8\_string"](#is_utf8_string)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, `["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags)`, `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`, `["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags)`, `["is\_utf8\_fixed\_width\_buf\_flags"](#is_utf8_fixed_width_buf_flags)`, `["is\_utf8\_fixed\_width\_buf\_loc\_flags"](#is_utf8_fixed_width_buf_loc_flags)`, `["is\_utf8\_fixed\_width\_buf\_loclen\_flags"](#is_utf8_fixed_width_buf_loclen_flags)`, `["is\_strict\_utf8\_string"](#is_strict_utf8_string)`, `["is\_strict\_utf8\_string\_loc"](#is_strict_utf8_string_loc)`, `["is\_strict\_utf8\_string\_loclen"](#is_strict_utf8_string_loclen)`, `["is\_c9strict\_utf8\_string"](#is_c9strict_utf8_string)`, `["is\_c9strict\_utf8\_string\_loc"](#is_c9strict_utf8_string_loc)`, and `["is\_c9strict\_utf8\_string\_loclen"](#is_c9strict_utf8_string_loclen)`.
```
bool is_utf8_string_flags(const U8 *s, STRLEN len,
const U32 flags)
```
`is_utf8_string_loc` Like `["is\_utf8\_string"](#is_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer.
See also `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)`.
```
bool is_utf8_string_loc(const U8 *s, const STRLEN len,
const U8 **ep)
```
`is_utf8_string_loclen` Like `["is\_utf8\_string"](#is_utf8_string)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer, and the number of UTF-8 encoded characters in the `el` pointer.
See also `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`.
```
bool is_utf8_string_loclen(const U8 *s, STRLEN len,
const U8 **ep, STRLEN *el)
```
`is_utf8_string_loclen_flags` Like `["is\_utf8\_string\_flags"](#is_utf8_string_flags)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer, and the number of UTF-8 encoded characters in the `el` pointer.
See also `["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags)`.
```
bool is_utf8_string_loclen_flags(const U8 *s, STRLEN len,
const U8 **ep, STRLEN *el,
const U32 flags)
```
`is_utf8_string_loc_flags` Like `["is\_utf8\_string\_flags"](#is_utf8_string_flags)` but stores the location of the failure (in the case of "utf8ness failure") or the location `s`+`len` (in the case of "utf8ness success") in the `ep` pointer.
See also `["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags)`.
```
bool is_utf8_string_loc_flags(const U8 *s, STRLEN len,
const U8 **ep, const U32 flags)
```
`is_utf8_valid_partial_char` Returns 0 if the sequence of bytes starting at `s` and looking no further than `e - 1` is the UTF-8 encoding, as extended by Perl, for one or more code points. Otherwise, it returns 1 if there exists at least one non-empty sequence of bytes that when appended to sequence `s`, starting at position `e` causes the entire sequence to be the well-formed UTF-8 of some code point; otherwise returns 0.
In other words this returns TRUE if `s` points to a partial UTF-8-encoded code point.
This is useful when a fixed-length buffer is being tested for being well-formed UTF-8, but the final few bytes in it don't comprise a full character; that is, it is split somewhere in the middle of the final code point's UTF-8 representation. (Presumably when the buffer is refreshed with the next chunk of data, the new first bytes will complete the partial code point.) This function is used to verify that the final bytes in the current buffer are in fact the legal beginning of some code point, so that if they aren't, the failure can be signalled without having to wait for the next read.
```
bool is_utf8_valid_partial_char(const U8 * const s0,
const U8 * const e)
```
`is_utf8_valid_partial_char_flags` Like `["is\_utf8\_valid\_partial\_char"](#is_utf8_valid_partial_char)`, it returns a boolean giving whether or not the input is a valid UTF-8 encoded partial character, but it takes an extra parameter, `flags`, which can further restrict which code points are considered valid.
If `flags` is 0, this behaves identically to `["is\_utf8\_valid\_partial\_char"](#is_utf8_valid_partial_char)`. Otherwise `flags` can be any combination of the `UTF8_DISALLOW_*foo*` flags accepted by `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)`. If there is any sequence of bytes that can complete the input partial character in such a way that a non-prohibited character is formed, the function returns TRUE; otherwise FALSE. Non character code points cannot be determined based on partial character input. But many of the other possible excluded types can be determined from just the first one or two bytes.
```
bool is_utf8_valid_partial_char_flags(const U8 * const s0,
const U8 * const e,
const U32 flags)
```
`isUTF8_CHAR` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8, as extended by Perl, that represents some code point; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation. Any bytes remaining before `e`, but beyond the ones needed to form the first code point in `s`, are not examined.
The code point can be any that will fit in an IV on this machine, using Perl's extension to official UTF-8 to represent those higher than the Unicode maximum of 0x10FFFF. That means that this macro is used to efficiently decide if the next few bytes in `s` is legal UTF-8 for a single character.
Use `["isSTRICT\_UTF8\_CHAR"](#isSTRICT_UTF8_CHAR)` to restrict the acceptable code points to those defined by Unicode to be fully interchangeable across applications; `["isC9\_STRICT\_UTF8\_CHAR"](#isC9_STRICT_UTF8_CHAR)` to use the [Unicode Corrigendum #9](http://www.unicode.org/versions/corrigendum9.html) definition of allowable code points; and `["isUTF8\_CHAR\_flags"](#isUTF8_CHAR_flags)` for a more customized definition.
Use `["is\_utf8\_string"](#is_utf8_string)`, `["is\_utf8\_string\_loc"](#is_utf8_string_loc)`, and `["is\_utf8\_string\_loclen"](#is_utf8_string_loclen)` to check entire strings.
Note also that a UTF-8 "invariant" character (i.e. ASCII on non-EBCDIC machines) is a valid UTF-8 character.
```
Size_t isUTF8_CHAR(const U8 * const s0, const U8 * const e)
```
`isUTF8_CHAR_flags` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8, as extended by Perl, that represents some code point, subject to the restrictions given by `flags`; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation. Any bytes remaining before `e`, but beyond the ones needed to form the first code point in `s`, are not examined.
If `flags` is 0, this gives the same results as `["isUTF8\_CHAR"](#isUTF8_CHAR)`; if `flags` is `UTF8_DISALLOW_ILLEGAL_INTERCHANGE`, this gives the same results as `["isSTRICT\_UTF8\_CHAR"](#isSTRICT_UTF8_CHAR)`; and if `flags` is `UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE`, this gives the same results as `["isC9\_STRICT\_UTF8\_CHAR"](#isC9_STRICT_UTF8_CHAR)`. Otherwise `flags` may be any combination of the `UTF8_DISALLOW_*foo*` flags understood by `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)`, with the same meanings.
The three alternative macros are for the most commonly needed validations; they are likely to run somewhat faster than this more general one, as they can be inlined into your code.
Use ["is\_utf8\_string\_flags"](#is_utf8_string_flags), ["is\_utf8\_string\_loc\_flags"](#is_utf8_string_loc_flags), and ["is\_utf8\_string\_loclen\_flags"](#is_utf8_string_loclen_flags) to check entire strings.
```
Size_t isUTF8_CHAR_flags(const U8 * const s0, const U8 * const e,
const U32 flags)
```
`LATIN1_TO_NATIVE` Returns the native equivalent of the input Latin-1 code point (including ASCII and control characters) given by `ch`. Thus, `LATIN1_TO_NATIVE(66)` on EBCDIC platforms returns 194. These each represent the character `"B"` on their respective platforms. On ASCII platforms no conversion is needed, so this macro expands to just its input, adding no time nor space requirements to the implementation.
For conversion of code points potentially larger than will fit in a character, use ["UNI\_TO\_NATIVE"](#UNI_TO_NATIVE).
```
U8 LATIN1_TO_NATIVE(U8 ch)
```
`NATIVE_TO_LATIN1` Returns the Latin-1 (including ASCII and control characters) equivalent of the input native code point given by `ch`. Thus, `NATIVE_TO_LATIN1(193)` on EBCDIC platforms returns 65. These each represent the character `"A"` on their respective platforms. On ASCII platforms no conversion is needed, so this macro expands to just its input, adding no time nor space requirements to the implementation.
For conversion of code points potentially larger than will fit in a character, use ["NATIVE\_TO\_UNI"](#NATIVE_TO_UNI).
```
U8 NATIVE_TO_LATIN1(U8 ch)
```
`NATIVE_TO_UNI` Returns the Unicode equivalent of the input native code point given by `ch`. Thus, `NATIVE_TO_UNI(195)` on EBCDIC platforms returns 67. These each represent the character `"C"` on their respective platforms. On ASCII platforms no conversion is needed, so this macro expands to just its input, adding no time nor space requirements to the implementation.
```
UV NATIVE_TO_UNI(UV ch)
```
`pv_uni_display` Build to the scalar `dsv` a displayable version of the UTF-8 encoded string `spv`, length `len`, the displayable version being at most `pvlim` bytes long (if longer, the rest is truncated and `"..."` will be appended).
The `flags` argument can have `UNI_DISPLAY_ISPRINT` set to display `isPRINT()`able characters as themselves, `UNI_DISPLAY_BACKSLASH` to display the `\\[nrfta\\]` as the backslashed versions (like `"\n"`) (`UNI_DISPLAY_BACKSLASH` is preferred over `UNI_DISPLAY_ISPRINT` for `"\\"`). `UNI_DISPLAY_QQ` (and its alias `UNI_DISPLAY_REGEX`) have both `UNI_DISPLAY_BACKSLASH` and `UNI_DISPLAY_ISPRINT` turned on.
Additionally, there is now `UNI_DISPLAY_BACKSPACE` which allows `\b` for a backspace, but only when `UNI_DISPLAY_BACKSLASH` also is set.
The pointer to the PV of the `dsv` is returned.
See also ["sv\_uni\_display"](#sv_uni_display).
```
char* pv_uni_display(SV *dsv, const U8 *spv, STRLEN len,
STRLEN pvlim, UV flags)
```
`REPLACEMENT_CHARACTER_UTF8` This is a macro that evaluates to a string constant of the UTF-8 bytes that define the Unicode REPLACEMENT CHARACTER (U+FFFD) for the platform that perl is compiled on. This allows code to use a mnemonic for this character that works on both ASCII and EBCDIC platforms. `sizeof(REPLACEMENT_CHARACTER_UTF8) - 1` can be used to get its length in bytes.
`sv_cat_decode` `encoding` is assumed to be an `Encode` object, the PV of `ssv` is assumed to be octets in that encoding and decoding the input starts from the position which `(PV + *offset)` pointed to. `dsv` will be concatenated with the decoded UTF-8 string from `ssv`. Decoding will terminate when the string `tstr` appears in decoding output or the input ends on the PV of `ssv`. The value which `offset` points will be modified to the last input position on `ssv`.
Returns TRUE if the terminator was found, else returns FALSE.
```
bool sv_cat_decode(SV* dsv, SV *encoding, SV *ssv, int *offset,
char* tstr, int tlen)
```
`sv_recode_to_utf8` `encoding` is assumed to be an `Encode` object, on entry the PV of `sv` is assumed to be octets in that encoding, and `sv` will be converted into Unicode (and UTF-8).
If `sv` already is UTF-8 (or if it is not `POK`), or if `encoding` is not a reference, nothing is done to `sv`. If `encoding` is not an `Encode::XS` Encoding object, bad things will happen. (See <encoding> and [Encode](encode).)
The PV of `sv` is returned.
```
char* sv_recode_to_utf8(SV* sv, SV *encoding)
```
`sv_uni_display` Build to the scalar `dsv` a displayable version of the scalar `sv`, the displayable version being at most `pvlim` bytes long (if longer, the rest is truncated and "..." will be appended).
The `flags` argument is as in ["pv\_uni\_display"](#pv_uni_display)().
The pointer to the PV of the `dsv` is returned.
```
char* sv_uni_display(SV *dsv, SV *ssv, STRLEN pvlim, UV flags)
```
`UNICODE_IS_NONCHAR` Returns a boolean as to whether or not `uv` is one of the Unicode non-character code points
```
bool UNICODE_IS_NONCHAR(const UV uv)
```
`UNICODE_IS_REPLACEMENT` Returns a boolean as to whether or not `uv` is the Unicode REPLACEMENT CHARACTER
```
bool UNICODE_IS_REPLACEMENT(const UV uv)
```
`UNICODE_IS_SUPER` Returns a boolean as to whether or not `uv` is above the maximum legal Unicode code point of U+10FFFF.
```
bool UNICODE_IS_SUPER(const UV uv)
```
`UNICODE_IS_SURROGATE` Returns a boolean as to whether or not `uv` is one of the Unicode surrogate code points
```
bool UNICODE_IS_SURROGATE(const UV uv)
```
`UNICODE_REPLACEMENT` Evaluates to 0xFFFD, the code point of the Unicode REPLACEMENT CHARACTER
`UNI_TO_NATIVE` Returns the native equivalent of the input Unicode code point given by `ch`. Thus, `UNI_TO_NATIVE(68)` on EBCDIC platforms returns 196. These each represent the character `"D"` on their respective platforms. On ASCII platforms no conversion is needed, so this macro expands to just its input, adding no time nor space requirements to the implementation.
```
UV UNI_TO_NATIVE(UV ch)
```
`utf8n_to_uvchr` THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES. Most code should use ["utf8\_to\_uvchr\_buf"](#utf8_to_uvchr_buf)() rather than call this directly.
Bottom level UTF-8 decode routine. Returns the native code point value of the first character in the string `s`, which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than `curlen` bytes; `*retlen` (if `retlen` isn't NULL) will be set to the length, in bytes, of that character.
The value of `flags` determines the behavior when `s` does not point to a well-formed UTF-8 character. If `flags` is 0, encountering a malformation causes zero to be returned and `*retlen` is set so that (`s` + `*retlen`) is the next possible position in `s` that could begin a non-malformed character. Also, if UTF-8 warnings haven't been lexically disabled, a warning is raised. Some UTF-8 input sequences may contain multiple malformations. This function tries to find every possible one in each call, so multiple warnings can be raised for the same sequence.
Various ALLOW flags can be set in `flags` to allow (and not warn on) individual types of malformations, such as the sequence being overlong (that is, when there is a shorter sequence that can express the same code point; overlong sequences are expressly forbidden in the UTF-8 standard due to potential security issues). Another malformation example is the first byte of a character not being a legal first byte. See *utf8.h* for the list of such flags. Even if allowed, this function generally returns the Unicode REPLACEMENT CHARACTER when it encounters a malformation. There are flags in *utf8.h* to override this behavior for the overlong malformations, but don't do that except for very specialized purposes.
The `UTF8_CHECK_ONLY` flag overrides the behavior when a non-allowed (by other flags) malformation is found. If this flag is set, the routine assumes that the caller will raise a warning, and this function will silently just set `retlen` to `-1` (cast to `STRLEN`) and return zero.
Note that this API requires disambiguation between successful decoding a `NUL` character, and an error return (unless the `UTF8_CHECK_ONLY` flag is set), as in both cases, 0 is returned, and, depending on the malformation, `retlen` may be set to 1. To disambiguate, upon a zero return, see if the first byte of `s` is 0 as well. If so, the input was a `NUL`; if not, the input had an error. Or you can use `["utf8n\_to\_uvchr\_error"](#utf8n_to_uvchr_error)`.
Certain code points are considered problematic. These are Unicode surrogates, Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF. By default these are considered regular code points, but certain situations warrant special handling for them, which can be specified using the `flags` parameter. If `flags` contains `UTF8_DISALLOW_ILLEGAL_INTERCHANGE`, all three classes are treated as malformations and handled as such. The flags `UTF8_DISALLOW_SURROGATE`, `UTF8_DISALLOW_NONCHAR`, and `UTF8_DISALLOW_SUPER` (meaning above the legal Unicode maximum) can be set to disallow these categories individually. `UTF8_DISALLOW_ILLEGAL_INTERCHANGE` restricts the allowed inputs to the strict UTF-8 traditionally defined by Unicode. Use `UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE` to use the strictness definition given by [Unicode Corrigendum #9](https://www.unicode.org/versions/corrigendum9.html). The difference between traditional strictness and C9 strictness is that the latter does not forbid non-character code points. (They are still discouraged, however.) For more discussion see ["Noncharacter code points" in perlunicode](perlunicode#Noncharacter-code-points).
The flags `UTF8_WARN_ILLEGAL_INTERCHANGE`, `UTF8_WARN_ILLEGAL_C9_INTERCHANGE`, `UTF8_WARN_SURROGATE`, `UTF8_WARN_NONCHAR`, and `UTF8_WARN_SUPER` will cause warning messages to be raised for their respective categories, but otherwise the code points are considered valid (not malformations). To get a category to both be treated as a malformation and raise a warning, specify both the WARN and DISALLOW flags. (But note that warnings are not raised if lexically disabled nor if `UTF8_CHECK_ONLY` is also specified.)
Extremely high code points were never specified in any standard, and require an extension to UTF-8 to express, which Perl does. It is likely that programs written in something other than Perl would not be able to read files that contain these; nor would Perl understand files written by something that uses a different extension. For these reasons, there is a separate set of flags that can warn and/or disallow these extremely high code points, even if other above-Unicode ones are accepted. They are the `UTF8_WARN_PERL_EXTENDED` and `UTF8_DISALLOW_PERL_EXTENDED` flags. For more information see `["UTF8\_GOT\_PERL\_EXTENDED"](#UTF8_GOT_PERL_EXTENDED)`. Of course `UTF8_DISALLOW_SUPER` will treat all above-Unicode code points, including these, as malformations. (Note that the Unicode standard considers anything above 0x10FFFF to be illegal, but there are standards predating it that allow up to 0x7FFF\_FFFF (2\*\*31 -1))
A somewhat misleadingly named synonym for `UTF8_WARN_PERL_EXTENDED` is retained for backward compatibility: `UTF8_WARN_ABOVE_31_BIT`. Similarly, `UTF8_DISALLOW_ABOVE_31_BIT` is usable instead of the more accurately named `UTF8_DISALLOW_PERL_EXTENDED`. The names are misleading because these flags can apply to code points that actually do fit in 31 bits. This happens on EBCDIC platforms, and sometimes when the [overlong malformation](#UTF8_GOT_LONG) is also present. The new names accurately describe the situation in all cases.
All other code points corresponding to Unicode characters, including private use and those yet to be assigned, are never considered malformed and never warn.
```
UV utf8n_to_uvchr(const U8 *s, STRLEN curlen, STRLEN *retlen,
const U32 flags)
```
`utf8n_to_uvchr_error` THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES. Most code should use ["utf8\_to\_uvchr\_buf"](#utf8_to_uvchr_buf)() rather than call this directly.
This function is for code that needs to know what the precise malformation(s) are when an error is found. If you also need to know the generated warning messages, use ["utf8n\_to\_uvchr\_msgs"](#utf8n_to_uvchr_msgs)() instead.
It is like `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)` but it takes an extra parameter placed after all the others, `errors`. If this parameter is 0, this function behaves identically to `["utf8n\_to\_uvchr"](#utf8n_to_uvchr)`. Otherwise, `errors` should be a pointer to a `U32` variable, which this function sets to indicate any errors found. Upon return, if `*errors` is 0, there were no errors found. Otherwise, `*errors` is the bit-wise `OR` of the bits described in the list below. Some of these bits will be set if a malformation is found, even if the input `flags` parameter indicates that the given malformation is allowed; those exceptions are noted:
`UTF8_GOT_PERL_EXTENDED` The input sequence is not standard UTF-8, but a Perl extension. This bit is set only if the input `flags` parameter contains either the `UTF8_DISALLOW_PERL_EXTENDED` or the `UTF8_WARN_PERL_EXTENDED` flags.
Code points above 0x7FFF\_FFFF (2\*\*31 - 1) were never specified in any standard, and so some extension must be used to express them. Perl uses a natural extension to UTF-8 to represent the ones up to 2\*\*36-1, and invented a further extension to represent even higher ones, so that any code point that fits in a 64-bit word can be represented. Text using these extensions is not likely to be portable to non-Perl code. We lump both of these extensions together and refer to them as Perl extended UTF-8. There exist other extensions that people have invented, incompatible with Perl's.
On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing extremely high code points kicks in at 0x3FFF\_FFFF (2\*\*30 -1), which is lower than on ASCII. Prior to that, code points 2\*\*31 and higher were simply unrepresentable, and a different, incompatible method was used to represent code points between 2\*\*30 and 2\*\*31 - 1.
On both platforms, ASCII and EBCDIC, `UTF8_GOT_PERL_EXTENDED` is set if Perl extended UTF-8 is used.
In earlier Perls, this bit was named `UTF8_GOT_ABOVE_31_BIT`, which you still may use for backward compatibility. That name is misleading, as this flag may be set when the code point actually does fit in 31 bits. This happens on EBCDIC platforms, and sometimes when the [overlong malformation](#UTF8_GOT_LONG) is also present. The new name accurately describes the situation in all cases.
`UTF8_GOT_CONTINUATION` The input sequence was malformed in that the first byte was a UTF-8 continuation byte.
`UTF8_GOT_EMPTY` The input `curlen` parameter was 0.
`UTF8_GOT_LONG` The input sequence was malformed in that there is some other sequence that evaluates to the same code point, but that sequence is shorter than this one.
Until Unicode 3.1, it was legal for programs to accept this malformation, but it was discovered that this created security issues.
`UTF8_GOT_NONCHAR` The code point represented by the input UTF-8 sequence is for a Unicode non-character code point. This bit is set only if the input `flags` parameter contains either the `UTF8_DISALLOW_NONCHAR` or the `UTF8_WARN_NONCHAR` flags.
`UTF8_GOT_NON_CONTINUATION` The input sequence was malformed in that a non-continuation type byte was found in a position where only a continuation type one should be. See also `["UTF8\_GOT\_SHORT"](#UTF8_GOT_SHORT)`.
`UTF8_GOT_OVERFLOW` The input sequence was malformed in that it is for a code point that is not representable in the number of bits available in an IV on the current platform.
`UTF8_GOT_SHORT` The input sequence was malformed in that `curlen` is smaller than required for a complete sequence. In other words, the input is for a partial character sequence.
`UTF8_GOT_SHORT` and `UTF8_GOT_NON_CONTINUATION` both indicate a too short sequence. The difference is that `UTF8_GOT_NON_CONTINUATION` indicates always that there is an error, while `UTF8_GOT_SHORT` means that an incomplete sequence was looked at. If no other flags are present, it means that the sequence was valid as far as it went. Depending on the application, this could mean one of three things:
* The `curlen` length parameter passed in was too small, and the function was prevented from examining all the necessary bytes.
* The buffer being looked at is based on reading data, and the data received so far stopped in the middle of a character, so that the next read will read the remainder of this character. (It is up to the caller to deal with the split bytes somehow.)
* This is a real error, and the partial sequence is all we're going to get.
`UTF8_GOT_SUPER` The input sequence was malformed in that it is for a non-Unicode code point; that is, one above the legal Unicode maximum. This bit is set only if the input `flags` parameter contains either the `UTF8_DISALLOW_SUPER` or the `UTF8_WARN_SUPER` flags.
`UTF8_GOT_SURROGATE` The input sequence was malformed in that it is for a -Unicode UTF-16 surrogate code point. This bit is set only if the input `flags` parameter contains either the `UTF8_DISALLOW_SURROGATE` or the `UTF8_WARN_SURROGATE` flags.
To do your own error handling, call this function with the `UTF8_CHECK_ONLY` flag to suppress any warnings, and then examine the `*errors` return.
```
UV utf8n_to_uvchr_error(const U8 *s, STRLEN curlen,
STRLEN *retlen, const U32 flags,
U32 * errors)
```
`utf8n_to_uvchr_msgs` THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES. Most code should use ["utf8\_to\_uvchr\_buf"](#utf8_to_uvchr_buf)() rather than call this directly.
This function is for code that needs to know what the precise malformation(s) are when an error is found, and wants the corresponding warning and/or error messages to be returned to the caller rather than be displayed. All messages that would have been displayed if all lexical warnings are enabled will be returned.
It is just like `["utf8n\_to\_uvchr\_error"](#utf8n_to_uvchr_error)` but it takes an extra parameter placed after all the others, `msgs`. If this parameter is 0, this function behaves identically to `["utf8n\_to\_uvchr\_error"](#utf8n_to_uvchr_error)`. Otherwise, `msgs` should be a pointer to an `AV *` variable, in which this function creates a new AV to contain any appropriate messages. The elements of the array are ordered so that the first message that would have been displayed is in the 0th element, and so on. Each element is a hash with three key-value pairs, as follows:
`text` The text of the message as a `SVpv`.
`warn_categories` The warning category (or categories) packed into a `SVuv`.
`flag` A single flag bit associated with this message, in a `SVuv`. The bit corresponds to some bit in the `*errors` return value, such as `UTF8_GOT_LONG`.
It's important to note that specifying this parameter as non-null will cause any warnings this function would otherwise generate to be suppressed, and instead be placed in `*msgs`. The caller can check the lexical warnings state (or not) when choosing what to do with the returned messages.
If the flag `UTF8_CHECK_ONLY` is passed, no warnings are generated, and hence no AV is created.
The caller, of course, is responsible for freeing any returned AV.
```
UV utf8n_to_uvchr_msgs(const U8 *s, STRLEN curlen,
STRLEN *retlen, const U32 flags,
U32 * errors, AV ** msgs)
```
`UTF8SKIP` returns the number of bytes a non-malformed UTF-8 encoded character whose first (perhaps only) byte is pointed to by `s`.
If there is a possibility of malformed input, use instead:
`["UTF8\_SAFE\_SKIP"](#UTF8_SAFE_SKIP)` if you know the maximum ending pointer in the buffer pointed to by `s`; or
`["UTF8\_CHK\_SKIP"](#UTF8_CHK_SKIP)` if you don't know it. It is better to restructure your code so the end pointer is passed down so that you know what it actually is at the point of this call, but if that isn't possible, `["UTF8\_CHK\_SKIP"](#UTF8_CHK_SKIP)` can minimize the chance of accessing beyond the end of the input buffer.
```
STRLEN UTF8SKIP(char* s)
```
`UTF8_CHK_SKIP` This is a safer version of `["UTF8SKIP"](#UTF8SKIP)`, but still not as safe as `["UTF8\_SAFE\_SKIP"](#UTF8_SAFE_SKIP)`. This version doesn't blindly assume that the input string pointed to by `s` is well-formed, but verifies that there isn't a NUL terminating character before the expected end of the next character in `s`. The length `UTF8_CHK_SKIP` returns stops just before any such NUL.
Perl tends to add NULs, as an insurance policy, after the end of strings in SV's, so it is likely that using this macro will prevent inadvertent reading beyond the end of the input buffer, even if it is malformed UTF-8.
This macro is intended to be used by XS modules where the inputs could be malformed, and it isn't feasible to restructure to use the safer `["UTF8\_SAFE\_SKIP"](#UTF8_SAFE_SKIP)`, for example when interfacing with a C library.
```
STRLEN UTF8_CHK_SKIP(char* s)
```
`utf8_distance` Returns the number of UTF-8 characters between the UTF-8 pointers `a` and `b`.
WARNING: use only if you \*know\* that the pointers point inside the same UTF-8 buffer.
```
IV utf8_distance(const U8 *a, const U8 *b)
```
`utf8_hop` Return the UTF-8 pointer `s` displaced by `off` characters, either forward or backward.
WARNING: do not use the following unless you \*know\* `off` is within the UTF-8 data pointed to by `s` \*and\* that on entry `s` is aligned on the first byte of character or just after the last byte of a character.
```
U8* utf8_hop(const U8 *s, SSize_t off)
```
`utf8_hop_back` Return the UTF-8 pointer `s` displaced by up to `off` characters, backward.
`off` must be non-positive.
`s` must be after or equal to `start`.
When moving backward it will not move before `start`.
Will not exceed this limit even if the string is not valid "UTF-8".
```
U8* utf8_hop_back(const U8 *s, SSize_t off, const U8 *start)
```
`utf8_hop_forward` Return the UTF-8 pointer `s` displaced by up to `off` characters, forward.
`off` must be non-negative.
`s` must be before or equal to `end`.
When moving forward it will not move beyond `end`.
Will not exceed this limit even if the string is not valid "UTF-8".
```
U8* utf8_hop_forward(const U8 *s, SSize_t off, const U8 *end)
```
`utf8_hop_safe` Return the UTF-8 pointer `s` displaced by up to `off` characters, either forward or backward.
When moving backward it will not move before `start`.
When moving forward it will not move beyond `end`.
Will not exceed those limits even if the string is not valid "UTF-8".
```
U8* utf8_hop_safe(const U8 *s, SSize_t off, const U8 *start,
const U8 *end)
```
`UTF8_IS_INVARIANT` Evaluates to 1 if the byte `c` represents the same character when encoded in UTF-8 as when not; otherwise evaluates to 0. UTF-8 invariant characters can be copied as-is when converting to/from UTF-8, saving time.
In spite of the name, this macro gives the correct result if the input string from which `c` comes is not encoded in UTF-8.
See `["UVCHR\_IS\_INVARIANT"](#UVCHR_IS_INVARIANT)` for checking if a UV is invariant.
```
bool UTF8_IS_INVARIANT(char c)
```
`UTF8_IS_NONCHAR` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8 that represents one of the Unicode non-character code points; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation.
```
bool UTF8_IS_NONCHAR(const U8 *s, const U8 *e)
```
`UTF8_IS_REPLACEMENT` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8 that represents the Unicode REPLACEMENT CHARACTER; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation.
```
bool UTF8_IS_REPLACEMENT(const U8 *s, const U8 *e)
```
`UTF8_IS_SUPER` Recall that Perl recognizes an extension to UTF-8 that can encode code points larger than the ones defined by Unicode, which are 0..0x10FFFF.
This macro evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are from this UTF-8 extension; otherwise it evaluates to 0. If non-zero, the return is how many bytes starting at `s` comprise the code point's representation.
0 is returned if the bytes are not well-formed extended UTF-8, or if they represent a code point that cannot fit in a UV on the current platform. Hence this macro can give different results when run on a 64-bit word machine than on one with a 32-bit word size.
Note that it is illegal in Perl to have code points that are larger than what can fit in an IV on the current machine; and illegal in Unicode to have any that this macro matches
```
bool UTF8_IS_SUPER(const U8 *s, const U8 *e)
```
`UTF8_IS_SURROGATE` Evaluates to non-zero if the first few bytes of the string starting at `s` and looking no further than `e - 1` are well-formed UTF-8 that represents one of the Unicode surrogate code points; otherwise it evaluates to 0. If non-zero, the value gives how many bytes starting at `s` comprise the code point's representation.
```
bool UTF8_IS_SURROGATE(const U8 *s, const U8 *e)
```
`utf8_length` Returns the number of characters in the sequence of UTF-8-encoded bytes starting at `s` and ending at the byte just before `e`. If <s> and <e> point to the same place, it returns 0 with no warning raised.
If `e < s` or if the scan would end up past `e`, it raises a UTF8 warning and returns the number of valid characters.
```
STRLEN utf8_length(const U8* s, const U8 *e)
```
`UTF8_MAXBYTES` The maximum width of a single UTF-8 encoded character, in bytes.
NOTE: Strictly speaking Perl's UTF-8 should not be called UTF-8 since UTF-8 is an encoding of Unicode, and Unicode's upper limit, 0x10FFFF, can be expressed with 4 bytes. However, Perl thinks of UTF-8 as a way to encode non-negative integers in a binary format, even those above Unicode.
`UTF8_MAXBYTES_CASE` The maximum number of UTF-8 bytes a single Unicode character can uppercase/lowercase/titlecase/fold into.
`UTF8_SAFE_SKIP` returns 0 if `s >= e`; otherwise returns the number of bytes in the UTF-8 encoded character whose first byte is pointed to by `s`. But it never returns beyond `e`. On DEBUGGING builds, it asserts that `s <= e`.
```
STRLEN UTF8_SAFE_SKIP(char* s, char* e)
```
`UTF8_SKIP` This is a synonym for `["UTF8SKIP"](#UTF8SKIP)`
```
STRLEN UTF8_SKIP(char* s)
```
`utf8_to_bytes` NOTE: `utf8_to_bytes` is **experimental** and may change or be removed without notice.
Converts a string `"s"` of length `*lenp` from UTF-8 into native byte encoding. Unlike ["bytes\_to\_utf8"](#bytes_to_utf8), this over-writes the original string, and updates `*lenp` to contain the new length. Returns zero on failure (leaving `"s"` unchanged) setting `*lenp` to -1.
Upon successful return, the number of variants in the string can be computed by having saved the value of `*lenp` before the call, and subtracting the after-call value of `*lenp` from it.
If you need a copy of the string, see ["bytes\_from\_utf8"](#bytes_from_utf8).
```
U8* utf8_to_bytes(U8 *s, STRLEN *lenp)
```
`utf8_to_uvchr` `**DEPRECATED!**` It is planned to remove `utf8_to_uvchr` from a future release of Perl. Do not use it for new code; remove it from existing code.
Returns the native code point of the first character in the string `s` which is assumed to be in UTF-8 encoding; `retlen` will be set to the length, in bytes, of that character.
Some, but not all, UTF-8 malformations are detected, and in fact, some malformed input could cause reading beyond the end of the input buffer, which is why this function is deprecated. Use ["utf8\_to\_uvchr\_buf"](#utf8_to_uvchr_buf) instead.
If `s` points to one of the detected malformations, and UTF8 warnings are enabled, zero is returned and `*retlen` is set (if `retlen` isn't `NULL`) to -1. If those warnings are off, the computed value if well-defined (or the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and `*retlen` is set (if `retlen` isn't NULL) so that (`s` + `*retlen`) is the next possible position in `s` that could begin a non-malformed character. See ["utf8n\_to\_uvchr"](#utf8n_to_uvchr) for details on when the REPLACEMENT CHARACTER is returned.
```
UV utf8_to_uvchr(const U8 *s, STRLEN *retlen)
```
`utf8_to_uvchr_buf` Returns the native code point of the first character in the string `s` which is assumed to be in UTF-8 encoding; `send` points to 1 beyond the end of `s`. `*retlen` will be set to the length, in bytes, of that character.
If `s` does not point to a well-formed UTF-8 character and UTF8 warnings are enabled, zero is returned and `*retlen` is set (if `retlen` isn't `NULL`) to -1. If those warnings are off, the computed value, if well-defined (or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and `*retlen` is set (if `retlen` isn't `NULL`) so that (`s` + `*retlen`) is the next possible position in `s` that could begin a non-malformed character. See ["utf8n\_to\_uvchr"](#utf8n_to_uvchr) for details on when the REPLACEMENT CHARACTER is returned.
```
UV utf8_to_uvchr_buf(const U8 *s, const U8 *send, STRLEN *retlen)
```
`UVCHR_IS_INVARIANT` Evaluates to 1 if the representation of code point `cp` is the same whether or not it is encoded in UTF-8; otherwise evaluates to 0. UTF-8 invariant characters can be copied as-is when converting to/from UTF-8, saving time. `cp` is Unicode if above 255; otherwise is platform-native.
```
bool UVCHR_IS_INVARIANT(UV cp)
```
`UVCHR_SKIP` returns the number of bytes required to represent the code point `cp` when encoded as UTF-8. `cp` is a native (ASCII or EBCDIC) code point if less than 255; a Unicode code point otherwise.
```
STRLEN UVCHR_SKIP(UV cp)
```
`uvchr_to_utf8` Adds the UTF-8 representation of the native code point `uv` to the end of the string `d`; `d` should have at least `UVCHR_SKIP(uv)+1` (up to `UTF8_MAXBYTES+1`) free bytes available. The return value is the pointer to the byte after the end of the new character. In other words,
```
d = uvchr_to_utf8(d, uv);
```
is the recommended wide native character-aware way of saying
```
*(d++) = uv;
```
This function accepts any code point from 0..`IV_MAX` as input. `IV_MAX` is typically 0x7FFF\_FFFF in a 32-bit word.
It is possible to forbid or warn on non-Unicode code points, or those that may be problematic by using ["uvchr\_to\_utf8\_flags"](#uvchr_to_utf8_flags).
```
U8* uvchr_to_utf8(U8 *d, UV uv)
```
`uvchr_to_utf8_flags` Adds the UTF-8 representation of the native code point `uv` to the end of the string `d`; `d` should have at least `UVCHR_SKIP(uv)+1` (up to `UTF8_MAXBYTES+1`) free bytes available. The return value is the pointer to the byte after the end of the new character. In other words,
```
d = uvchr_to_utf8_flags(d, uv, flags);
```
or, in most cases,
```
d = uvchr_to_utf8_flags(d, uv, 0);
```
This is the Unicode-aware way of saying
```
*(d++) = uv;
```
If `flags` is 0, this function accepts any code point from 0..`IV_MAX` as input. `IV_MAX` is typically 0x7FFF\_FFFF in a 32-bit word.
Specifying `flags` can further restrict what is allowed and not warned on, as follows:
If `uv` is a Unicode surrogate code point and `UNICODE_WARN_SURROGATE` is set, the function will raise a warning, provided UTF8 warnings are enabled. If instead `UNICODE_DISALLOW_SURROGATE` is set, the function will fail and return NULL. If both flags are set, the function will both warn and return NULL.
Similarly, the `UNICODE_WARN_NONCHAR` and `UNICODE_DISALLOW_NONCHAR` flags affect how the function handles a Unicode non-character.
And likewise, the `UNICODE_WARN_SUPER` and `UNICODE_DISALLOW_SUPER` flags affect the handling of code points that are above the Unicode maximum of 0x10FFFF. Languages other than Perl may not be able to accept files that contain these.
The flag `UNICODE_WARN_ILLEGAL_INTERCHANGE` selects all three of the above WARN flags; and `UNICODE_DISALLOW_ILLEGAL_INTERCHANGE` selects all three DISALLOW flags. `UNICODE_DISALLOW_ILLEGAL_INTERCHANGE` restricts the allowed inputs to the strict UTF-8 traditionally defined by Unicode. Similarly, `UNICODE_WARN_ILLEGAL_C9_INTERCHANGE` and `UNICODE_DISALLOW_ILLEGAL_C9_INTERCHANGE` are shortcuts to select the above-Unicode and surrogate flags, but not the non-character ones, as defined in [Unicode Corrigendum #9](https://www.unicode.org/versions/corrigendum9.html). See ["Noncharacter code points" in perlunicode](perlunicode#Noncharacter-code-points).
Extremely high code points were never specified in any standard, and require an extension to UTF-8 to express, which Perl does. It is likely that programs written in something other than Perl would not be able to read files that contain these; nor would Perl understand files written by something that uses a different extension. For these reasons, there is a separate set of flags that can warn and/or disallow these extremely high code points, even if other above-Unicode ones are accepted. They are the `UNICODE_WARN_PERL_EXTENDED` and `UNICODE_DISALLOW_PERL_EXTENDED` flags. For more information see `["UTF8\_GOT\_PERL\_EXTENDED"](#UTF8_GOT_PERL_EXTENDED)`. Of course `UNICODE_DISALLOW_SUPER` will treat all above-Unicode code points, including these, as malformations. (Note that the Unicode standard considers anything above 0x10FFFF to be illegal, but there are standards predating it that allow up to 0x7FFF\_FFFF (2\*\*31 -1))
A somewhat misleadingly named synonym for `UNICODE_WARN_PERL_EXTENDED` is retained for backward compatibility: `UNICODE_WARN_ABOVE_31_BIT`. Similarly, `UNICODE_DISALLOW_ABOVE_31_BIT` is usable instead of the more accurately named `UNICODE_DISALLOW_PERL_EXTENDED`. The names are misleading because on EBCDIC platforms,these flags can apply to code points that actually do fit in 31 bits. The new names accurately describe the situation in all cases.
```
U8* uvchr_to_utf8_flags(U8 *d, UV uv, UV flags)
```
`uvchr_to_utf8_flags_msgs` THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
Most code should use `["uvchr\_to\_utf8\_flags"](#uvchr_to_utf8_flags)()` rather than call this directly.
This function is for code that wants any warning and/or error messages to be returned to the caller rather than be displayed. All messages that would have been displayed if all lexical warnings are enabled will be returned.
It is just like `["uvchr\_to\_utf8\_flags"](#uvchr_to_utf8_flags)` but it takes an extra parameter placed after all the others, `msgs`. If this parameter is 0, this function behaves identically to `["uvchr\_to\_utf8\_flags"](#uvchr_to_utf8_flags)`. Otherwise, `msgs` should be a pointer to an `HV *` variable, in which this function creates a new HV to contain any appropriate messages. The hash has three key-value pairs, as follows:
`text` The text of the message as a `SVpv`.
`warn_categories` The warning category (or categories) packed into a `SVuv`.
`flag` A single flag bit associated with this message, in a `SVuv`. The bit corresponds to some bit in the `*errors` return value, such as `UNICODE_GOT_SURROGATE`.
It's important to note that specifying this parameter as non-null will cause any warnings this function would otherwise generate to be suppressed, and instead be placed in `*msgs`. The caller can check the lexical warnings state (or not) when choosing what to do with the returned messages.
The caller, of course, is responsible for freeing any returned HV.
```
U8* uvchr_to_utf8_flags_msgs(U8 *d, UV uv, UV flags, HV ** msgs)
```
Utility Functions
------------------
`C_ARRAY_END` Returns a pointer to one element past the final element of the input C array.
```
void * C_ARRAY_END(void *a)
```
`C_ARRAY_LENGTH` Returns the number of elements in the input C array (so you want your zero-based indices to be less than but not equal to).
```
STRLEN C_ARRAY_LENGTH(void *a)
```
`getcwd_sv` Fill `sv` with current working directory
```
int getcwd_sv(SV* sv)
```
`IN_PERL_COMPILETIME` Returns 1 if this macro is being called during the compilation phase of the program; otherwise 0;
```
bool IN_PERL_COMPILETIME
```
`IN_PERL_RUNTIME` Returns 1 if this macro is being called during the execution phase of the program; otherwise 0;
```
bool IN_PERL_RUNTIME
```
`IS_SAFE_SYSCALL` Same as ["is\_safe\_syscall"](#is_safe_syscall).
```
bool IS_SAFE_SYSCALL(NN const char *pv, STRLEN len,
NN const char *what, NN const char *op_name)
```
`is_safe_syscall` Test that the given `pv` (with length `len`) doesn't contain any internal `NUL` characters. If it does, set `errno` to `ENOENT`, optionally warn using the `syscalls` category, and return FALSE.
Return TRUE if the name is safe.
`what` and `op_name` are used in any warning.
Used by the `IS_SAFE_SYSCALL()` macro.
```
bool is_safe_syscall(const char *pv, STRLEN len,
const char *what, const char *op_name)
```
`my_setenv` A wrapper for the C library [setenv(3)](http://man.he.net/man3/setenv). Don't use the latter, as the perl version has desirable safeguards
```
void my_setenv(const char* nam, const char* val)
```
`phase_name` Returns the given phase's name as a NUL-terminated string.
For example, to print a stack trace that includes the current interpreter phase you might do:
```
const char* phase_name = phase_name(PL_phase);
mess("This is weird. (Perl phase: %s)", phase_name);
```
```
const char *const phase_name(enum perl_phase)
```
`Poison` PoisonWith(0xEF) for catching access to freed memory.
```
void Poison(void* dest, int nitems, type)
```
`PoisonFree` PoisonWith(0xEF) for catching access to freed memory.
```
void PoisonFree(void* dest, int nitems, type)
```
`PoisonNew` PoisonWith(0xAB) for catching access to allocated but uninitialized memory.
```
void PoisonNew(void* dest, int nitems, type)
```
`PoisonWith` Fill up memory with a byte pattern (a byte repeated over and over again) that hopefully catches attempts to access uninitialized memory.
```
void PoisonWith(void* dest, int nitems, type, U8 byte)
```
`StructCopy` This is an architecture-independent macro to copy one structure to another.
```
void StructCopy(type *src, type *dest, type)
```
`sv_destroyable` Dummy routine which reports that object can be destroyed when there is no sharing module present. It ignores its single SV argument, and returns 'true'. Exists to avoid test for a `NULL` function pointer and because it could potentially warn under some level of strict-ness.
```
bool sv_destroyable(SV *sv)
```
`sv_nosharing` Dummy routine which "shares" an SV when there is no sharing module present. Or "locks" it. Or "unlocks" it. In other words, ignores its single SV argument. Exists to avoid test for a `NULL` function pointer and because it could potentially warn under some level of strict-ness.
```
void sv_nosharing(SV *sv)
```
Versioning
----------
`new_version` Returns a new version object based on the passed in SV:
```
SV *sv = new_version(SV *ver);
```
Does not alter the passed in ver SV. See "upg\_version" if you want to upgrade the SV.
```
SV* new_version(SV *ver)
```
`PERL_REVISION` `**DEPRECATED!**` It is planned to remove `PERL_REVISION` from a future release of Perl. Do not use it for new code; remove it from existing code.
The major number component of the perl interpreter currently being compiled or executing. This has been `5` from 1993 into 2020.
Instead use one of the version comparison macros. See `["PERL\_VERSION\_EQ"](#PERL_VERSION_EQ)`.
`PERL_SUBVERSION` `**DEPRECATED!**` It is planned to remove `PERL_SUBVERSION` from a future release of Perl. Do not use it for new code; remove it from existing code.
The micro number component of the perl interpreter currently being compiled or executing. In stable releases this gives the dot release number for maintenance updates. In development releases this gives a tag for a snapshot of the status at various points in the development cycle.
Instead use one of the version comparison macros. See `["PERL\_VERSION\_EQ"](#PERL_VERSION_EQ)`.
`PERL_VERSION` `**DEPRECATED!**` It is planned to remove `PERL_VERSION` from a future release of Perl. Do not use it for new code; remove it from existing code.
The minor number component of the perl interpreter currently being compiled or executing. Between 1993 into 2020, this has ranged from 0 to 33.
Instead use one of the version comparison macros. See `["PERL\_VERSION\_EQ"](#PERL_VERSION_EQ)`.
`PERL_VERSION_EQ` `PERL_VERSION_NE` `PERL_VERSION_LT` `PERL_VERSION_LE` `PERL_VERSION_GT`
`PERL_VERSION_GE` Returns whether or not the perl currently being compiled has the specified relationship to the perl given by the parameters. For example,
```
#if PERL_VERSION_GT(5,24,2)
code that will only be compiled on perls after v5.24.2
#else
fallback code
#endif
```
Note that this is usable in making compile-time decisions
You may use the special value '\*' for the final number to mean ALL possible values for it. Thus,
```
#if PERL_VERSION_EQ(5,31,'*')
```
means all perls in the 5.31 series. And
```
#if PERL_VERSION_NE(5,24,'*')
```
means all perls EXCEPT 5.24 ones. And
```
#if PERL_VERSION_LE(5,9,'*')
```
is effectively
```
#if PERL_VERSION_LT(5,10,0)
```
This means you don't have to think so much when converting from the existing deprecated `PERL_VERSION` to using this macro:
```
#if PERL_VERSION <= 9
```
becomes
```
#if PERL_VERSION_LE(5,9,'*')
```
```
bool PERL_VERSION_EQ(const U8 major, const U8 minor,
const U8 patch)
```
`prescan_version` Validate that a given string can be parsed as a version object, but doesn't actually perform the parsing. Can use either strict or lax validation rules. Can optionally set a number of hint variables to save the parsing code some time when tokenizing.
```
const char* prescan_version(const char *s, bool strict,
const char** errstr, bool *sqv,
int *ssaw_decimal, int *swidth,
bool *salpha)
```
`scan_version` Returns a pointer to the next character after the parsed version string, as well as upgrading the passed in SV to an RV.
Function must be called with an already existing SV like
```
sv = newSV(0);
s = scan_version(s, SV *sv, bool qv);
```
Performs some preprocessing to the string to ensure that it has the correct characteristics of a version. Flags the object if it contains an underscore (which denotes this is an alpha version). The boolean qv denotes that the version should be interpreted as if it had multiple decimals, even if it doesn't.
```
const char* scan_version(const char *s, SV *rv, bool qv)
```
`upg_version` In-place upgrade of the supplied SV to a version object.
```
SV *sv = upg_version(SV *sv, bool qv);
```
Returns a pointer to the upgraded SV. Set the boolean qv if you want to force this SV to be interpreted as an "extended" version.
```
SV* upg_version(SV *ver, bool qv)
```
`vcmp` Version object aware cmp. Both operands must already have been converted into version objects.
```
int vcmp(SV *lhv, SV *rhv)
```
`vnormal` Accepts a version object and returns the normalized string representation. Call like:
```
sv = vnormal(rv);
```
NOTE: you can pass either the object directly or the SV contained within the RV.
The SV returned has a refcount of 1.
```
SV* vnormal(SV *vs)
```
`vnumify` Accepts a version object and returns the normalized floating point representation. Call like:
```
sv = vnumify(rv);
```
NOTE: you can pass either the object directly or the SV contained within the RV.
The SV returned has a refcount of 1.
```
SV* vnumify(SV *vs)
```
`vstringify` In order to maintain maximum compatibility with earlier versions of Perl, this function will return either the floating point notation or the multiple dotted notation, depending on whether the original version contained 1 or more dots, respectively.
The SV returned has a refcount of 1.
```
SV* vstringify(SV *vs)
```
`vverify` Validates that the SV contains valid internal structure for a version object. It may be passed either the version object (RV) or the hash itself (HV). If the structure is valid, it returns the HV. If the structure is invalid, it returns NULL.
```
SV *hv = vverify(sv);
```
Note that it only confirms the bare minimum structure (so as not to get confused by derived classes which may contain additional hash entries):
* The SV is an HV or a reference to an HV
* The hash contains a "version" key
* The "version" key has a reference to an AV as its value
```
SV* vverify(SV *vs)
```
Warning and Dieing
-------------------
In all these calls, the `U32 w*n*` parameters are warning category constants. You can see the ones currently available in ["Category Hierarchy" in warnings](warnings#Category-Hierarchy), just capitalize all letters in the names and prefix them by `WARN_`. So, for example, the category `void` used in a perl program becomes `WARN_VOID` when used in XS code and passed to one of the calls below.
`ckWARN` `ckWARN2` `ckWARN3`
`ckWARN4` These return a boolean as to whether or not warnings are enabled for any of the warning category(ies) parameters: `w`, `w1`, ....
Should any of the categories by default be enabled even if not within the scope of `use warnings`, instead use the `["ckWARN\_d"](#ckWARN_d)` macros.
The categories must be completely independent, one may not be subclassed from the other.
```
bool ckWARN (U32 w)
bool ckWARN2(U32 w1, U32 w2)
bool ckWARN3(U32 w1, U32 w2, U32 w3)
bool ckWARN4(U32 w1, U32 w2, U32 w3, U32 w4)
```
`ckWARN_d` `ckWARN2_d` `ckWARN3_d`
`ckWARN4_d` Like `["ckWARN"](#ckWARN)`, but for use if and only if the warning category(ies) is by default enabled even if not within the scope of `use warnings`.
```
bool ckWARN_d (U32 w)
bool ckWARN2_d(U32 w1, U32 w2)
bool ckWARN3_d(U32 w1, U32 w2, U32 w3)
bool ckWARN4_d(U32 w1, U32 w2, U32 w3, U32 w4)
```
`ck_warner`
`ck_warner_d` If none of the warning categories given by `err` are enabled, do nothing; otherwise call `["warner"](#warner)` or `["warner\_nocontext"](#warner_nocontext)` with the passed-in parameters;.
`err` must be one of the `["packWARN"](#packWARN)`, `packWARN2`, `packWARN3`, `packWARN4` macros populated with the appropriate number of warning categories.
The two forms differ only in that `ck_warner_d` should be used if warnings for any of the categories are by default enabled.
NOTE: `ck_warner` must be explicitly called as `Perl_ck_warner` with an `aTHX_` parameter.
NOTE: `ck_warner_d` must be explicitly called as `Perl_ck_warner_d` with an `aTHX_` parameter.
```
void Perl_ck_warner(pTHX_ U32 err, const char* pat, ...)
```
`CLEAR_ERRSV` Clear the contents of `$@`, setting it to the empty string.
This replaces any read-only SV with a fresh SV and removes any magic.
```
void CLEAR_ERRSV()
```
`croak`
`croak_nocontext` These are XS interfaces to Perl's `die` function.
They take a sprintf-style format pattern and argument list, which are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for `["mess\_sv"](#mess_sv)`.
The error message will be used as an exception, by default returning control to the nearest enclosing `eval`, but subject to modification by a `$SIG{__DIE__}` handler. In any case, these croak functions never return normally.
For historical reasons, if `pat` is null then the contents of `ERRSV` (`$@`) will be used as an error message or object instead of building an error message from arguments. If you want to throw a non-string object, or build an error message in an SV yourself, it is preferable to use the `["croak\_sv"](#croak_sv)` function, which does not involve clobbering `ERRSV`.
The two forms differ only in that `croak_nocontext` does not take a thread context (`aTHX`) parameter. It is usually preferred as it takes up fewer bytes of code than plain `Perl_croak`, and time is rarely a critical resource when you are about to throw an exception.
NOTE: `croak` must be explicitly called as `Perl_croak` with an `aTHX_` parameter.
```
void Perl_croak (pTHX_ const char* pat, ...)
void croak_nocontext(const char* pat, ...)
```
`croak_no_modify` This encapsulates a common reason for dying, generating terser object code than using the generic `Perl_croak`. It is exactly equivalent to `Perl_croak(aTHX_ "%s", PL_no_modify)` (which expands to something like "Modification of a read-only value attempted").
Less code used on exception code paths reduces CPU cache pressure.
```
void croak_no_modify()
```
`croak_sv` This is an XS interface to Perl's `die` function.
`baseex` is the error message or object. If it is a reference, it will be used as-is. Otherwise it is used as a string, and if it does not end with a newline then it will be extended with some indication of the current location in the code, as described for ["mess\_sv"](#mess_sv).
The error message or object will be used as an exception, by default returning control to the nearest enclosing `eval`, but subject to modification by a `$SIG{__DIE__}` handler. In any case, the `croak_sv` function never returns normally.
To die with a simple string message, the ["croak"](#croak) function may be more convenient.
```
void croak_sv(SV *baseex)
```
`die`
`die_nocontext` These behave the same as ["croak"](#croak), except for the return type. They should be used only where the `OP *` return type is required. They never actually return.
The two forms differ only in that `die_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
NOTE: `die` must be explicitly called as `Perl_die` with an `aTHX_` parameter.
```
OP* Perl_die (pTHX_ const char* pat, ...)
OP* die_nocontext(const char* pat, ...)
```
`die_sv` This behaves the same as ["croak\_sv"](#croak_sv), except for the return type. It should be used only where the `OP *` return type is required. The function never actually returns.
```
OP* die_sv(SV *baseex)
```
`ERRSV` Returns the SV for `$@`, creating it if needed.
```
SV * ERRSV
```
`packWARN` `packWARN2` `packWARN3`
`packWARN4` These macros are used to pack warning categories into a single U32 to pass to macros and functions that take a warning category parameter. The number of categories to pack is given by the name, with a corresponding number of category parameters passed.
```
U32 packWARN (U32 w1)
U32 packWARN2(U32 w1, U32 w2)
U32 packWARN3(U32 w1, U32 w2, U32 w3)
U32 packWARN4(U32 w1, U32 w2, U32 w3, U32 w4)
```
`SANE_ERRSV` Clean up ERRSV so we can safely set it.
This replaces any read-only SV with a fresh writable copy and removes any magic.
```
void SANE_ERRSV()
```
`vcroak` This is an XS interface to Perl's `die` function.
`pat` and `args` are a sprintf-style format pattern and encapsulated argument list. These are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for ["mess\_sv"](#mess_sv).
The error message will be used as an exception, by default returning control to the nearest enclosing `eval`, but subject to modification by a `$SIG{__DIE__}` handler. In any case, the `croak` function never returns normally.
For historical reasons, if `pat` is null then the contents of `ERRSV` (`$@`) will be used as an error message or object instead of building an error message from arguments. If you want to throw a non-string object, or build an error message in an SV yourself, it is preferable to use the ["croak\_sv"](#croak_sv) function, which does not involve clobbering `ERRSV`.
```
void vcroak(const char* pat, va_list* args)
```
`vwarn` This is an XS interface to Perl's `warn` function.
This is like `["warn"](#warn)`, but `args` are an encapsulated argument list.
Unlike with ["vcroak"](#vcroak), `pat` is not permitted to be null.
```
void vwarn(const char* pat, va_list* args)
```
`vwarner` This is like `["warner"](#warner)`, but `args` are an encapsulated argument list.
```
void vwarner(U32 err, const char* pat, va_list* args)
```
`warn`
`warn_nocontext` These are XS interfaces to Perl's `warn` function.
They take a sprintf-style format pattern and argument list, which are used to generate a string message. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for `["mess\_sv"](#mess_sv)`.
The error message or object will by default be written to standard error, but this is subject to modification by a `$SIG{__WARN__}` handler.
Unlike with `["croak"](#croak)`, `pat` is not permitted to be null.
The two forms differ only in that `warn_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
NOTE: `warn` must be explicitly called as `Perl_warn` with an `aTHX_` parameter.
```
void Perl_warn (pTHX_ const char* pat, ...)
void warn_nocontext(const char* pat, ...)
```
`warner`
`warner_nocontext` These output a warning of the specified category (or categories) given by `err`, using the sprintf-style format pattern `pat`, and argument list.
`err` must be one of the `["packWARN"](#packWARN)`, `packWARN2`, `packWARN3`, `packWARN4` macros populated with the appropriate number of warning categories. If any of the warning categories they specify is fatal, a fatal exception is thrown.
In any event a message is generated by the pattern and arguments. If the message does not end with a newline, then it will be extended with some indication of the current location in the code, as described for ["mess\_sv"](#mess_sv).
The error message or object will by default be written to standard error, but this is subject to modification by a `$SIG{__WARN__}` handler.
`pat` is not permitted to be null.
The two forms differ only in that `warner_nocontext` does not take a thread context (`aTHX`) parameter, so is used in situations where the caller doesn't already have the thread context.
These functions differ from the similarly named `["warn"](#warn)` functions, in that the latter are for XS code to unconditionally display a warning, whereas these are for code that may be compiling a perl program, and does extra checking to see if the warning should be fatal.
NOTE: `warner` must be explicitly called as `Perl_warner` with an `aTHX_` parameter.
```
void Perl_warner (pTHX_ U32 err, const char* pat, ...)
void warner_nocontext(U32 err, const char* pat, ...)
```
`warn_sv` This is an XS interface to Perl's `warn` function.
`baseex` is the error message or object. If it is a reference, it will be used as-is. Otherwise it is used as a string, and if it does not end with a newline then it will be extended with some indication of the current location in the code, as described for ["mess\_sv"](#mess_sv).
The error message or object will by default be written to standard error, but this is subject to modification by a `$SIG{__WARN__}` handler.
To warn with a simple string message, the ["warn"](#warn) function may be more convenient.
```
void warn_sv(SV *baseex)
```
XS
--
*xsubpp* compiles XS code into C. See ["xsubpp" in perlutil](perlutil#xsubpp).
`aMY_CXT` Described in <perlxs>.
`aMY_CXT_` Described in <perlxs>.
`_aMY_CXT`
Described in <perlxs>.
`ax` Variable which is setup by `xsubpp` to indicate the stack base offset, used by the `ST`, `XSprePUSH` and `XSRETURN` macros. The `dMARK` macro must be called prior to setup the `MARK` variable.
```
I32 ax
```
`CLASS` Variable which is setup by `xsubpp` to indicate the class name for a C++ XS constructor. This is always a `char*`. See `["THIS"](#THIS)`.
```
char* CLASS
```
`dAX` Sets up the `ax` variable. This is usually handled automatically by `xsubpp` by calling `dXSARGS`.
```
dAX;
```
`dAXMARK` Sets up the `ax` variable and stack marker variable `mark`. This is usually handled automatically by `xsubpp` by calling `dXSARGS`.
```
dAXMARK;
```
`dITEMS` Sets up the `items` variable. This is usually handled automatically by `xsubpp` by calling `dXSARGS`.
```
dITEMS;
```
`dMY_CXT` Described in <perlxs>.
`dMY_CXT_SV` Now a placeholder that declares nothing
```
dMY_CXT_SV;
```
`dUNDERBAR` Sets up any variable needed by the `UNDERBAR` macro. It used to define `padoff_du`, but it is currently a noop. However, it is strongly advised to still use it for ensuring past and future compatibility.
```
dUNDERBAR;
```
`dXSARGS` Sets up stack and mark pointers for an XSUB, calling `dSP` and `dMARK`. Sets up the `ax` and `items` variables by calling `dAX` and `dITEMS`. This is usually handled automatically by `xsubpp`.
```
dXSARGS;
```
`dXSI32` Sets up the `ix` variable for an XSUB which has aliases. This is usually handled automatically by `xsubpp`.
```
dXSI32;
```
`items` Variable which is setup by `xsubpp` to indicate the number of items on the stack. See ["Variable-length Parameter Lists" in perlxs](perlxs#Variable-length-Parameter-Lists).
```
I32 items
```
`ix` Variable which is setup by `xsubpp` to indicate which of an XSUB's aliases was used to invoke it. See ["The ALIAS: Keyword" in perlxs](perlxs#The-ALIAS%3A-Keyword).
```
I32 ix
```
`MY_CXT` Described in <perlxs>.
`MY_CXT_CLONE` Described in <perlxs>.
`MY_CXT_INIT` Described in <perlxs>.
`pMY_CXT` Described in <perlxs>.
`pMY_CXT_` Described in <perlxs>.
`_pMY_CXT`
Described in <perlxs>.
`RETVAL` Variable which is setup by `xsubpp` to hold the return value for an XSUB. This is always the proper type for the XSUB. See ["The RETVAL Variable" in perlxs](perlxs#The-RETVAL-Variable).
```
type RETVAL
```
`ST` Used to access elements on the XSUB's stack.
```
SV* ST(int ix)
```
`START_MY_CXT` Described in <perlxs>.
`THIS` Variable which is setup by `xsubpp` to designate the object in a C++ XSUB. This is always the proper type for the C++ object. See `["CLASS"](#CLASS)` and ["Using XS With C++" in perlxs](perlxs#Using-XS-With-C%2B%2B).
```
type THIS
```
`UNDERBAR` The SV\* corresponding to the `$_` variable. Works even if there is a lexical `$_` in scope.
`XS` Macro to declare an XSUB and its C parameter list. This is handled by `xsubpp`. It is the same as using the more explicit `XS_EXTERNAL` macro; the latter is preferred.
`XS_EXTERNAL` Macro to declare an XSUB and its C parameter list explicitly exporting the symbols.
`XS_INTERNAL` Macro to declare an XSUB and its C parameter list without exporting the symbols. This is handled by `xsubpp` and generally preferable over exporting the XSUB symbols unnecessarily.
`XSPROTO` Macro used by `["XS\_INTERNAL"](#XS_INTERNAL)` and `["XS\_EXTERNAL"](#XS_EXTERNAL)` to declare a function prototype. You probably shouldn't be using this directly yourself.
Undocumented elements
----------------------
The following functions have been flagged as part of the public API, but are currently undocumented. Use them at your own risk, as the interfaces are subject to change. Functions that are not listed in this document are not intended for public use, and should NOT be used under any circumstances.
If you feel you need to use one of these functions, first send email to [[email protected]](mailto:[email protected]). It may be that there is a good reason for the function not being documented, and it should be removed from this list; or it may just be that no one has gotten around to documenting it. In the latter case, you will be asked to submit a patch to document the function. Once your patch is accepted, it will indicate that the interface is stable (unless it is explicitly marked otherwise) and usable by you.
```
clone_params_del gv_name_set newANONSUB save_helem
clone_params_new hv_free_ent newAVREF save_helem_flags
do_close hv_ksplit newCVREF save_pushi32ptr
do_open hv_name_set newGVREF save_pushptr
do_openn my_failure_exit newHVREF save_pushptrptr
gv_autoload_pv newANONATTRSUB newSVREF start_subparse
gv_autoload_pvn newANONHASH save_aelem sv_dup
gv_autoload_sv newANONLIST save_aelem_flags sv_dup_inc
```
AUTHORS
-------
Until May 1997, this document was maintained by Jeff Okamoto <[email protected]>. It is now maintained as part of Perl itself.
With lots of help and suggestions from Dean Roehrich, Malcolm Beattie, Andreas Koenig, Paul Hudson, Ilya Zakharevich, Paul Marquess, Neil Bowers, Matthew Green, Tim Bunce, Spider Boardman, Ulrich Pfeifer, Stephen McCamant, and Gurusamy Sarathy.
API Listing originally by Dean Roehrich <[email protected]>.
Updated to be autogenerated from comments in the source by Benjamin Stuhl.
SEE ALSO
---------
*config.h*, <perlapio>, <perlcall>, <perlclib>, <perlembed>, <perlfilter>, <perlguts>, <perlhacktips>, <perlintern>, <perlinterp>, <perliol>, <perlmroapi>, <perlreapi>, <perlreguts>, <perlxs>
| programming_docs |
perl ExtUtils::Constant::Base ExtUtils::Constant::Base
========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Constant::Base - base class for ExtUtils::Constant objects
SYNOPSIS
--------
```
require ExtUtils::Constant::Base;
@ISA = 'ExtUtils::Constant::Base';
```
DESCRIPTION
-----------
ExtUtils::Constant::Base provides a base implementation of methods to generate C code to give fast constant value lookup by named string. Currently it's mostly used ExtUtils::Constant::XS, which generates the lookup code for the constant() subroutine found in many XS modules.
USAGE
-----
ExtUtils::Constant::Base exports no subroutines. The following methods are available
header A method returning a scalar containing definitions needed, typically for a C header file.
memEQ\_clause args\_hashref A method to return a suitable C `if` statement to check whether *name* is equal to the C variable `name`. If *checked\_at* is defined, then it is used to avoid `memEQ` for short names, or to generate a comment to highlight the position of the character in the `switch` statement.
If i<checked\_at> is a reference to a scalar, then instead it gives the characters pre-checked at the beginning, (and the number of chars by which the C variable name has been advanced. These need to be chopped from the front of *name*).
dump\_names arg\_hashref, ITEM... An internal function to generate the embedded perl code that will regenerate the constant subroutines. *default\_type*, *types* and *ITEM*s are the same as for C\_constant. *indent* is treated as number of spaces to indent by. If `declare_types` is true a `$types` is always declared in the perl code generated, if defined and false never declared, and if undefined `$types` is only declared if the values in *types* as passed in cannot be inferred from *default\_types* and the *ITEM*s.
assign arg\_hashref, VALUE... A method to return a suitable assignment clause. If *type* is aggregate (eg *PVN* expects both pointer and length) then there should be multiple *VALUE*s for the components. *pre* and *post* if defined give snippets of C code to proceed and follow the assignment. *pre* will be at the start of a block, so variables may be defined in it.
return\_clause arg\_hashref, ITEM A method to return a suitable `#ifdef` clause. *ITEM* is a hashref (as passed to `C_constant` and `match_clause`. *indent* is the number of spaces to indent, defaulting to 6.
switch\_clause arg\_hashref, NAMELEN, ITEMHASH, ITEM... An internal method to generate a suitable `switch` clause, called by `C_constant` *ITEM*s are in the hash ref format as given in the description of `C_constant`, and must all have the names of the same length, given by *NAMELEN*. *ITEMHASH* is a reference to a hash, keyed by name, values being the hashrefs in the *ITEM* list. (No parameters are modified, and there can be keys in the *ITEMHASH* that are not in the list of *ITEM*s without causing problems - the hash is passed in to save generating it afresh for each call).
params WHAT An "internal" method, subject to change, currently called to allow an overriding class to cache information that will then be passed into all the `*param*` calls. (Yes, having to read the source to make sense of this is considered a known bug). *WHAT* is be a hashref of types the constant function will return. In ExtUtils::Constant::XS this method is used to returns a hashref keyed IV NV PV SV to show which combination of pointers will be needed in the C argument list generated by C\_constant\_other\_params\_definition and C\_constant\_other\_params
dogfood arg\_hashref, ITEM... An internal function to generate the embedded perl code that will regenerate the constant subroutines. Parameters are the same as for C\_constant.
Currently the base class does nothing and returns an empty string.
normalise\_items args, default\_type, seen\_types, seen\_items, ITEM... Convert the items to a normalised form. For 8 bit and Unicode values converts the item to an array of 1 or 2 items, both 8 bit and UTF-8 encoded.
C\_constant arg\_hashref, ITEM... A function that returns a **list** of C subroutine definitions that return the value and type of constants when passed the name by the XS wrapper. *ITEM...* gives a list of constant names. Each can either be a string, which is taken as a C macro name, or a reference to a hash with the following keys
name The name of the constant, as seen by the perl code.
type The type of the constant (*IV*, *NV* etc)
value A C expression for the value of the constant, or a list of C expressions if the type is aggregate. This defaults to the *name* if not given.
macro The C pre-processor macro to use in the `#ifdef`. This defaults to the *name*, and is mainly used if *value* is an `enum`. If a reference an array is passed then the first element is used in place of the `#ifdef` line, and the second element in place of the `#endif`. This allows pre-processor constructions such as
```
#if defined (foo)
#if !defined (bar)
...
#endif
#endif
```
to be used to determine if a constant is to be defined.
A "macro" 1 signals that the constant is always defined, so the `#if`/`#endif` test is omitted.
default Default value to use (instead of `croak`ing with "your vendor has not defined...") to return if the macro isn't defined. Specify a reference to an array with type followed by value(s).
pre C code to use before the assignment of the value of the constant. This allows you to use temporary variables to extract a value from part of a `struct` and return this as *value*. This C code is places at the start of a block, so you can declare variables in it.
post C code to place between the assignment of value (to a temporary) and the return from the function. This allows you to clear up anything in *pre*. Rarely needed.
def\_pre def\_post Equivalents of *pre* and *post* for the default value.
utf8 Generated internally. Is zero or undefined if name is 7 bit ASCII, "no" if the name is 8 bit (and so should only match if SvUTF8() is false), "yes" if the name is utf8 encoded.
The internals automatically clone any name with characters 128-255 but none 256+ (ie one that could be either in bytes or utf8) into a second entry which is utf8 encoded.
weight Optional sorting weight for names, to determine the order of linear testing when multiple names fall in the same case of a switch clause. Higher comes earlier, undefined defaults to zero.
In the argument hashref, *package* is the name of the package, and is only used in comments inside the generated C code. *subname* defaults to `constant` if undefined.
*default\_type* is the type returned by `ITEM`s that don't specify their type. It defaults to the value of `default_type()`. *types* should be given either as a comma separated list of types that the C subroutine *subname* will generate or as a reference to a hash. *default\_type* will be added to the list if not present, as will any types given in the list of *ITEM*s. The resultant list should be the same list of types that `XS_constant` is given. [Otherwise `XS_constant` and `C_constant` may differ in the number of parameters to the constant function. *indent* is currently unused and ignored. In future it may be used to pass in information used to change the C indentation style used.] The best way to maintain consistency is to pass in a hash reference and let this function update it.
*breakout* governs when child functions of *subname* are generated. If there are *breakout* or more *ITEM*s with the same length of name, then the code to switch between them is placed into a function named *subname*\_*len*, for example `constant_5` for names 5 characters long. The default *breakout* is 3. A single `ITEM` is always inlined.
BUGS
----
Not everything is documented yet.
Probably others.
AUTHOR
------
Nicholas Clark <[email protected]> based on the code in `h2xs` by Larry Wall and others
perl Encode::MIME::Header Encode::MIME::Header
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::MIME::Header -- MIME encoding for an unstructured email header
SYNOPSIS
--------
```
use Encode qw(encode decode);
my $mime_str = encode("MIME-Header", "Sample:Text \N{U+263A}");
# $mime_str is "=?UTF-8?B?U2FtcGxlOlRleHQg4pi6?="
my $mime_q_str = encode("MIME-Q", "Sample:Text \N{U+263A}");
# $mime_q_str is "=?UTF-8?Q?Sample=3AText_=E2=98=BA?="
my $str = decode("MIME-Header",
"=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=\r\n " .
"=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?="
);
# $str is "If you can read this you understand the example."
use Encode qw(decode :fallbacks);
use Encode::MIME::Header;
local $Encode::MIME::Header::STRICT_DECODE = 1;
my $strict_string = decode("MIME-Header", $mime_string, FB_CROAK);
# use strict decoding and croak on errors
```
ABSTRACT
--------
This module implements [RFC 2047](https://tools.ietf.org/html/rfc2047) MIME encoding for an unstructured field body of the email header. It can also be used for [RFC 822](https://tools.ietf.org/html/rfc822) 'text' token. However, it cannot be used directly for the whole header with the field name or for the structured header fields like From, To, Cc, Message-Id, etc... There are 3 encoding names supported by this module: `MIME-Header`, `MIME-B` and `MIME-Q`.
DESCRIPTION
-----------
Decode method takes an unstructured field body of the email header (or [RFC 822](https://tools.ietf.org/html/rfc822) 'text' token) as its input and decodes each MIME encoded-word from input string to a sequence of bytes according to [RFC 2047](https://tools.ietf.org/html/rfc2047) and [RFC 2231](https://tools.ietf.org/html/rfc2231). Subsequently, each sequence of bytes with the corresponding MIME charset is decoded with [the Encode module](encode) and finally, one output string is returned. Text parts of the input string which do not contain MIME encoded-word stay unmodified in the output string. Folded newlines between two consecutive MIME encoded-words are discarded, others are preserved in the output string. `MIME-B` can decode Base64 variant, `MIME-Q` can decode Quoted-Printable variant and `MIME-Header` can decode both of them. If [Encode module](encode) does not support particular MIME charset or chosen variant then an action based on [CHECK flags](encode#Handling-Malformed-Data) is performed (by default, the MIME encoded-word is not decoded).
Encode method takes a scalar string as its input and uses [strict UTF-8](encode#UTF-8-vs.-utf8-vs.-UTF8) encoder for encoding it to UTF-8 bytes. Then a sequence of UTF-8 bytes is encoded into MIME encoded-words (`MIME-Header` and `MIME-B` use a Base64 variant while `MIME-Q` uses a Quoted-Printable variant) where each MIME encoded-word is limited to 75 characters. MIME encoded-words are separated by `CRLF SPACE` and joined to one output string. Output string is suitable for unstructured field body of the email header.
Both encode and decode methods propagate [CHECK flags](encode#Handling-Malformed-Data) when encoding and decoding the MIME charset.
BUGS
----
Versions prior to 2.22 (part of Encode 2.83) have a malfunctioning decoder and encoder. The MIME encoder infamously inserted additional spaces or discarded white spaces between consecutive MIME encoded-words, which led to invalid MIME headers produced by this module. The MIME decoder had a tendency to discard white spaces, incorrectly interpret data or attempt to decode Base64 MIME encoded-words as Quoted-Printable. These problems were fixed in version 2.22. It is highly recommended not to use any version prior 2.22!
Versions prior to 2.24 (part of Encode 2.87) ignored [CHECK flags](encode#Handling-Malformed-Data). The MIME encoder used [not strict utf8](encode#UTF-8-vs.-utf8-vs.-UTF8) encoder for input Unicode strings which could lead to invalid UTF-8 sequences. MIME decoder used also [not strict utf8](encode#UTF-8-vs.-utf8-vs.-UTF8) decoder and additionally called the decode method with a `Encode::FB_PERLQQ` flag (thus user-specified [CHECK flags](encode#Handling-Malformed-Data) were ignored). Moreover, it automatically croaked when a MIME encoded-word contained unknown encoding. Since version 2.24, this module uses [strict UTF-8](encode#UTF-8-vs.-utf8-vs.-UTF8) encoder and decoder. And [CHECK flags](encode#Handling-Malformed-Data) are correctly propagated.
Since version 2.22 (part of Encode 2.83), the MIME encoder should be fully compliant to [RFC 2047](https://tools.ietf.org/html/rfc2047) and [RFC 2231](https://tools.ietf.org/html/rfc2231). Due to the aforementioned bugs in previous versions of the MIME encoder, there is a *less strict* compatible mode for the MIME decoder which is used by default. It should be able to decode MIME encoded-words encoded by pre 2.22 versions of this module. However, note that this is not correct according to [RFC 2047](https://tools.ietf.org/html/rfc2047).
In default *not strict* mode the MIME decoder attempts to decode every substring which looks like a MIME encoded-word. Therefore, the MIME encoded-words do not need to be separated by white space. To enforce a correct *strict* mode, set variable `$Encode::MIME::Header::STRICT_DECODE` to 1 e.g. by localizing:
```
use Encode::MIME::Header;
local $Encode::MIME::Header::STRICT_DECODE = 1;
```
AUTHORS
-------
Pali <[email protected]>
SEE ALSO
---------
[Encode](encode), [RFC 822](https://tools.ietf.org/html/rfc822), [RFC 2047](https://tools.ietf.org/html/rfc2047), [RFC 2231](https://tools.ietf.org/html/rfc2231)
perl Test2::API::Breakage Test2::API::Breakage
====================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::Breakage - What breaks at what version
DESCRIPTION
-----------
This module provides lists of modules that are broken, or have been broken in the past, when upgrading <Test::Builder> to use [Test2](test2).
FUNCTIONS
---------
These can be imported, or called as methods on the class.
%mod\_ver = upgrade\_suggested()
%mod\_ver = Test2::API::Breakage->upgrade\_suggested() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then an upgrade would be a good idea, but not strictly necessary.
%mod\_ver = upgrade\_required()
%mod\_ver = Test2::API::Breakage->upgrade\_required() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then an upgrade is required for the module to work properly.
%mod\_ver = known\_broken()
%mod\_ver = Test2::API::Breakage->known\_broken() This returns key/value pairs. The key is the module name, the value is the version number. If the installed version of the module is at or below the specified one then the module will not work. A newer version may work, but is not tested or verified.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Unicode::Collate::CJK::Korean Unicode::Collate::CJK::Korean
=============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Unicode::Collate::CJK::Korean - weighting CJK Unified Ideographs for Unicode::Collate
SYNOPSIS
--------
```
use Unicode::Collate;
use Unicode::Collate::CJK::Korean;
my $collator = Unicode::Collate->new(
overrideCJK => \&Unicode::Collate::CJK::Korean::weightKorean
);
```
DESCRIPTION
-----------
`Unicode::Collate::CJK::Korean` provides `weightKorean()`, that is adequate for `overrideCJK` of `Unicode::Collate` and makes tailoring of CJK Unified Ideographs in the order of CLDR's Korean ordering.
SEE ALSO
---------
CLDR - Unicode Common Locale Data Repository <http://cldr.unicode.org/>
Unicode Locale Data Markup Language (LDML) - UTS #35 <http://www.unicode.org/reports/tr35/>
<Unicode::Collate>
<Unicode::Collate::Locale>
perl Memoize::SDBM_File Memoize::SDBM\_File
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Memoize::SDBM\_File - glue to provide EXISTS for SDBM\_File for Storable use
DESCRIPTION
-----------
See [Memoize](memoize).
perl Test2::EventFacet::Trace Test2::EventFacet::Trace
========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [FACET FIELDS](#FACET-FIELDS)
+ [DISCOURAGED HUB RELATED FIELDS](#DISCOURAGED-HUB-RELATED-FIELDS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet::Trace - Debug information for events
DESCRIPTION
-----------
The <Test2::API::Context> object, as well as all <Test2::Event> types need to have access to information about where they were created. This object represents that information.
SYNOPSIS
--------
```
use Test2::EventFacet::Trace;
my $trace = Test2::EventFacet::Trace->new(
frame => [$package, $file, $line, $subname],
);
```
FACET FIELDS
-------------
$string = $trace->{details}
$string = $trace->details() Used as a custom trace message that will be used INSTEAD of `at <FILE> line <LINE>` when calling `$trace->debug`.
$frame = $trace->{frame}
$frame = $trace->frame() Get the call frame arrayref.
```
[$package, $file, $line, $subname]
```
$int = $trace->{pid}
$int = $trace->pid() The process ID in which the event was generated.
$int = $trace->{tid}
$int = $trace->tid() The thread ID in which the event was generated.
$id = $trace->{cid}
$id = $trace->cid() The ID of the context that was used to create the event.
$uuid = $trace->{uuid}
$uuid = $trace->uuid() The UUID of the context that was used to create the event. (If uuid tagging was enabled)
($pkg, $file, $line, $subname) = $trace->call Get the basic call info as a list.
@caller = $trace->full\_call Get the full caller(N) results.
$warning\_bits = $trace->warning\_bits Get index 9 from the full caller info. This is the warnings\_bits field.
The value of this is not portable across perl versions or even processes. However it can be used in the process that generated it to reproduce the warnings settings in a new scope.
```
eval <<EOT;
BEGIN { ${^WARNING_BITS} = $trace->warning_bits };
... context's warning settings apply here ...
EOT
```
###
DISCOURAGED HUB RELATED FIELDS
These fields were not always set properly by tools. These are **MOSTLY** deprecated by the <Test2::EventFacet::Hub> facets. These fields are not required, and may only reflect the hub that was current when the event was created, which is not necessarily the same as the hub the event was sent through.
Some tools did do a good job setting these to the correct hub, but you cannot always rely on that. Use the 'hubs' facet list instead.
$hid = $trace->{hid}
$hid = $trace->hid() The ID of the hub that was current when the event was created.
$huuid = $trace->{huuid}
$huuid = $trace->huuid() The UUID of the hub that was current when the event was created. (If uuid tagging was enabled).
$int = $trace->{nested}
$int = $trace->nested() How deeply nested the event is.
$bool = $trace->{buffered}
$bool = $trace->buffered() True if the event was buffered and not sent to the formatter independent of a parent (This should never be set when nested is `0` or `undef`).
METHODS
-------
**Note:** All facet frames are also methods.
$trace->set\_detail($msg)
$msg = $trace->detail Used to get/set a custom trace message that will be used INSTEAD of `at <FILE> line <LINE>` when calling `$trace->debug`.
`detail()` is an alias to the `details` facet field for backwards compatibility.
$str = $trace->debug Typically returns the string `at <FILE> line <LINE>`. If `detail` is set then its value will be returned instead.
$trace->alert($MESSAGE) This issues a warning at the frame (filename and line number where errors should be reported).
$trace->throw($MESSAGE) This throws an exception at the frame (filename and line number where errors should be reported).
($package, $file, $line, $subname) = $trace->call() Get the caller details for the debug-info. This is where errors should be reported.
$pkg = $trace->package Get the debug-info package.
$file = $trace->file Get the debug-info filename.
$line = $trace->line Get the debug-info line number.
$subname = $trace->subname Get the debug-info subroutine name.
$sig = trace->signature Get a signature string that identifies this trace. This is used to check if multiple events are related. The signature includes pid, tid, file, line number, and the cid.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
| programming_docs |
perl I18N::LangTags I18N::LangTags
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [ABOUT LOWERCASING](#ABOUT-LOWERCASING)
* [ABOUT UNICODE PLAINTEXT LANGUAGE TAGS](#ABOUT-UNICODE-PLAINTEXT-LANGUAGE-TAGS)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
* [AUTHOR](#AUTHOR)
NAME
----
I18N::LangTags - functions for dealing with RFC3066-style language tags
SYNOPSIS
--------
```
use I18N::LangTags();
```
...or specify whichever of those functions you want to import, like so:
```
use I18N::LangTags qw(implicate_supers similarity_language_tag);
```
All the exportable functions are listed below -- you're free to import only some, or none at all. By default, none are imported. If you say:
```
use I18N::LangTags qw(:ALL)
```
...then all are exported. (This saves you from having to use something less obvious like `use I18N::LangTags qw(/./)`.)
If you don't import any of these functions, assume a `&I18N::LangTags::` in front of all the function names in the following examples.
DESCRIPTION
-----------
Language tags are a formalism, described in RFC 3066 (obsoleting 1766), for declaring what language form (language and possibly dialect) a given chunk of information is in.
This library provides functions for common tasks involving language tags as they are needed in a variety of protocols and applications.
Please see the "See Also" references for a thorough explanation of how to correctly use language tags.
* the function is\_language\_tag($lang1)
Returns true iff $lang1 is a formally valid language tag.
```
is_language_tag("fr") is TRUE
is_language_tag("x-jicarilla") is FALSE
(Subtags can be 8 chars long at most -- 'jicarilla' is 9)
is_language_tag("sgn-US") is TRUE
(That's American Sign Language)
is_language_tag("i-Klikitat") is TRUE
(True without regard to the fact noone has actually
registered Klikitat -- it's a formally valid tag)
is_language_tag("fr-patois") is TRUE
(Formally valid -- altho descriptively weak!)
is_language_tag("Spanish") is FALSE
is_language_tag("french-patois") is FALSE
(No good -- first subtag has to match
/^([xXiI]|[a-zA-Z]{2,3})$/ -- see RFC3066)
is_language_tag("x-borg-prot2532") is TRUE
(Yes, subtags can contain digits, as of RFC3066)
```
* the function extract\_language\_tags($whatever)
Returns a list of whatever looks like formally valid language tags in $whatever. Not very smart, so don't get too creative with what you want to feed it.
```
extract_language_tags("fr, fr-ca, i-mingo")
returns: ('fr', 'fr-ca', 'i-mingo')
extract_language_tags("It's like this: I'm in fr -- French!")
returns: ('It', 'in', 'fr')
(So don't just feed it any old thing.)
```
The output is untainted. If you don't know what tainting is, don't worry about it.
* the function same\_language\_tag($lang1, $lang2)
Returns true iff $lang1 and $lang2 are acceptable variant tags representing the same language-form.
```
same_language_tag('x-kadara', 'i-kadara') is TRUE
(The x/i- alternation doesn't matter)
same_language_tag('X-KADARA', 'i-kadara') is TRUE
(...and neither does case)
same_language_tag('en', 'en-US') is FALSE
(all-English is not the SAME as US English)
same_language_tag('x-kadara', 'x-kadar') is FALSE
(these are totally unrelated tags)
same_language_tag('no-bok', 'nb') is TRUE
(no-bok is a legacy tag for nb (Norwegian Bokmal))
```
`same_language_tag` works by just seeing whether `encode_language_tag($lang1)` is the same as `encode_language_tag($lang2)`.
(Yes, I know this function is named a bit oddly. Call it historic reasons.)
* the function similarity\_language\_tag($lang1, $lang2)
Returns an integer representing the degree of similarity between tags $lang1 and $lang2 (the order of which does not matter), where similarity is the number of common elements on the left, without regard to case and to x/i- alternation.
```
similarity_language_tag('fr', 'fr-ca') is 1
(one element in common)
similarity_language_tag('fr-ca', 'fr-FR') is 1
(one element in common)
similarity_language_tag('fr-CA-joual',
'fr-CA-PEI') is 2
similarity_language_tag('fr-CA-joual', 'fr-CA') is 2
(two elements in common)
similarity_language_tag('x-kadara', 'i-kadara') is 1
(x/i- doesn't matter)
similarity_language_tag('en', 'x-kadar') is 0
similarity_language_tag('x-kadara', 'x-kadar') is 0
(unrelated tags -- no similarity)
similarity_language_tag('i-cree-syllabic',
'i-cherokee-syllabic') is 0
(no B<leftmost> elements in common!)
```
* the function is\_dialect\_of($lang1, $lang2)
Returns true iff language tag $lang1 represents a subform of language tag $lang2.
**Get the order right! It doesn't work the other way around!**
```
is_dialect_of('en-US', 'en') is TRUE
(American English IS a dialect of all-English)
is_dialect_of('fr-CA-joual', 'fr-CA') is TRUE
is_dialect_of('fr-CA-joual', 'fr') is TRUE
(Joual is a dialect of (a dialect of) French)
is_dialect_of('en', 'en-US') is FALSE
(all-English is a NOT dialect of American English)
is_dialect_of('fr', 'en-CA') is FALSE
is_dialect_of('en', 'en' ) is TRUE
is_dialect_of('en-US', 'en-US') is TRUE
(B<Note:> these are degenerate cases)
is_dialect_of('i-mingo-tom', 'x-Mingo') is TRUE
(the x/i thing doesn't matter, nor does case)
is_dialect_of('nn', 'no') is TRUE
(because 'nn' (New Norse) is aliased to 'no-nyn',
as a special legacy case, and 'no-nyn' is a
subform of 'no' (Norwegian))
```
* the function super\_languages($lang1)
Returns a list of language tags that are superordinate tags to $lang1 -- it gets this by removing subtags from the end of $lang1 until nothing (or just "i" or "x") is left.
```
super_languages("fr-CA-joual") is ("fr-CA", "fr")
super_languages("en-AU") is ("en")
super_languages("en") is empty-list, ()
super_languages("i-cherokee") is empty-list, ()
...not ("i"), which would be illegal as well as pointless.
```
If $lang1 is not a valid language tag, returns empty-list in a list context, undef in a scalar context.
A notable and rather unavoidable problem with this method: "x-mingo-tom" has an "x" because the whole tag isn't an IANA-registered tag -- but super\_languages('x-mingo-tom') is ('x-mingo') -- which isn't really right, since 'i-mingo' is registered. But this module has no way of knowing that. (But note that same\_language\_tag('x-mingo', 'i-mingo') is TRUE.)
More importantly, you assume *at your peril* that superordinates of $lang1 are mutually intelligible with $lang1. Consider this carefully.
* the function locale2language\_tag($locale\_identifier)
This takes a locale name (like "en", "en\_US", or "en\_US.ISO8859-1") and maps it to a language tag. If it's not mappable (as with, notably, "C" and "POSIX"), this returns empty-list in a list context, or undef in a scalar context.
```
locale2language_tag("en") is "en"
locale2language_tag("en_US") is "en-US"
locale2language_tag("en_US.ISO8859-1") is "en-US"
locale2language_tag("C") is undef or ()
locale2language_tag("POSIX") is undef or ()
locale2language_tag("POSIX") is undef or ()
```
I'm not totally sure that locale names map satisfactorily to language tags. Think REAL hard about how you use this. YOU HAVE BEEN WARNED.
The output is untainted. If you don't know what tainting is, don't worry about it.
* the function encode\_language\_tag($lang1)
This function, if given a language tag, returns an encoding of it such that:
\* tags representing different languages never get the same encoding.
\* tags representing the same language always get the same encoding.
\* an encoding of a formally valid language tag always is a string value that is defined, has length, and is true if considered as a boolean.
Note that the encoding itself is **not** a formally valid language tag. Note also that you cannot, currently, go from an encoding back to a language tag that it's an encoding of.
Note also that you **must** consider the encoded value as atomic; i.e., you should not consider it as anything but an opaque, unanalysable string value. (The internals of the encoding method may change in future versions, as the language tagging standard changes over time.)
`encode_language_tag` returns undef if given anything other than a formally valid language tag.
The reason `encode_language_tag` exists is because different language tags may represent the same language; this is normally treatable with `same_language_tag`, but consider this situation:
You have a data file that expresses greetings in different languages. Its format is "[language tag]=[how to say 'Hello']", like:
```
en-US=Hiho
fr=Bonjour
i-mingo=Hau'
```
And suppose you write a program that reads that file and then runs as a daemon, answering client requests that specify a language tag and then expect the string that says how to greet in that language. So an interaction looks like:
```
greeting-client asks: fr
greeting-server answers: Bonjour
```
So far so good. But suppose the way you're implementing this is:
```
my %greetings;
die unless open(IN, "<", "in.dat");
while(<IN>) {
chomp;
next unless /^([^=]+)=(.+)/s;
my($lang, $expr) = ($1, $2);
$greetings{$lang} = $expr;
}
close(IN);
```
at which point %greetings has the contents:
```
"en-US" => "Hiho"
"fr" => "Bonjour"
"i-mingo" => "Hau'"
```
And suppose then that you answer client requests for language $wanted by just looking up $greetings{$wanted}.
If the client asks for "fr", that will look up successfully in %greetings, to the value "Bonjour". And if the client asks for "i-mingo", that will look up successfully in %greetings, to the value "Hau'".
But if the client asks for "i-Mingo" or "x-mingo", or "Fr", then the lookup in %greetings fails. That's the Wrong Thing.
You could instead do lookups on $wanted with:
```
use I18N::LangTags qw(same_language_tag);
my $response = '';
foreach my $l2 (keys %greetings) {
if(same_language_tag($wanted, $l2)) {
$response = $greetings{$l2};
last;
}
}
```
But that's rather inefficient. A better way to do it is to start your program with:
```
use I18N::LangTags qw(encode_language_tag);
my %greetings;
die unless open(IN, "<", "in.dat");
while(<IN>) {
chomp;
next unless /^([^=]+)=(.+)/s;
my($lang, $expr) = ($1, $2);
$greetings{
encode_language_tag($lang)
} = $expr;
}
close(IN);
```
and then just answer client requests for language $wanted by just looking up
```
$greetings{encode_language_tag($wanted)}
```
And that does the Right Thing.
* the function alternate\_language\_tags($lang1)
This function, if given a language tag, returns all language tags that are alternate forms of this language tag. (I.e., tags which refer to the same language.) This is meant to handle legacy tags caused by the minor changes in language tag standards over the years; and the x-/i- alternation is also dealt with.
Note that this function does *not* try to equate new (and never-used, and unusable) ISO639-2 three-letter tags to old (and still in use) ISO639-1 two-letter equivalents -- like "ara" -> "ar" -- because "ara" has *never* been in use as an Internet language tag, and RFC 3066 stipulates that it never should be, since a shorter tag ("ar") exists.
Examples:
```
alternate_language_tags('no-bok') is ('nb')
alternate_language_tags('nb') is ('no-bok')
alternate_language_tags('he') is ('iw')
alternate_language_tags('iw') is ('he')
alternate_language_tags('i-hakka') is ('zh-hakka', 'x-hakka')
alternate_language_tags('zh-hakka') is ('i-hakka', 'x-hakka')
alternate_language_tags('en') is ()
alternate_language_tags('x-mingo-tom') is ('i-mingo-tom')
alternate_language_tags('x-klikitat') is ('i-klikitat')
alternate_language_tags('i-klikitat') is ('x-klikitat')
```
This function returns empty-list if given anything other than a formally valid language tag.
* the function @langs = panic\_languages(@accept\_languages)
This function takes a list of 0 or more language tags that constitute a given user's Accept-Language list, and returns a list of tags for *other* (non-super) languages that are probably acceptable to the user, to be used *if all else fails*.
For example, if a user accepts only 'ca' (Catalan) and 'es' (Spanish), and the documents/interfaces you have available are just in German, Italian, and Chinese, then the user will most likely want the Italian one (and not the Chinese or German one!), instead of getting nothing. So `panic_languages('ca', 'es')` returns a list containing 'it' (Italian).
English ('en') is *always* in the return list, but whether it's at the very end or not depends on the input languages. This function works by consulting an internal table that stipulates what common languages are "close" to each other.
A useful construct you might consider using is:
```
@fallbacks = super_languages(@accept_languages);
push @fallbacks, panic_languages(
@accept_languages, @fallbacks,
);
```
* the function implicate\_supers( ...languages... )
This takes a list of strings (which are presumed to be language-tags; strings that aren't, are ignored); and after each one, this function inserts super-ordinate forms that don't already appear in the list. The original list, plus these insertions, is returned.
In other words, it takes this:
```
pt-br de-DE en-US fr pt-br-janeiro
```
and returns this:
```
pt-br pt de-DE de en-US en fr pt-br-janeiro
```
This function is most useful in the idiom
```
implicate_supers( I18N::LangTags::Detect::detect() );
```
(See <I18N::LangTags::Detect>.)
* the function implicate\_supers\_strictly( ...languages... )
This works like `implicate_supers` except that the implicated forms are added to the end of the return list.
In other words, implicate\_supers\_strictly takes a list of strings (which are presumed to be language-tags; strings that aren't, are ignored) and after the whole given list, it inserts the super-ordinate forms of all given tags, minus any tags that already appear in the input list.
In other words, it takes this:
```
pt-br de-DE en-US fr pt-br-janeiro
```
and returns this:
```
pt-br de-DE en-US fr pt-br-janeiro pt de en
```
The reason this function has "\_strictly" in its name is that when you're processing an Accept-Language list according to the RFCs, if you interpret the RFCs quite strictly, then you would use implicate\_supers\_strictly, but for normal use (i.e., common-sense use, as far as I'm concerned) you'd use implicate\_supers.
ABOUT LOWERCASING
------------------
I've considered making all the above functions that output language tags return all those tags strictly in lowercase. Having all your language tags in lowercase does make some things easier. But you might as well just lowercase as you like, or call `encode_language_tag($lang1)` where appropriate.
ABOUT UNICODE PLAINTEXT LANGUAGE TAGS
--------------------------------------
In some future version of I18N::LangTags, I plan to include support for RFC2482-style language tags -- which are basically just normal language tags with their ASCII characters shifted into Plane 14.
SEE ALSO
---------
\* <I18N::LangTags::List>
\* RFC 3066, `<http://www.ietf.org/rfc/rfc3066.txt>`, "Tags for the Identification of Languages". (Obsoletes RFC 1766)
\* RFC 2277, `<http://www.ietf.org/rfc/rfc2277.txt>`, "IETF Policy on Character Sets and Languages".
\* RFC 2231, `<http://www.ietf.org/rfc/rfc2231.txt>`, "MIME Parameter Value and Encoded Word Extensions: Character Sets, Languages, and Continuations".
\* RFC 2482, `<http://www.ietf.org/rfc/rfc2482.txt>`, "Language Tagging in Unicode Plain Text".
\* Locale::Codes, in `<http://www.perl.com/CPAN/modules/by-module/Locale/>`
\* ISO 639-2, "Codes for the representation of names of languages", including two-letter and three-letter codes, `<http://www.loc.gov/standards/iso639-2/php/code_list.php>`
\* The IANA list of registered languages (hopefully up-to-date), `<http://www.iana.org/assignments/language-tags>`
COPYRIGHT
---------
Copyright (c) 1998+ Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The programs and documentation in this dist are distributed in the hope that they will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Sean M. Burke `[email protected]`
perl perltrap perltrap
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Awk Traps](#Awk-Traps)
+ [C/C++ Traps](#C/C++-Traps)
+ [JavaScript Traps](#JavaScript-Traps)
+ [Sed Traps](#Sed-Traps)
+ [Shell Traps](#Shell-Traps)
+ [Perl Traps](#Perl-Traps)
NAME
----
perltrap - Perl traps for the unwary
DESCRIPTION
-----------
The biggest trap of all is forgetting to `use warnings` or use the **-w** switch; see <warnings> and ["-w" in perlrun](perlrun#-w). The second biggest trap is not making your entire program runnable under `use strict`. The third biggest trap is not reading the list of changes in this version of Perl; see [perldelta](https://perldoc.perl.org/5.36.0/perldelta).
###
Awk Traps
Accustomed **awk** users should take special note of the following:
* A Perl program executes only once, not once for each input line. You can do an implicit loop with `-n` or `-p`.
* The English module, loaded via
```
use English;
```
allows you to refer to special variables (like `$/`) with names (like $RS), as though they were in **awk**; see <perlvar> for details.
* Semicolons are required after all simple statements in Perl (except at the end of a block). Newline is not a statement delimiter.
* Curly brackets are required on `if`s and `while`s.
* Variables begin with "$", "@" or "%" in Perl.
* Arrays index from 0. Likewise string positions in substr() and index().
* You have to decide whether your array has numeric or string indices.
* Hash values do not spring into existence upon mere reference.
* You have to decide whether you want to use string or numeric comparisons.
* Reading an input line does not split it for you. You get to split it to an array yourself. And the split() operator has different arguments than **awk**'s.
* The current input line is normally in $\_, not $0. It generally does not have the newline stripped. ($0 is the name of the program executed.) See <perlvar>.
* $<*digit*> does not refer to fields--it refers to substrings matched by the last match pattern.
* The print() statement does not add field and record separators unless you set `$,` and `$\`. You can set $OFS and $ORS if you're using the English module.
* You must open your files before you print to them.
* The range operator is "..", not comma. The comma operator works as in C.
* The match operator is "=~", not "~". ("~" is the one's complement operator, as in C.)
* The exponentiation operator is "\*\*", not "^". "^" is the XOR operator, as in C. (You know, one could get the feeling that **awk** is basically incompatible with C.)
* The concatenation operator is ".", not the null string. (Using the null string would render `/pat/ /pat/` unparsable, because the third slash would be interpreted as a division operator--the tokenizer is in fact slightly context sensitive for operators like "/", "?", and ">". And in fact, "." itself can be the beginning of a number.)
* The `next`, `exit`, and `continue` keywords work differently.
* The following variables work differently:
```
Awk Perl
ARGC scalar @ARGV (compare with $#ARGV)
ARGV[0] $0
FILENAME $ARGV
FNR $. - something
FS (whatever you like)
NF $#Fld, or some such
NR $.
OFMT $#
OFS $,
ORS $\
RLENGTH length($&)
RS $/
RSTART length($`)
SUBSEP $;
```
* You cannot set $RS to a pattern, only a string.
* When in doubt, run the **awk** construct through **a2p** and see what it gives you.
###
C/C++ Traps
Cerebral C and C++ programmers should take note of the following:
* Curly brackets are required on `if`'s and `while`'s.
* You must use `elsif` rather than `else if`.
* The `break` and `continue` keywords from C become in Perl `last` and `next`, respectively. Unlike in C, these do *not* work within a `do { } while` construct. See ["Loop Control" in perlsyn](perlsyn#Loop-Control).
* The switch statement is called `given`/`when` and only available in perl 5.10 or newer. See ["Switch Statements" in perlsyn](perlsyn#Switch-Statements).
* Variables begin with "$", "@" or "%" in Perl.
* Comments begin with "#", not "/\*" or "//". Perl may interpret C/C++ comments as division operators, unterminated regular expressions or the defined-or operator.
* You can't take the address of anything, although a similar operator in Perl is the backslash, which creates a reference.
* `ARGV` must be capitalized. `$ARGV[0]` is C's `argv[1]`, and `argv[0]` ends up in `$0`.
* System calls such as link(), unlink(), rename(), etc. return nonzero for success, not 0. (system(), however, returns zero for success.)
* Signal handlers deal with signal names, not numbers. Use `kill -l` to find their names on your system.
###
JavaScript Traps
Judicious JavaScript programmers should take note of the following:
* In Perl, binary `+` is always addition. `$string1 + $string2` converts both strings to numbers and then adds them. To concatenate two strings, use the `.` operator.
* The `+` unary operator doesn't do anything in Perl. It exists to avoid syntactic ambiguities.
* Unlike `for...in`, Perl's `for` (also spelled `foreach`) does not allow the left-hand side to be an arbitrary expression. It must be a variable:
```
for my $variable (keys %hash) {
...
}
```
Furthermore, don't forget the `keys` in there, as `foreach my $kv (%hash) {}` iterates over the keys and values, and is generally not useful ($kv would be a key, then a value, and so on).
* To iterate over the indices of an array, use `foreach my $i (0 .. $#array) {}`. `foreach my $v (@array) {}` iterates over the values.
* Perl requires braces following `if`, `while`, `foreach`, etc.
* In Perl, `else if` is spelled `elsif`.
* `? :` has higher precedence than assignment. In JavaScript, one can write:
```
condition ? do_something() : variable = 3
```
and the variable is only assigned if the condition is false. In Perl, you need parentheses:
```
$condition ? do_something() : ($variable = 3);
```
Or just use `if`.
* Perl requires semicolons to separate statements.
* Variables declared with `my` only affect code *after* the declaration. You cannot write `$x = 1; my $x;` and expect the first assignment to affect the same variable. It will instead assign to an `$x` declared previously in an outer scope, or to a global variable.
Note also that the variable is not visible until the following *statement*. This means that in `my $x = 1 + $x` the second $x refers to one declared previously.
* `my` variables are scoped to the current block, not to the current function. If you write `{my $x;} $x;`, the second `$x` does not refer to the one declared inside the block.
* An object's members cannot be made accessible as variables. The closest Perl equivalent to `with(object) { method() }` is `for`, which can alias `$_` to the object:
```
for ($object) {
$_->method;
}
```
* The object or class on which a method is called is passed as one of the method's arguments, not as a separate `this` value.
###
Sed Traps
Seasoned **sed** programmers should take note of the following:
* A Perl program executes only once, not once for each input line. You can do an implicit loop with `-n` or `-p`.
* Backreferences in substitutions use "$" rather than "\".
* The pattern matching metacharacters "(", ")", and "|" do not have backslashes in front.
* The range operator is `...`, rather than comma.
###
Shell Traps
Sharp shell programmers should take note of the following:
* The backtick operator does variable interpolation without regard to the presence of single quotes in the command.
* The backtick operator does no translation of the return value, unlike **csh**.
* Shells (especially **csh**) do several levels of substitution on each command line. Perl does substitution in only certain constructs such as double quotes, backticks, angle brackets, and search patterns.
* Shells interpret scripts a little bit at a time. Perl compiles the entire program before executing it (except for `BEGIN` blocks, which execute at compile time).
* The arguments are available via @ARGV, not $1, $2, etc.
* The environment is not automatically made available as separate scalar variables.
* The shell's `test` uses "=", "!=", "<" etc for string comparisons and "-eq", "-ne", "-lt" etc for numeric comparisons. This is the reverse of Perl, which uses `eq`, `ne`, `lt` for string comparisons, and `==`, `!=` `<` etc for numeric comparisons.
###
Perl Traps
Practicing Perl Programmers should take note of the following:
* Remember that many operations behave differently in a list context than they do in a scalar one. See <perldata> for details.
* Avoid barewords if you can, especially all lowercase ones. You can't tell by just looking at it whether a bareword is a function or a string. By using quotes on strings and parentheses on function calls, you won't ever get them confused.
* You cannot discern from mere inspection which builtins are unary operators (like chop() and chdir()) and which are list operators (like print() and unlink()). (Unless prototyped, user-defined subroutines can **only** be list operators, never unary ones.) See <perlop> and <perlsub>.
* People have a hard time remembering that some functions default to $\_, or @ARGV, or whatever, but that others which you might expect to do not.
* The <FH> construct is not the name of the filehandle, it is a readline operation on that handle. The data read is assigned to $\_ only if the file read is the sole condition in a while loop:
```
while (<FH>) { }
while (defined($_ = <FH>)) { }..
<FH>; # data discarded!
```
* Remember not to use `=` when you need `=~`; these two constructs are quite different:
```
$x = /foo/;
$x =~ /foo/;
```
* The `do {}` construct isn't a real loop that you can use loop control on.
* Use `my()` for local variables whenever you can get away with it (but see <perlform> for where you can't). Using `local()` actually gives a local value to a global variable, which leaves you open to unforeseen side-effects of dynamic scoping.
* If you localize an exported variable in a module, its exported value will not change. The local name becomes an alias to a new value but the external name is still an alias for the original.
As always, if any of these are ever officially declared as bugs, they'll be fixed and removed.
| programming_docs |
perl ExtUtils::Constant::Utils ExtUtils::Constant::Utils
=========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [USAGE](#USAGE)
* [AUTHOR](#AUTHOR)
NAME
----
ExtUtils::Constant::Utils - helper functions for ExtUtils::Constant
SYNOPSIS
--------
```
use ExtUtils::Constant::Utils qw (C_stringify);
$C_code = C_stringify $stuff;
```
DESCRIPTION
-----------
ExtUtils::Constant::Utils packages up utility subroutines used by ExtUtils::Constant, ExtUtils::Constant::Base and derived classes. All its functions are explicitly exportable.
USAGE
-----
C\_stringify NAME A function which returns a 7 bit ASCII correctly \ escaped version of the string passed suitable for C's "" or ''. It will die if passed Unicode characters.
perl\_stringify NAME A function which returns a 7 bit ASCII correctly \ escaped version of the string passed suitable for a perl "" string.
AUTHOR
------
Nicholas Clark <[email protected]> based on the code in `h2xs` by Larry Wall and others
perl perlinterp perlinterp
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [ELEMENTS OF THE INTERPRETER](#ELEMENTS-OF-THE-INTERPRETER)
+ [Startup](#Startup)
+ [Parsing](#Parsing)
+ [Optimization](#Optimization)
+ [Running](#Running)
+ [Exception handing](#Exception-handing)
+ [INTERNAL VARIABLE TYPES](#INTERNAL-VARIABLE-TYPES)
* [OP TREES](#OP-TREES)
* [STACKS](#STACKS)
+ [Argument stack](#Argument-stack)
+ [Mark stack](#Mark-stack)
+ [Save stack](#Save-stack)
* [MILLIONS OF MACROS](#MILLIONS-OF-MACROS)
* [FURTHER READING](#FURTHER-READING)
NAME
----
perlinterp - An overview of the Perl interpreter
DESCRIPTION
-----------
This document provides an overview of how the Perl interpreter works at the level of C code, along with pointers to the relevant C source code files.
ELEMENTS OF THE INTERPRETER
----------------------------
The work of the interpreter has two main stages: compiling the code into the internal representation, or bytecode, and then executing it. ["Compiled code" in perlguts](perlguts#Compiled-code) explains exactly how the compilation stage happens.
Here is a short breakdown of perl's operation:
### Startup
The action begins in *perlmain.c*. (or *miniperlmain.c* for miniperl) This is very high-level code, enough to fit on a single screen, and it resembles the code found in <perlembed>; most of the real action takes place in *perl.c*
*perlmain.c* is generated by `ExtUtils::Miniperl` from *miniperlmain.c* at make time, so you should make perl to follow this along.
First, *perlmain.c* allocates some memory and constructs a Perl interpreter, along these lines:
```
1 PERL_SYS_INIT3(&argc,&argv,&env);
2
3 if (!PL_do_undump) {
4 my_perl = perl_alloc();
5 if (!my_perl)
6 exit(1);
7 perl_construct(my_perl);
8 PL_perl_destruct_level = 0;
9 }
```
Line 1 is a macro, and its definition is dependent on your operating system. Line 3 references `PL_do_undump`, a global variable - all global variables in Perl start with `PL_`. This tells you whether the current running program was created with the `-u` flag to perl and then *undump*, which means it's going to be false in any sane context.
Line 4 calls a function in *perl.c* to allocate memory for a Perl interpreter. It's quite a simple function, and the guts of it looks like this:
```
my_perl = (PerlInterpreter*)PerlMem_malloc(sizeof(PerlInterpreter));
```
Here you see an example of Perl's system abstraction, which we'll see later: `PerlMem_malloc` is either your system's `malloc`, or Perl's own `malloc` as defined in *malloc.c* if you selected that option at configure time.
Next, in line 7, we construct the interpreter using perl\_construct, also in *perl.c*; this sets up all the special variables that Perl needs, the stacks, and so on.
Now we pass Perl the command line options, and tell it to go:
```
if (!perl_parse(my_perl, xs_init, argc, argv, (char **)NULL))
perl_run(my_perl);
exitstatus = perl_destruct(my_perl);
perl_free(my_perl);
```
`perl_parse` is actually a wrapper around `S_parse_body`, as defined in *perl.c*, which processes the command line options, sets up any statically linked XS modules, opens the program and calls `yyparse` to parse it.
### Parsing
The aim of this stage is to take the Perl source, and turn it into an op tree. We'll see what one of those looks like later. Strictly speaking, there's three things going on here.
`yyparse`, the parser, lives in *perly.c*, although you're better off reading the original YACC input in *perly.y*. (Yes, Virginia, there **is** a YACC grammar for Perl!) The job of the parser is to take your code and "understand" it, splitting it into sentences, deciding which operands go with which operators and so on.
The parser is nobly assisted by the lexer, which chunks up your input into tokens, and decides what type of thing each token is: a variable name, an operator, a bareword, a subroutine, a core function, and so on. The main point of entry to the lexer is `yylex`, and that and its associated routines can be found in *toke.c*. Perl isn't much like other computer languages; it's highly context sensitive at times, it can be tricky to work out what sort of token something is, or where a token ends. As such, there's a lot of interplay between the tokeniser and the parser, which can get pretty frightening if you're not used to it.
As the parser understands a Perl program, it builds up a tree of operations for the interpreter to perform during execution. The routines which construct and link together the various operations are to be found in *op.c*, and will be examined later.
### Optimization
Now the parsing stage is complete, and the finished tree represents the operations that the Perl interpreter needs to perform to execute our program. Next, Perl does a dry run over the tree looking for optimisations: constant expressions such as `3 + 4` will be computed now, and the optimizer will also see if any multiple operations can be replaced with a single one. For instance, to fetch the variable `$foo`, instead of grabbing the glob `*foo` and looking at the scalar component, the optimizer fiddles the op tree to use a function which directly looks up the scalar in question. The main optimizer is `peep` in *op.c*, and many ops have their own optimizing functions.
### Running
Now we're finally ready to go: we have compiled Perl byte code, and all that's left to do is run it. The actual execution is done by the `runops_standard` function in *run.c*; more specifically, it's done by these three innocent looking lines:
```
while ((PL_op = PL_op->op_ppaddr(aTHX))) {
PERL_ASYNC_CHECK();
}
```
You may be more comfortable with the Perl version of that:
```
PERL_ASYNC_CHECK() while $Perl::op = &{$Perl::op->{function}};
```
Well, maybe not. Anyway, each op contains a function pointer, which stipulates the function which will actually carry out the operation. This function will return the next op in the sequence - this allows for things like `if` which choose the next op dynamically at run time. The `PERL_ASYNC_CHECK` makes sure that things like signals interrupt execution if required.
The actual functions called are known as PP code, and they're spread between four files: *pp\_hot.c* contains the "hot" code, which is most often used and highly optimized, *pp\_sys.c* contains all the system-specific functions, *pp\_ctl.c* contains the functions which implement control structures (`if`, `while` and the like) and *pp.c* contains everything else. These are, if you like, the C code for Perl's built-in functions and operators.
Note that each `pp_` function is expected to return a pointer to the next op. Calls to perl subs (and eval blocks) are handled within the same runops loop, and do not consume extra space on the C stack. For example, `pp_entersub` and `pp_entertry` just push a `CxSUB` or `CxEVAL` block struct onto the context stack which contain the address of the op following the sub call or eval. They then return the first op of that sub or eval block, and so execution continues of that sub or block. Later, a `pp_leavesub` or `pp_leavetry` op pops the `CxSUB` or `CxEVAL`, retrieves the return op from it, and returns it.
###
Exception handing
Perl's exception handing (i.e. `die` etc.) is built on top of the low-level `setjmp()`/`longjmp()` C-library functions. These basically provide a way to capture the current PC and SP registers and later restore them; i.e. a `longjmp()` continues at the point in code where a previous `setjmp()` was done, with anything further up on the C stack being lost. This is why code should always save values using `SAVE_*FOO*` rather than in auto variables.
The perl core wraps `setjmp()` etc in the macros `JMPENV_PUSH` and `JMPENV_JUMP`. The basic rule of perl exceptions is that `exit`, and `die` (in the absence of `eval`) perform a `JMPENV_JUMP(2)`, while `die` within `eval` does a `JMPENV_JUMP(3)`.
At entry points to perl, such as `perl_parse()`, `perl_run()` and `call_sv(cv, G_EVAL)` each does a `JMPENV_PUSH`, then enter a runops loop or whatever, and handle possible exception returns. For a 2 return, final cleanup is performed, such as popping stacks and calling `CHECK` or `END` blocks. Amongst other things, this is how scope cleanup still occurs during an `exit`.
If a `die` can find a `CxEVAL` block on the context stack, then the stack is popped to that level and the return op in that block is assigned to `PL_restartop`; then a `JMPENV_JUMP(3)` is performed. This normally passes control back to the guard. In the case of `perl_run` and `call_sv`, a non-null `PL_restartop` triggers re-entry to the runops loop. The is the normal way that `die` or `croak` is handled within an `eval`.
Sometimes ops are executed within an inner runops loop, such as tie, sort or overload code. In this case, something like
```
sub FETCH { eval { die } }
```
would cause a longjmp right back to the guard in `perl_run`, popping both runops loops, which is clearly incorrect. One way to avoid this is for the tie code to do a `JMPENV_PUSH` before executing `FETCH` in the inner runops loop, but for efficiency reasons, perl in fact just sets a flag, using `CATCH_SET(TRUE)`. The `pp_require`, `pp_entereval` and `pp_entertry` ops check this flag, and if true, they call `docatch`, which does a `JMPENV_PUSH` and starts a new runops level to execute the code, rather than doing it on the current loop.
As a further optimisation, on exit from the eval block in the `FETCH`, execution of the code following the block is still carried on in the inner loop. When an exception is raised, `docatch` compares the `JMPENV` level of the `CxEVAL` with `PL_top_env` and if they differ, just re-throws the exception. In this way any inner loops get popped.
Here's an example.
```
1: eval { tie @a, 'A' };
2: sub A::TIEARRAY {
3: eval { die };
4: die;
5: }
```
To run this code, `perl_run` is called, which does a `JMPENV_PUSH` then enters a runops loop. This loop executes the eval and tie ops on line 1, with the eval pushing a `CxEVAL` onto the context stack.
The `pp_tie` does a `CATCH_SET(TRUE)`, then starts a second runops loop to execute the body of `TIEARRAY`. When it executes the entertry op on line 3, `CATCH_GET` is true, so `pp_entertry` calls `docatch` which does a `JMPENV_PUSH` and starts a third runops loop, which then executes the die op. At this point the C call stack looks like this:
```
Perl_pp_die
Perl_runops # third loop
S_docatch_body
S_docatch
Perl_pp_entertry
Perl_runops # second loop
S_call_body
Perl_call_sv
Perl_pp_tie
Perl_runops # first loop
S_run_body
perl_run
main
```
and the context and data stacks, as shown by `-Dstv`, look like:
```
STACK 0: MAIN
CX 0: BLOCK =>
CX 1: EVAL => AV() PV("A"\0)
retop=leave
STACK 1: MAGIC
CX 0: SUB =>
retop=(null)
CX 1: EVAL => *
retop=nextstate
```
The die pops the first `CxEVAL` off the context stack, sets `PL_restartop` from it, does a `JMPENV_JUMP(3)`, and control returns to the top `docatch`. This then starts another third-level runops level, which executes the nextstate, pushmark and die ops on line 4. At the point that the second `pp_die` is called, the C call stack looks exactly like that above, even though we are no longer within an inner eval; this is because of the optimization mentioned earlier. However, the context stack now looks like this, ie with the top CxEVAL popped:
```
STACK 0: MAIN
CX 0: BLOCK =>
CX 1: EVAL => AV() PV("A"\0)
retop=leave
STACK 1: MAGIC
CX 0: SUB =>
retop=(null)
```
The die on line 4 pops the context stack back down to the CxEVAL, leaving it as:
```
STACK 0: MAIN
CX 0: BLOCK =>
```
As usual, `PL_restartop` is extracted from the `CxEVAL`, and a `JMPENV_JUMP(3)` done, which pops the C stack back to the docatch:
```
S_docatch
Perl_pp_entertry
Perl_runops # second loop
S_call_body
Perl_call_sv
Perl_pp_tie
Perl_runops # first loop
S_run_body
perl_run
main
```
In this case, because the `JMPENV` level recorded in the `CxEVAL` differs from the current one, `docatch` just does a `JMPENV_JUMP(3)` and the C stack unwinds to:
```
perl_run
main
```
Because `PL_restartop` is non-null, `run_body` starts a new runops loop and execution continues.
###
INTERNAL VARIABLE TYPES
You should by now have had a look at <perlguts>, which tells you about Perl's internal variable types: SVs, HVs, AVs and the rest. If not, do that now.
These variables are used not only to represent Perl-space variables, but also any constants in the code, as well as some structures completely internal to Perl. The symbol table, for instance, is an ordinary Perl hash. Your code is represented by an SV as it's read into the parser; any program files you call are opened via ordinary Perl filehandles, and so on.
The core <Devel::Peek> module lets us examine SVs from a Perl program. Let's see, for instance, how Perl treats the constant `"hello"`.
```
% perl -MDevel::Peek -e 'Dump("hello")'
1 SV = PV(0xa041450) at 0xa04ecbc
2 REFCNT = 1
3 FLAGS = (POK,READONLY,pPOK)
4 PV = 0xa0484e0 "hello"\0
5 CUR = 5
6 LEN = 6
```
Reading `Devel::Peek` output takes a bit of practise, so let's go through it line by line.
Line 1 tells us we're looking at an SV which lives at `0xa04ecbc` in memory. SVs themselves are very simple structures, but they contain a pointer to a more complex structure. In this case, it's a PV, a structure which holds a string value, at location `0xa041450`. Line 2 is the reference count; there are no other references to this data, so it's 1.
Line 3 are the flags for this SV - it's OK to use it as a PV, it's a read-only SV (because it's a constant) and the data is a PV internally. Next we've got the contents of the string, starting at location `0xa0484e0`.
Line 5 gives us the current length of the string - note that this does **not** include the null terminator. Line 6 is not the length of the string, but the length of the currently allocated buffer; as the string grows, Perl automatically extends the available storage via a routine called `SvGROW`.
You can get at any of these quantities from C very easily; just add `Sv` to the name of the field shown in the snippet, and you've got a macro which will return the value: `SvCUR(sv)` returns the current length of the string, `SvREFCOUNT(sv)` returns the reference count, `SvPV(sv, len)` returns the string itself with its length, and so on. More macros to manipulate these properties can be found in <perlguts>.
Let's take an example of manipulating a PV, from `sv_catpvn`, in *sv.c*
```
1 void
2 Perl_sv_catpvn(pTHX_ SV *sv, const char *ptr, STRLEN len)
3 {
4 STRLEN tlen;
5 char *junk;
6 junk = SvPV_force(sv, tlen);
7 SvGROW(sv, tlen + len + 1);
8 if (ptr == junk)
9 ptr = SvPVX(sv);
10 Move(ptr,SvPVX(sv)+tlen,len,char);
11 SvCUR(sv) += len;
12 *SvEND(sv) = '\0';
13 (void)SvPOK_only_UTF8(sv); /* validate pointer */
14 SvTAINT(sv);
15 }
```
This is a function which adds a string, `ptr`, of length `len` onto the end of the PV stored in `sv`. The first thing we do in line 6 is make sure that the SV **has** a valid PV, by calling the `SvPV_force` macro to force a PV. As a side effect, `tlen` gets set to the current value of the PV, and the PV itself is returned to `junk`.
In line 7, we make sure that the SV will have enough room to accommodate the old string, the new string and the null terminator. If `LEN` isn't big enough, `SvGROW` will reallocate space for us.
Now, if `junk` is the same as the string we're trying to add, we can grab the string directly from the SV; `SvPVX` is the address of the PV in the SV.
Line 10 does the actual catenation: the `Move` macro moves a chunk of memory around: we move the string `ptr` to the end of the PV - that's the start of the PV plus its current length. We're moving `len` bytes of type `char`. After doing so, we need to tell Perl we've extended the string, by altering `CUR` to reflect the new length. `SvEND` is a macro which gives us the end of the string, so that needs to be a `"\0"`.
Line 13 manipulates the flags; since we've changed the PV, any IV or NV values will no longer be valid: if we have `$a=10; $a.="6";` we don't want to use the old IV of 10. `SvPOK_only_utf8` is a special UTF-8-aware version of `SvPOK_only`, a macro which turns off the IOK and NOK flags and turns on POK. The final `SvTAINT` is a macro which launders tainted data if taint mode is turned on.
AVs and HVs are more complicated, but SVs are by far the most common variable type being thrown around. Having seen something of how we manipulate these, let's go on and look at how the op tree is constructed.
OP TREES
---------
First, what is the op tree, anyway? The op tree is the parsed representation of your program, as we saw in our section on parsing, and it's the sequence of operations that Perl goes through to execute your program, as we saw in ["Running"](#Running).
An op is a fundamental operation that Perl can perform: all the built-in functions and operators are ops, and there are a series of ops which deal with concepts the interpreter needs internally - entering and leaving a block, ending a statement, fetching a variable, and so on.
The op tree is connected in two ways: you can imagine that there are two "routes" through it, two orders in which you can traverse the tree. First, parse order reflects how the parser understood the code, and secondly, execution order tells perl what order to perform the operations in.
The easiest way to examine the op tree is to stop Perl after it has finished parsing, and get it to dump out the tree. This is exactly what the compiler backends <B::Terse>, <B::Concise> and CPAN module <B::Debug do.
Let's have a look at how Perl sees `$a = $b + $c`:
```
% perl -MO=Terse -e '$a=$b+$c'
1 LISTOP (0x8179888) leave
2 OP (0x81798b0) enter
3 COP (0x8179850) nextstate
4 BINOP (0x8179828) sassign
5 BINOP (0x8179800) add [1]
6 UNOP (0x81796e0) null [15]
7 SVOP (0x80fafe0) gvsv GV (0x80fa4cc) *b
8 UNOP (0x81797e0) null [15]
9 SVOP (0x8179700) gvsv GV (0x80efeb0) *c
10 UNOP (0x816b4f0) null [15]
11 SVOP (0x816dcf0) gvsv GV (0x80fa460) *a
```
Let's start in the middle, at line 4. This is a BINOP, a binary operator, which is at location `0x8179828`. The specific operator in question is `sassign` - scalar assignment - and you can find the code which implements it in the function `pp_sassign` in *pp\_hot.c*. As a binary operator, it has two children: the add operator, providing the result of `$b+$c`, is uppermost on line 5, and the left hand side is on line 10.
Line 10 is the null op: this does exactly nothing. What is that doing there? If you see the null op, it's a sign that something has been optimized away after parsing. As we mentioned in ["Optimization"](#Optimization), the optimization stage sometimes converts two operations into one, for example when fetching a scalar variable. When this happens, instead of rewriting the op tree and cleaning up the dangling pointers, it's easier just to replace the redundant operation with the null op. Originally, the tree would have looked like this:
```
10 SVOP (0x816b4f0) rv2sv [15]
11 SVOP (0x816dcf0) gv GV (0x80fa460) *a
```
That is, fetch the `a` entry from the main symbol table, and then look at the scalar component of it: `gvsv` (`pp_gvsv` in *pp\_hot.c*) happens to do both these things.
The right hand side, starting at line 5 is similar to what we've just seen: we have the `add` op (`pp_add`, also in *pp\_hot.c*) add together two `gvsv`s.
Now, what's this about?
```
1 LISTOP (0x8179888) leave
2 OP (0x81798b0) enter
3 COP (0x8179850) nextstate
```
`enter` and `leave` are scoping ops, and their job is to perform any housekeeping every time you enter and leave a block: lexical variables are tidied up, unreferenced variables are destroyed, and so on. Every program will have those first three lines: `leave` is a list, and its children are all the statements in the block. Statements are delimited by `nextstate`, so a block is a collection of `nextstate` ops, with the ops to be performed for each statement being the children of `nextstate`. `enter` is a single op which functions as a marker.
That's how Perl parsed the program, from top to bottom:
```
Program
|
Statement
|
=
/ \
/ \
$a +
/ \
$b $c
```
However, it's impossible to **perform** the operations in this order: you have to find the values of `$b` and `$c` before you add them together, for instance. So, the other thread that runs through the op tree is the execution order: each op has a field `op_next` which points to the next op to be run, so following these pointers tells us how perl executes the code. We can traverse the tree in this order using the `exec` option to `B::Terse`:
```
% perl -MO=Terse,exec -e '$a=$b+$c'
1 OP (0x8179928) enter
2 COP (0x81798c8) nextstate
3 SVOP (0x81796c8) gvsv GV (0x80fa4d4) *b
4 SVOP (0x8179798) gvsv GV (0x80efeb0) *c
5 BINOP (0x8179878) add [1]
6 SVOP (0x816dd38) gvsv GV (0x80fa468) *a
7 BINOP (0x81798a0) sassign
8 LISTOP (0x8179900) leave
```
This probably makes more sense for a human: enter a block, start a statement. Get the values of `$b` and `$c`, and add them together. Find `$a`, and assign one to the other. Then leave.
The way Perl builds up these op trees in the parsing process can be unravelled by examining *toke.c*, the lexer, and *perly.y*, the YACC grammar. Let's look at the code that constructs the tree for `$a = $b + $c`.
First, we'll look at the `Perl_yylex` function in the lexer. We want to look for `case 'x'`, where x is the first character of the operator. (Incidentally, when looking for the code that handles a keyword, you'll want to search for `KEY_foo` where "foo" is the keyword.) Here is the code that handles assignment (there are quite a few operators beginning with `=`, so most of it is omitted for brevity):
```
1 case '=':
2 s++;
... code that handles == => etc. and pod ...
3 pl_yylval.ival = 0;
4 OPERATOR(ASSIGNOP);
```
We can see on line 4 that our token type is `ASSIGNOP` (`OPERATOR` is a macro, defined in *toke.c*, that returns the token type, among other things). And `+`:
```
1 case '+':
2 {
3 const char tmp = *s++;
... code for ++ ...
4 if (PL_expect == XOPERATOR) {
...
5 Aop(OP_ADD);
6 }
...
7 }
```
Line 4 checks what type of token we are expecting. `Aop` returns a token. If you search for `Aop` elsewhere in *toke.c*, you will see that it returns an `ADDOP` token.
Now that we know the two token types we want to look for in the parser, let's take the piece of *perly.y* we need to construct the tree for `$a = $b + $c`
```
1 term : term ASSIGNOP term
2 { $$ = newASSIGNOP(OPf_STACKED, $1, $2, $3); }
3 | term ADDOP term
4 { $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
```
If you're not used to reading BNF grammars, this is how it works: You're fed certain things by the tokeniser, which generally end up in upper case. `ADDOP` and `ASSIGNOP` are examples of "terminal symbols", because you can't get any simpler than them.
The grammar, lines one and three of the snippet above, tells you how to build up more complex forms. These complex forms, "non-terminal symbols" are generally placed in lower case. `term` here is a non-terminal symbol, representing a single expression.
The grammar gives you the following rule: you can make the thing on the left of the colon if you see all the things on the right in sequence. This is called a "reduction", and the aim of parsing is to completely reduce the input. There are several different ways you can perform a reduction, separated by vertical bars: so, `term` followed by `=` followed by `term` makes a `term`, and `term` followed by `+` followed by `term` can also make a `term`.
So, if you see two terms with an `=` or `+`, between them, you can turn them into a single expression. When you do this, you execute the code in the block on the next line: if you see `=`, you'll do the code in line 2. If you see `+`, you'll do the code in line 4. It's this code which contributes to the op tree.
```
| term ADDOP term
{ $$ = newBINOP($2, 0, scalar($1), scalar($3)); }
```
What this does is creates a new binary op, and feeds it a number of variables. The variables refer to the tokens: `$1` is the first token in the input, `$2` the second, and so on - think regular expression backreferences. `$$` is the op returned from this reduction. So, we call `newBINOP` to create a new binary operator. The first parameter to `newBINOP`, a function in *op.c*, is the op type. It's an addition operator, so we want the type to be `ADDOP`. We could specify this directly, but it's right there as the second token in the input, so we use `$2`. The second parameter is the op's flags: 0 means "nothing special". Then the things to add: the left and right hand side of our expression, in scalar context.
The functions that create ops, which have names like `newUNOP` and `newBINOP`, call a "check" function associated with each op type, before returning the op. The check functions can mangle the op as they see fit, and even replace it with an entirely new one. These functions are defined in *op.c*, and have a `Perl_ck_` prefix. You can find out which check function is used for a particular op type by looking in *regen/opcodes*. Take `OP_ADD`, for example. (`OP_ADD` is the token value from the `Aop(OP_ADD)` in *toke.c* which the parser passes to `newBINOP` as its first argument.) Here is the relevant line:
```
add addition (+) ck_null IfsT2 S S
```
The check function in this case is `Perl_ck_null`, which does nothing. Let's look at a more interesting case:
```
readline <HANDLE> ck_readline t% F?
```
And here is the function from *op.c*:
```
1 OP *
2 Perl_ck_readline(pTHX_ OP *o)
3 {
4 PERL_ARGS_ASSERT_CK_READLINE;
5
6 if (o->op_flags & OPf_KIDS) {
7 OP *kid = cLISTOPo->op_first;
8 if (kid->op_type == OP_RV2GV)
9 kid->op_private |= OPpALLOW_FAKE;
10 }
11 else {
12 OP * const newop
13 = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0,
14 PL_argvgv));
15 op_free(o);
16 return newop;
17 }
18 return o;
19 }
```
One particularly interesting aspect is that if the op has no kids (i.e., `readline()` or `<>`) the op is freed and replaced with an entirely new one that references `*ARGV` (lines 12-16).
STACKS
------
When perl executes something like `addop`, how does it pass on its results to the next op? The answer is, through the use of stacks. Perl has a number of stacks to store things it's currently working on, and we'll look at the three most important ones here.
###
Argument stack
Arguments are passed to PP code and returned from PP code using the argument stack, `ST`. The typical way to handle arguments is to pop them off the stack, deal with them how you wish, and then push the result back onto the stack. This is how, for instance, the cosine operator works:
```
NV value;
value = POPn;
value = Perl_cos(value);
XPUSHn(value);
```
We'll see a more tricky example of this when we consider Perl's macros below. `POPn` gives you the NV (floating point value) of the top SV on the stack: the `$x` in `cos($x)`. Then we compute the cosine, and push the result back as an NV. The `X` in `XPUSHn` means that the stack should be extended if necessary - it can't be necessary here, because we know there's room for one more item on the stack, since we've just removed one! The `XPUSH*` macros at least guarantee safety.
Alternatively, you can fiddle with the stack directly: `SP` gives you the first element in your portion of the stack, and `TOP*` gives you the top SV/IV/NV/etc. on the stack. So, for instance, to do unary negation of an integer:
```
SETi(-TOPi);
```
Just set the integer value of the top stack entry to its negation.
Argument stack manipulation in the core is exactly the same as it is in XSUBs - see <perlxstut>, <perlxs> and <perlguts> for a longer description of the macros used in stack manipulation.
###
Mark stack
I say "your portion of the stack" above because PP code doesn't necessarily get the whole stack to itself: if your function calls another function, you'll only want to expose the arguments aimed for the called function, and not (necessarily) let it get at your own data. The way we do this is to have a "virtual" bottom-of-stack, exposed to each function. The mark stack keeps bookmarks to locations in the argument stack usable by each function. For instance, when dealing with a tied variable, (internally, something with "P" magic) Perl has to call methods for accesses to the tied variables. However, we need to separate the arguments exposed to the method to the argument exposed to the original function - the store or fetch or whatever it may be. Here's roughly how the tied `push` is implemented; see `av_push` in *av.c*:
```
1 PUSHMARK(SP);
2 EXTEND(SP,2);
3 PUSHs(SvTIED_obj((SV*)av, mg));
4 PUSHs(val);
5 PUTBACK;
6 ENTER;
7 call_method("PUSH", G_SCALAR|G_DISCARD);
8 LEAVE;
```
Let's examine the whole implementation, for practice:
```
1 PUSHMARK(SP);
```
Push the current state of the stack pointer onto the mark stack. This is so that when we've finished adding items to the argument stack, Perl knows how many things we've added recently.
```
2 EXTEND(SP,2);
3 PUSHs(SvTIED_obj((SV*)av, mg));
4 PUSHs(val);
```
We're going to add two more items onto the argument stack: when you have a tied array, the `PUSH` subroutine receives the object and the value to be pushed, and that's exactly what we have here - the tied object, retrieved with `SvTIED_obj`, and the value, the SV `val`.
```
5 PUTBACK;
```
Next we tell Perl to update the global stack pointer from our internal variable: `dSP` only gave us a local copy, not a reference to the global.
```
6 ENTER;
7 call_method("PUSH", G_SCALAR|G_DISCARD);
8 LEAVE;
```
`ENTER` and `LEAVE` localise a block of code - they make sure that all variables are tidied up, everything that has been localised gets its previous value returned, and so on. Think of them as the `{` and `}` of a Perl block.
To actually do the magic method call, we have to call a subroutine in Perl space: `call_method` takes care of that, and it's described in <perlcall>. We call the `PUSH` method in scalar context, and we're going to discard its return value. The call\_method() function removes the top element of the mark stack, so there is nothing for the caller to clean up.
###
Save stack
C doesn't have a concept of local scope, so perl provides one. We've seen that `ENTER` and `LEAVE` are used as scoping braces; the save stack implements the C equivalent of, for example:
```
{
local $foo = 42;
...
}
```
See ["Localizing changes" in perlguts](perlguts#Localizing-changes) for how to use the save stack.
MILLIONS OF MACROS
-------------------
One thing you'll notice about the Perl source is that it's full of macros. Some have called the pervasive use of macros the hardest thing to understand, others find it adds to clarity. Let's take an example, a stripped-down version the code which implements the addition operator:
```
1 PP(pp_add)
2 {
3 dSP; dATARGET;
4 tryAMAGICbin_MG(add_amg, AMGf_assign|AMGf_numeric);
5 {
6 dPOPTOPnnrl_ul;
7 SETn( left + right );
8 RETURN;
9 }
10 }
```
Every line here (apart from the braces, of course) contains a macro. The first line sets up the function declaration as Perl expects for PP code; line 3 sets up variable declarations for the argument stack and the target, the return value of the operation. Line 4 tries to see if the addition operation is overloaded; if so, the appropriate subroutine is called.
Line 6 is another variable declaration - all variable declarations start with `d` - which pops from the top of the argument stack two NVs (hence `nn`) and puts them into the variables `right` and `left`, hence the `rl`. These are the two operands to the addition operator. Next, we call `SETn` to set the NV of the return value to the result of adding the two values. This done, we return - the `RETURN` macro makes sure that our return value is properly handled, and we pass the next operator to run back to the main run loop.
Most of these macros are explained in <perlapi>, and some of the more important ones are explained in <perlxs> as well. Pay special attention to ["Background and MULTIPLICITY" in perlguts](perlguts#Background-and-MULTIPLICITY) for information on the `[pad]THX_?` macros.
FURTHER READING
----------------
For more information on the Perl internals, please see the documents listed at ["Internals and C Language Interface" in perl](perl#Internals-and-C-Language-Interface).
| programming_docs |
perl Pod::Html Pod::Html
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [pod2html](#pod2html)
+ [Auxiliary Functions](#Auxiliary-Functions)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Pod::Html - module to convert pod files to HTML
SYNOPSIS
--------
```
use Pod::Html;
pod2html([options]);
```
DESCRIPTION
-----------
Converts files from pod format (see <perlpod>) to HTML format. It can automatically generate indexes and cross-references, and it keeps a cache of things it knows how to cross-reference.
FUNCTIONS
---------
### pod2html
```
pod2html("pod2html",
"--podpath=lib:ext:pod:vms",
"--podroot=/usr/src/perl",
"--htmlroot=/perl/nmanual",
"--recurse",
"--infile=foo.pod",
"--outfile=/perl/nmanual/foo.html");
```
pod2html takes the following arguments:
backlink
```
--backlink
```
Turns every `head1` heading into a link back to the top of the page. By default, no backlinks are generated.
cachedir
```
--cachedir=name
```
Creates the directory cache in the given directory.
css
```
--css=stylesheet
```
Specify the URL of a cascading style sheet. Also disables all HTML/CSS `style` attributes that are output by default (to avoid conflicts).
flush
```
--flush
```
Flushes the directory cache.
header
```
--header
--noheader
```
Creates header and footer blocks containing the text of the `NAME` section. By default, no headers are generated.
help
```
--help
```
Displays the usage message.
htmldir
```
--htmldir=name
```
Sets the directory to which all cross references in the resulting html file will be relative. Not passing this causes all links to be absolute since this is the value that tells Pod::Html the root of the documentation tree.
Do not use this and --htmlroot in the same call to pod2html; they are mutually exclusive.
htmlroot
```
--htmlroot=name
```
Sets the base URL for the HTML files. When cross-references are made, the HTML root is prepended to the URL.
Do not use this if relative links are desired: use --htmldir instead.
Do not pass both this and --htmldir to pod2html; they are mutually exclusive.
index
```
--index
--noindex
```
Generate an index at the top of the HTML file. This is the default behaviour.
infile
```
--infile=name
```
Specify the pod file to convert. Input is taken from STDIN if no infile is specified.
outfile
```
--outfile=name
```
Specify the HTML file to create. Output goes to STDOUT if no outfile is specified.
poderrors
```
--poderrors
--nopoderrors
```
Include a "POD ERRORS" section in the outfile if there were any POD errors in the infile. This section is included by default.
podpath
```
--podpath=name:...:name
```
Specify which subdirectories of the podroot contain pod files whose HTML converted forms can be linked to in cross references.
podroot
```
--podroot=name
```
Specify the base directory for finding library pods. Default is the current working directory.
quiet
```
--quiet
--noquiet
```
Don't display *mostly harmless* warning messages. These messages will be displayed by default. But this is not the same as `verbose` mode.
recurse
```
--recurse
--norecurse
```
Recurse into subdirectories specified in podpath (default behaviour).
title
```
--title=title
```
Specify the title of the resulting HTML file.
verbose
```
--verbose
--noverbose
```
Display progress messages. By default, they won't be displayed.
###
Auxiliary Functions
Prior to perl-5.36, the following three functions were exported by *Pod::Html*, either by default or on request:
* `htmlify()` (by default)
* `anchorify()` (upon request)
* `relativize_url()` (upon request)
The definition and documentation of these functions have been moved to *Pod::Html::Util*, viewable via `perldoc Pod::Html::Util`.
In perl-5.36, these functions will be importable from either *Pod::Html* or *Pod::Html::Util*. However, beginning with perl-5.38 they will only be importable, upon request, from *Pod::Html::Util*. Please modify your code as needed.
ENVIRONMENT
-----------
Uses `$Config{pod2html}` to setup default options.
AUTHOR
------
Marc Green, <[email protected]>.
Original version by Tom Christiansen, <[email protected]>.
SEE ALSO
---------
<perlpod>
COPYRIGHT
---------
This program is distributed under the Artistic License.
perl Pod::Perldoc::ToXml Pod::Perldoc::ToXml
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToXml - let Perldoc render Pod as XML
SYNOPSIS
--------
```
perldoc -o xml -d out.xml Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Simple::XMLOutStream as a formatter class.
This is actually a Pod::Simple::XMLOutStream subclass, and inherits all its options.
You have to have installed Pod::Simple::XMLOutStream (from the Pod::Simple dist), or this class won't work.
SEE ALSO
---------
<Pod::Simple::XMLOutStream>, <Pod::Simple>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl perlpodspec perlpodspec
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Pod Definitions](#Pod-Definitions)
* [Pod Commands](#Pod-Commands)
* [Pod Formatting Codes](#Pod-Formatting-Codes)
* [Notes on Implementing Pod Processors](#Notes-on-Implementing-Pod-Processors)
* [About L<...> Codes](#About-L%3C...%3E-Codes)
* [About =over...=back Regions](#About-=over...=back-Regions)
* [About Data Paragraphs and "=begin/=end" Regions](#About-Data-Paragraphs-and-%22=begin/=end%22-Regions)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perlpodspec - Plain Old Documentation: format specification and notes
DESCRIPTION
-----------
This document is detailed notes on the Pod markup language. Most people will only have to read <perlpod> to know how to write in Pod, but this document may answer some incidental questions to do with parsing and rendering Pod.
In this document, "must" / "must not", "should" / "should not", and "may" have their conventional (cf. RFC 2119) meanings: "X must do Y" means that if X doesn't do Y, it's against this specification, and should really be fixed. "X should do Y" means that it's recommended, but X may fail to do Y, if there's a good reason. "X may do Y" is merely a note that X can do Y at will (although it is up to the reader to detect any connotation of "and I think it would be *nice* if X did Y" versus "it wouldn't really *bother* me if X did Y").
Notably, when I say "the parser should do Y", the parser may fail to do Y, if the calling application explicitly requests that the parser *not* do Y. I often phrase this as "the parser should, by default, do Y." This doesn't *require* the parser to provide an option for turning off whatever feature Y is (like expanding tabs in verbatim paragraphs), although it implicates that such an option *may* be provided.
Pod Definitions
----------------
Pod is embedded in files, typically Perl source files, although you can write a file that's nothing but Pod.
A **line** in a file consists of zero or more non-newline characters, terminated by either a newline or the end of the file.
A **newline sequence** is usually a platform-dependent concept, but Pod parsers should understand it to mean any of CR (ASCII 13), LF (ASCII 10), or a CRLF (ASCII 13 followed immediately by ASCII 10), in addition to any other system-specific meaning. The first CR/CRLF/LF sequence in the file may be used as the basis for identifying the newline sequence for parsing the rest of the file.
A **blank line** is a line consisting entirely of zero or more spaces (ASCII 32) or tabs (ASCII 9), and terminated by a newline or end-of-file. A **non-blank line** is a line containing one or more characters other than space or tab (and terminated by a newline or end-of-file).
(*Note:* Many older Pod parsers did not accept a line consisting of spaces/tabs and then a newline as a blank line. The only lines they considered blank were lines consisting of *no characters at all*, terminated by a newline.)
**Whitespace** is used in this document as a blanket term for spaces, tabs, and newline sequences. (By itself, this term usually refers to literal whitespace. That is, sequences of whitespace characters in Pod source, as opposed to "E<32>", which is a formatting code that *denotes* a whitespace character.)
A **Pod parser** is a module meant for parsing Pod (regardless of whether this involves calling callbacks or building a parse tree or directly formatting it). A **Pod formatter** (or **Pod translator**) is a module or program that converts Pod to some other format (HTML, plaintext, TeX, PostScript, RTF). A **Pod processor** might be a formatter or translator, or might be a program that does something else with the Pod (like counting words, scanning for index points, etc.).
Pod content is contained in **Pod blocks**. A Pod block starts with a line that matches `m/\A=[a-zA-Z]/`, and continues up to the next line that matches `m/\A=cut/` or up to the end of the file if there is no `m/\A=cut/` line.
Note that a parser is not expected to distinguish between something that looks like pod, but is in a quoted string, such as a here document.
Within a Pod block, there are **Pod paragraphs**. A Pod paragraph consists of non-blank lines of text, separated by one or more blank lines.
For purposes of Pod processing, there are four types of paragraphs in a Pod block:
* A command paragraph (also called a "directive"). The first line of this paragraph must match `m/\A=[a-zA-Z]/`. Command paragraphs are typically one line, as in:
```
=head1 NOTES
=item *
```
But they may span several (non-blank) lines:
```
=for comment
Hm, I wonder what it would look like if
you tried to write a BNF for Pod from this.
=head3 Dr. Strangelove, or: How I Learned to
Stop Worrying and Love the Bomb
```
*Some* command paragraphs allow formatting codes in their content (i.e., after the part that matches `m/\A=[a-zA-Z]\S*\s*/`), as in:
```
=head1 Did You Remember to C<use strict;>?
```
In other words, the Pod processing handler for "head1" will apply the same processing to "Did You Remember to C<use strict;>?" that it would to an ordinary paragraph (i.e., formatting codes like "C<...>") are parsed and presumably formatted appropriately, and whitespace in the form of literal spaces and/or tabs is not significant.
* A **verbatim paragraph**. The first line of this paragraph must be a literal space or tab, and this paragraph must not be inside a "=begin *identifier*", ... "=end *identifier*" sequence unless "*identifier*" begins with a colon (":"). That is, if a paragraph starts with a literal space or tab, but *is* inside a "=begin *identifier*", ... "=end *identifier*" region, then it's a data paragraph, unless "*identifier*" begins with a colon.
Whitespace *is* significant in verbatim paragraphs (although, in processing, tabs are probably expanded).
* An **ordinary paragraph**. A paragraph is an ordinary paragraph if its first line matches neither `m/\A=[a-zA-Z]/` nor `m/\A[ \t]/`, *and* if it's not inside a "=begin *identifier*", ... "=end *identifier*" sequence unless "*identifier*" begins with a colon (":").
* A **data paragraph**. This is a paragraph that *is* inside a "=begin *identifier*" ... "=end *identifier*" sequence where "*identifier*" does *not* begin with a literal colon (":"). In some sense, a data paragraph is not part of Pod at all (i.e., effectively it's "out-of-band"), since it's not subject to most kinds of Pod parsing; but it is specified here, since Pod parsers need to be able to call an event for it, or store it in some form in a parse tree, or at least just parse *around* it.
For example: consider the following paragraphs:
```
# <- that's the 0th column
=head1 Foo
Stuff
$foo->bar
=cut
```
Here, "=head1 Foo" and "=cut" are command paragraphs because the first line of each matches `m/\A=[a-zA-Z]/`. "*[space][space]*$foo->bar" is a verbatim paragraph, because its first line starts with a literal whitespace character (and there's no "=begin"..."=end" region around).
The "=begin *identifier*" ... "=end *identifier*" commands stop paragraphs that they surround from being parsed as ordinary or verbatim paragraphs, if *identifier* doesn't begin with a colon. This is discussed in detail in the section ["About Data Paragraphs and "=begin/=end" Regions"](#About-Data-Paragraphs-and-%22%3Dbegin%2F%3Dend%22-Regions).
Pod Commands
-------------
This section is intended to supplement and clarify the discussion in ["Command Paragraph" in perlpod](perlpod#Command-Paragraph). These are the currently recognized Pod commands:
"=head1", "=head2", "=head3", "=head4", "=head5", "=head6" This command indicates that the text in the remainder of the paragraph is a heading. That text may contain formatting codes. Examples:
```
=head1 Object Attributes
=head3 What B<Not> to Do!
```
Both `=head5` and `=head6` were added in 2020 and might not be supported on all Pod parsers. <Pod::Simple> 3.41 was released on October 2020 and supports both of these providing support for all <Pod::Simple>-based Pod parsers.
"=pod" This command indicates that this paragraph begins a Pod block. (If we are already in the middle of a Pod block, this command has no effect at all.) If there is any text in this command paragraph after "=pod", it must be ignored. Examples:
```
=pod
This is a plain Pod paragraph.
=pod This text is ignored.
```
"=cut" This command indicates that this line is the end of this previously started Pod block. If there is any text after "=cut" on the line, it must be ignored. Examples:
```
=cut
=cut The documentation ends here.
=cut
# This is the first line of program text.
sub foo { # This is the second.
```
It is an error to try to *start* a Pod block with a "=cut" command. In that case, the Pod processor must halt parsing of the input file, and must by default emit a warning.
"=over" This command indicates that this is the start of a list/indent region. If there is any text following the "=over", it must consist of only a nonzero positive numeral. The semantics of this numeral is explained in the ["About =over...=back Regions"](#About-%3Dover...%3Dback-Regions) section, further below. Formatting codes are not expanded. Examples:
```
=over 3
=over 3.5
=over
```
"=item" This command indicates that an item in a list begins here. Formatting codes are processed. The semantics of the (optional) text in the remainder of this paragraph are explained in the ["About =over...=back Regions"](#About-%3Dover...%3Dback-Regions) section, further below. Examples:
```
=item
=item *
=item *
=item 14
=item 3.
=item C<< $thing->stuff(I<dodad>) >>
=item For transporting us beyond seas to be tried for pretended
offenses
=item He is at this time transporting large armies of foreign
mercenaries to complete the works of death, desolation and
tyranny, already begun with circumstances of cruelty and perfidy
scarcely paralleled in the most barbarous ages, and totally
unworthy the head of a civilized nation.
```
"=back" This command indicates that this is the end of the region begun by the most recent "=over" command. It permits no text after the "=back" command.
"=begin formatname"
"=begin formatname parameter" This marks the following paragraphs (until the matching "=end formatname") as being for some special kind of processing. Unless "formatname" begins with a colon, the contained non-command paragraphs are data paragraphs. But if "formatname" *does* begin with a colon, then non-command paragraphs are ordinary paragraphs or data paragraphs. This is discussed in detail in the section ["About Data Paragraphs and "=begin/=end" Regions"](#About-Data-Paragraphs-and-%22%3Dbegin%2F%3Dend%22-Regions).
It is advised that formatnames match the regexp `m/\A:?[-a-zA-Z0-9_]+\z/`. Everything following whitespace after the formatname is a parameter that may be used by the formatter when dealing with this region. This parameter must not be repeated in the "=end" paragraph. Implementors should anticipate future expansion in the semantics and syntax of the first parameter to "=begin"/"=end"/"=for".
"=end formatname" This marks the end of the region opened by the matching "=begin formatname" region. If "formatname" is not the formatname of the most recent open "=begin formatname" region, then this is an error, and must generate an error message. This is discussed in detail in the section ["About Data Paragraphs and "=begin/=end" Regions"](#About-Data-Paragraphs-and-%22%3Dbegin%2F%3Dend%22-Regions).
"=for formatname text..." This is synonymous with:
```
=begin formatname
text...
=end formatname
```
That is, it creates a region consisting of a single paragraph; that paragraph is to be treated as a normal paragraph if "formatname" begins with a ":"; if "formatname" *doesn't* begin with a colon, then "text..." will constitute a data paragraph. There is no way to use "=for formatname text..." to express "text..." as a verbatim paragraph.
"=encoding encodingname" This command, which should occur early in the document (at least before any non-US-ASCII data!), declares that this document is encoded in the encoding *encodingname*, which must be an encoding name that [Encode](encode) recognizes. (Encode's list of supported encodings, in <Encode::Supported>, is useful here.) If the Pod parser cannot decode the declared encoding, it should emit a warning and may abort parsing the document altogether.
A document having more than one "=encoding" line should be considered an error. Pod processors may silently tolerate this if the not-first "=encoding" lines are just duplicates of the first one (e.g., if there's a "=encoding utf8" line, and later on another "=encoding utf8" line). But Pod processors should complain if there are contradictory "=encoding" lines in the same document (e.g., if there is a "=encoding utf8" early in the document and "=encoding big5" later). Pod processors that recognize BOMs may also complain if they see an "=encoding" line that contradicts the BOM (e.g., if a document with a UTF-16LE BOM has an "=encoding shiftjis" line).
If a Pod processor sees any command other than the ones listed above (like "=head", or "=haed1", or "=stuff", or "=cuttlefish", or "=w123"), that processor must by default treat this as an error. It must not process the paragraph beginning with that command, must by default warn of this as an error, and may abort the parse. A Pod parser may allow a way for particular applications to add to the above list of known commands, and to stipulate, for each additional command, whether formatting codes should be processed.
Future versions of this specification may add additional commands.
Pod Formatting Codes
---------------------
(Note that in previous drafts of this document and of perlpod, formatting codes were referred to as "interior sequences", and this term may still be found in the documentation for Pod parsers, and in error messages from Pod processors.)
There are two syntaxes for formatting codes:
* A formatting code starts with a capital letter (just US-ASCII [A-Z]) followed by a "<", any number of characters, and ending with the first matching ">". Examples:
```
That's what I<you> think!
What's C<CORE::dump()> for?
X<C<chmod> and C<unlink()> Under Different Operating Systems>
```
* A formatting code starts with a capital letter (just US-ASCII [A-Z]) followed by two or more "<"'s, one or more whitespace characters, any number of characters, one or more whitespace characters, and ending with the first matching sequence of two or more ">"'s, where the number of ">"'s equals the number of "<"'s in the opening of this formatting code. Examples:
```
That's what I<< you >> think!
C<<< open(X, ">>thing.dat") || die $! >>>
B<< $foo->bar(); >>
```
With this syntax, the whitespace character(s) after the "C<<<" and before the ">>>" (or whatever letter) are *not* renderable. They do not signify whitespace, are merely part of the formatting codes themselves. That is, these are all synonymous:
```
C<thing>
C<< thing >>
C<< thing >>
C<<< thing >>>
C<<<<
thing
>>>>
```
and so on.
Finally, the multiple-angle-bracket form does *not* alter the interpretation of nested formatting codes, meaning that the following four example lines are identical in meaning:
```
B<example: C<$a E<lt>=E<gt> $b>>
B<example: C<< $a <=> $b >>>
B<example: C<< $a E<lt>=E<gt> $b >>>
B<<< example: C<< $a E<lt>=E<gt> $b >> >>>
```
In parsing Pod, a notably tricky part is the correct parsing of (potentially nested!) formatting codes. Implementors should consult the code in the `parse_text` routine in Pod::Parser as an example of a correct implementation.
`I<text>` -- italic text See the brief discussion in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
`B<text>` -- bold text See the brief discussion in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
`C<code>` -- code text See the brief discussion in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
`F<filename>` -- style for filenames See the brief discussion in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
`X<topic name>` -- an index entry See the brief discussion in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
This code is unusual in that most formatters completely discard this code and its content. Other formatters will render it with invisible codes that can be used in building an index of the current document.
`Z<>` -- a null (zero-effect) formatting code Discussed briefly in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes).
This code is unusual in that it should have no content. That is, a processor may complain if it sees `Z<potatoes>`. Whether or not it complains, the *potatoes* text should ignored.
`L<name>` -- a hyperlink The complicated syntaxes of this code are discussed at length in ["Formatting Codes" in perlpod](perlpod#Formatting-Codes), and implementation details are discussed below, in ["About L<...> Codes"](#About-L-Codes). Parsing the contents of L<content> is tricky. Notably, the content has to be checked for whether it looks like a URL, or whether it has to be split on literal "|" and/or "/" (in the right order!), and so on, *before* E<...> codes are resolved.
`E<escape>` -- a character escape See ["Formatting Codes" in perlpod](perlpod#Formatting-Codes), and several points in ["Notes on Implementing Pod Processors"](#Notes-on-Implementing-Pod-Processors).
`S<text>` -- text contains non-breaking spaces This formatting code is syntactically simple, but semantically complex. What it means is that each space in the printable content of this code signifies a non-breaking space.
Consider:
```
C<$x ? $y : $z>
S<C<$x ? $y : $z>>
```
Both signify the monospace (c[ode] style) text consisting of "$x", one space, "?", one space, ":", one space, "$z". The difference is that in the latter, with the S code, those spaces are not "normal" spaces, but instead are non-breaking spaces.
If a Pod processor sees any formatting code other than the ones listed above (as in "N<...>", or "Q<...>", etc.), that processor must by default treat this as an error. A Pod parser may allow a way for particular applications to add to the above list of known formatting codes; a Pod parser might even allow a way to stipulate, for each additional command, whether it requires some form of special processing, as L<...> does.
Future versions of this specification may add additional formatting codes.
Historical note: A few older Pod processors would not see a ">" as closing a "C<" code, if the ">" was immediately preceded by a "-". This was so that this:
```
C<$foo->bar>
```
would parse as equivalent to this:
```
C<$foo-E<gt>bar>
```
instead of as equivalent to a "C" formatting code containing only "$foo-", and then a "bar>" outside the "C" formatting code. This problem has since been solved by the addition of syntaxes like this:
```
C<< $foo->bar >>
```
Compliant parsers must not treat "->" as special.
Formatting codes absolutely cannot span paragraphs. If a code is opened in one paragraph, and no closing code is found by the end of that paragraph, the Pod parser must close that formatting code, and should complain (as in "Unterminated I code in the paragraph starting at line 123: 'Time objects are not...'"). So these two paragraphs:
```
I<I told you not to do this!
Don't make me say it again!>
```
...must *not* be parsed as two paragraphs in italics (with the I code starting in one paragraph and starting in another.) Instead, the first paragraph should generate a warning, but that aside, the above code must parse as if it were:
```
I<I told you not to do this!>
Don't make me say it again!E<gt>
```
(In SGMLish jargon, all Pod commands are like block-level elements, whereas all Pod formatting codes are like inline-level elements.)
Notes on Implementing Pod Processors
-------------------------------------
The following is a long section of miscellaneous requirements and suggestions to do with Pod processing.
* Pod formatters should tolerate lines in verbatim blocks that are of any length, even if that means having to break them (possibly several times, for very long lines) to avoid text running off the side of the page. Pod formatters may warn of such line-breaking. Such warnings are particularly appropriate for lines are over 100 characters long, which are usually not intentional.
* Pod parsers must recognize *all* of the three well-known newline formats: CR, LF, and CRLF. See <perlport>.
* Pod parsers should accept input lines that are of any length.
* Since Perl recognizes a Unicode Byte Order Mark at the start of files as signaling that the file is Unicode encoded as in UTF-16 (whether big-endian or little-endian) or UTF-8, Pod parsers should do the same. Otherwise, the character encoding should be understood as being UTF-8 if the first highbit byte sequence in the file seems valid as a UTF-8 sequence, or otherwise as CP-1252 (earlier versions of this specification used Latin-1 instead of CP-1252).
Future versions of this specification may specify how Pod can accept other encodings. Presumably treatment of other encodings in Pod parsing would be as in XML parsing: whatever the encoding declared by a particular Pod file, content is to be stored in memory as Unicode characters.
* The well known Unicode Byte Order Marks are as follows: if the file begins with the two literal byte values 0xFE 0xFF, this is the BOM for big-endian UTF-16. If the file begins with the two literal byte value 0xFF 0xFE, this is the BOM for little-endian UTF-16. On an ASCII platform, if the file begins with the three literal byte values 0xEF 0xBB 0xBF, this is the BOM for UTF-8. A mechanism portable to EBCDIC platforms is to:
```
my $utf8_bom = "\x{FEFF}";
utf8::encode($utf8_bom);
```
* A naive, but often sufficient heuristic on ASCII platforms, for testing the first highbit byte-sequence in a BOM-less file (whether in code or in Pod!), to see whether that sequence is valid as UTF-8 (RFC 2279) is to check whether that the first byte in the sequence is in the range 0xC2 - 0xFD *and* whether the next byte is in the range 0x80 - 0xBF. If so, the parser may conclude that this file is in UTF-8, and all highbit sequences in the file should be assumed to be UTF-8. Otherwise the parser should treat the file as being in CP-1252. (A better check, and which works on EBCDIC platforms as well, is to pass a copy of the sequence to [utf8::decode()](utf8) which performs a full validity check on the sequence and returns TRUE if it is valid UTF-8, FALSE otherwise. This function is always pre-loaded, is fast because it is written in C, and will only get called at most once, so you don't need to avoid it out of performance concerns.) In the unlikely circumstance that the first highbit sequence in a truly non-UTF-8 file happens to appear to be UTF-8, one can cater to our heuristic (as well as any more intelligent heuristic) by prefacing that line with a comment line containing a highbit sequence that is clearly *not* valid as UTF-8. A line consisting of simply "#", an e-acute, and any non-highbit byte, is sufficient to establish this file's encoding.
* Pod processors must treat a "=for [label] [content...]" paragraph as meaning the same thing as a "=begin [label]" paragraph, content, and an "=end [label]" paragraph. (The parser may conflate these two constructs, or may leave them distinct, in the expectation that the formatter will nevertheless treat them the same.)
* When rendering Pod to a format that allows comments (i.e., to nearly any format other than plaintext), a Pod formatter must insert comment text identifying its name and version number, and the name and version numbers of any modules it might be using to process the Pod. Minimal examples:
```
%% POD::Pod2PS v3.14159, using POD::Parser v1.92
<!-- Pod::HTML v3.14159, using POD::Parser v1.92 -->
{\doccomm generated by Pod::Tree::RTF 3.14159 using Pod::Tree 1.08}
.\" Pod::Man version 3.14159, using POD::Parser version 1.92
```
Formatters may also insert additional comments, including: the release date of the Pod formatter program, the contact address for the author(s) of the formatter, the current time, the name of input file, the formatting options in effect, version of Perl used, etc.
Formatters may also choose to note errors/warnings as comments, besides or instead of emitting them otherwise (as in messages to STDERR, or `die`ing).
* Pod parsers *may* emit warnings or error messages ("Unknown E code E<zslig>!") to STDERR (whether through printing to STDERR, or `warn`ing/`carp`ing, or `die`ing/`croak`ing), but *must* allow suppressing all such STDERR output, and instead allow an option for reporting errors/warnings in some other way, whether by triggering a callback, or noting errors in some attribute of the document object, or some similarly unobtrusive mechanism -- or even by appending a "Pod Errors" section to the end of the parsed form of the document.
* In cases of exceptionally aberrant documents, Pod parsers may abort the parse. Even then, using `die`ing/`croak`ing is to be avoided; where possible, the parser library may simply close the input file and add text like "\*\*\* Formatting Aborted \*\*\*" to the end of the (partial) in-memory document.
* In paragraphs where formatting codes (like E<...>, B<...>) are understood (i.e., *not* verbatim paragraphs, but *including* ordinary paragraphs, and command paragraphs that produce renderable text, like "=head1"), literal whitespace should generally be considered "insignificant", in that one literal space has the same meaning as any (nonzero) number of literal spaces, literal newlines, and literal tabs (as long as this produces no blank lines, since those would terminate the paragraph). Pod parsers should compact literal whitespace in each processed paragraph, but may provide an option for overriding this (since some processing tasks do not require it), or may follow additional special rules (for example, specially treating period-space-space or period-newline sequences).
* Pod parsers should not, by default, try to coerce apostrophe (') and quote (") into smart quotes (little 9's, 66's, 99's, etc), nor try to turn backtick (`) into anything else but a single backtick character (distinct from an open quote character!), nor "--" into anything but two minus signs. They *must never* do any of those things to text in C<...> formatting codes, and never *ever* to text in verbatim paragraphs.
* When rendering Pod to a format that has two kinds of hyphens (-), one that's a non-breaking hyphen, and another that's a breakable hyphen (as in "object-oriented", which can be split across lines as "object-", newline, "oriented"), formatters are encouraged to generally translate "-" to non-breaking hyphen, but may apply heuristics to convert some of these to breaking hyphens.
* Pod formatters should make reasonable efforts to keep words of Perl code from being broken across lines. For example, "Foo::Bar" in some formatting systems is seen as eligible for being broken across lines as "Foo::" newline "Bar" or even "Foo::-" newline "Bar". This should be avoided where possible, either by disabling all line-breaking in mid-word, or by wrapping particular words with internal punctuation in "don't break this across lines" codes (which in some formats may not be a single code, but might be a matter of inserting non-breaking zero-width spaces between every pair of characters in a word.)
* Pod parsers should, by default, expand tabs in verbatim paragraphs as they are processed, before passing them to the formatter or other processor. Parsers may also allow an option for overriding this.
* Pod parsers should, by default, remove newlines from the end of ordinary and verbatim paragraphs before passing them to the formatter. For example, while the paragraph you're reading now could be considered, in Pod source, to end with (and contain) the newline(s) that end it, it should be processed as ending with (and containing) the period character that ends this sentence.
* Pod parsers, when reporting errors, should make some effort to report an approximate line number ("Nested E<>'s in Paragraph #52, near line 633 of Thing/Foo.pm!"), instead of merely noting the paragraph number ("Nested E<>'s in Paragraph #52 of Thing/Foo.pm!"). Where this is problematic, the paragraph number should at least be accompanied by an excerpt from the paragraph ("Nested E<>'s in Paragraph #52 of Thing/Foo.pm, which begins 'Read/write accessor for the C<interest rate> attribute...'").
* Pod parsers, when processing a series of verbatim paragraphs one after another, should consider them to be one large verbatim paragraph that happens to contain blank lines. I.e., these two lines, which have a blank line between them:
```
use Foo;
print Foo->VERSION
```
should be unified into one paragraph ("\tuse Foo;\n\n\tprint Foo->VERSION") before being passed to the formatter or other processor. Parsers may also allow an option for overriding this.
While this might be too cumbersome to implement in event-based Pod parsers, it is straightforward for parsers that return parse trees.
* Pod formatters, where feasible, are advised to avoid splitting short verbatim paragraphs (under twelve lines, say) across pages.
* Pod parsers must treat a line with only spaces and/or tabs on it as a "blank line" such as separates paragraphs. (Some older parsers recognized only two adjacent newlines as a "blank line" but would not recognize a newline, a space, and a newline, as a blank line. This is noncompliant behavior.)
* Authors of Pod formatters/processors should make every effort to avoid writing their own Pod parser. There are already several in CPAN, with a wide range of interface styles -- and one of them, Pod::Simple, comes with modern versions of Perl.
* Characters in Pod documents may be conveyed either as literals, or by number in E<n> codes, or by an equivalent mnemonic, as in E<eacute> which is exactly equivalent to E<233>. The numbers are the Latin1/Unicode values, even on EBCDIC platforms.
When referring to characters by using a E<n> numeric code, numbers in the range 32-126 refer to those well known US-ASCII characters (also defined there by Unicode, with the same meaning), which all Pod formatters must render faithfully. Characters whose E<> numbers are in the ranges 0-31 and 127-159 should not be used (neither as literals, nor as E<number> codes), except for the literal byte-sequences for newline (ASCII 13, ASCII 13 10, or ASCII 10), and tab (ASCII 9).
Numbers in the range 160-255 refer to Latin-1 characters (also defined there by Unicode, with the same meaning). Numbers above 255 should be understood to refer to Unicode characters.
* Be warned that some formatters cannot reliably render characters outside 32-126; and many are able to handle 32-126 and 160-255, but nothing above 255.
* Besides the well-known "E<lt>" and "E<gt>" codes for less-than and greater-than, Pod parsers must understand "E<sol>" for "/" (solidus, slash), and "E<verbar>" for "|" (vertical bar, pipe). Pod parsers should also understand "E<lchevron>" and "E<rchevron>" as legacy codes for characters 171 and 187, i.e., "left-pointing double angle quotation mark" = "left pointing guillemet" and "right-pointing double angle quotation mark" = "right pointing guillemet". (These look like little "<<" and ">>", and they are now preferably expressed with the HTML/XHTML codes "E<laquo>" and "E<raquo>".)
* Pod parsers should understand all "E<html>" codes as defined in the entity declarations in the most recent XHTML specification at `www.W3.org`. Pod parsers must understand at least the entities that define characters in the range 160-255 (Latin-1). Pod parsers, when faced with some unknown "E<*identifier*>" code, shouldn't simply replace it with nullstring (by default, at least), but may pass it through as a string consisting of the literal characters E, less-than, *identifier*, greater-than. Or Pod parsers may offer the alternative option of processing such unknown "E<*identifier*>" codes by firing an event especially for such codes, or by adding a special node-type to the in-memory document tree. Such "E<*identifier*>" may have special meaning to some processors, or some processors may choose to add them to a special error report.
* Pod parsers must also support the XHTML codes "E<quot>" for character 34 (doublequote, "), "E<amp>" for character 38 (ampersand, &), and "E<apos>" for character 39 (apostrophe, ').
* Note that in all cases of "E<whatever>", *whatever* (whether an htmlname, or a number in any base) must consist only of alphanumeric characters -- that is, *whatever* must match `m/\A\w+\z/`. So "E< 0 1 2 3 >" is invalid, because it contains spaces, which aren't alphanumeric characters. This presumably does not *need* special treatment by a Pod processor; " 0 1 2 3 " doesn't look like a number in any base, so it would presumably be looked up in the table of HTML-like names. Since there isn't (and cannot be) an HTML-like entity called " 0 1 2 3 ", this will be treated as an error. However, Pod processors may treat "E< 0 1 2 3 >" or "E<e-acute>" as *syntactically* invalid, potentially earning a different error message than the error message (or warning, or event) generated by a merely unknown (but theoretically valid) htmlname, as in "E<qacute>" [sic]. However, Pod parsers are not required to make this distinction.
* Note that E<number> *must not* be interpreted as simply "codepoint *number* in the current/native character set". It always means only "the character represented by codepoint *number* in Unicode." (This is identical to the semantics of &#*number*; in XML.)
This will likely require many formatters to have tables mapping from treatable Unicode codepoints (such as the "\xE9" for the e-acute character) to the escape sequences or codes necessary for conveying such sequences in the target output format. A converter to \*roff would, for example know that "\xE9" (whether conveyed literally, or via a E<...> sequence) is to be conveyed as "e\\\*'". Similarly, a program rendering Pod in a Mac OS application window, would presumably need to know that "\xE9" maps to codepoint 142 in MacRoman encoding that (at time of writing) is native for Mac OS. Such Unicode2whatever mappings are presumably already widely available for common output formats. (Such mappings may be incomplete! Implementers are not expected to bend over backwards in an attempt to render Cherokee syllabics, Etruscan runes, Byzantine musical symbols, or any of the other weird things that Unicode can encode.) And if a Pod document uses a character not found in such a mapping, the formatter should consider it an unrenderable character.
* If, surprisingly, the implementor of a Pod formatter can't find a satisfactory pre-existing table mapping from Unicode characters to escapes in the target format (e.g., a decent table of Unicode characters to \*roff escapes), it will be necessary to build such a table. If you are in this circumstance, you should begin with the characters in the range 0x00A0 - 0x00FF, which is mostly the heavily used accented characters. Then proceed (as patience permits and fastidiousness compels) through the characters that the (X)HTML standards groups judged important enough to merit mnemonics for. These are declared in the (X)HTML specifications at the www.W3.org site. At time of writing (September 2001), the most recent entity declaration files are:
```
http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent
http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent
http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent
```
Then you can progress through any remaining notable Unicode characters in the range 0x2000-0x204D (consult the character tables at www.unicode.org), and whatever else strikes your fancy. For example, in *xhtml-symbol.ent*, there is the entry:
```
<!ENTITY infin "∞"> <!-- infinity, U+221E ISOtech -->
```
While the mapping "infin" to the character "\x{221E}" will (hopefully) have been already handled by the Pod parser, the presence of the character in this file means that it's reasonably important enough to include in a formatter's table that maps from notable Unicode characters to the codes necessary for rendering them. So for a Unicode-to-\*roff mapping, for example, this would merit the entry:
```
"\x{221E}" => '\(in',
```
It is eagerly hoped that in the future, increasing numbers of formats (and formatters) will support Unicode characters directly (as (X)HTML does with `∞`, `∞`, or `∞`), reducing the need for idiosyncratic mappings of Unicode-to-*my\_escapes*.
* It is up to individual Pod formatter to display good judgement when confronted with an unrenderable character (which is distinct from an unknown E<thing> sequence that the parser couldn't resolve to anything, renderable or not). It is good practice to map Latin letters with diacritics (like "E<eacute>"/"E<233>") to the corresponding unaccented US-ASCII letters (like a simple character 101, "e"), but clearly this is often not feasible, and an unrenderable character may be represented as "?", or the like. In attempting a sane fallback (as from E<233> to "e"), Pod formatters may use the %Latin1Code\_to\_fallback table in <Pod::Escapes>, or <Text::Unidecode>, if available.
For example, this Pod text:
```
magic is enabled if you set C<$Currency> to 'E<euro>'.
```
may be rendered as: "magic is enabled if you set `$Currency` to '*?*'" or as "magic is enabled if you set `$Currency` to '**[euro]**'", or as "magic is enabled if you set `$Currency` to '[x20AC]', etc.
A Pod formatter may also note, in a comment or warning, a list of what unrenderable characters were encountered.
* E<...> may freely appear in any formatting code (other than in another E<...> or in an Z<>). That is, "X<The E<euro>1,000,000 Solution>" is valid, as is "L<The E<euro>1,000,000 Solution|Million::Euros>".
* Some Pod formatters output to formats that implement non-breaking spaces as an individual character (which I'll call "NBSP"), and others output to formats that implement non-breaking spaces just as spaces wrapped in a "don't break this across lines" code. Note that at the level of Pod, both sorts of codes can occur: Pod can contain a NBSP character (whether as a literal, or as a "E<160>" or "E<nbsp>" code); and Pod can contain "S<foo I<bar> baz>" codes, where "mere spaces" (character 32) in such codes are taken to represent non-breaking spaces. Pod parsers should consider supporting the optional parsing of "S<foo I<bar> baz>" as if it were "foo*NBSP*I<bar>*NBSP*baz", and, going the other way, the optional parsing of groups of words joined by NBSP's as if each group were in a S<...> code, so that formatters may use the representation that maps best to what the output format demands.
* Some processors may find that the `S<...>` code is easiest to implement by replacing each space in the parse tree under the content of the S, with an NBSP. But note: the replacement should apply *not* to spaces in *all* text, but *only* to spaces in *printable* text. (This distinction may or may not be evident in the particular tree/event model implemented by the Pod parser.) For example, consider this unusual case:
```
S<L</Autoloaded Functions>>
```
This means that the space in the middle of the visible link text must not be broken across lines. In other words, it's the same as this:
```
L<"AutoloadedE<160>Functions"/Autoloaded Functions>
```
However, a misapplied space-to-NBSP replacement could (wrongly) produce something equivalent to this:
```
L<"AutoloadedE<160>Functions"/AutoloadedE<160>Functions>
```
...which is almost definitely not going to work as a hyperlink (assuming this formatter outputs a format supporting hypertext).
Formatters may choose to just not support the S format code, especially in cases where the output format simply has no NBSP character/code and no code for "don't break this stuff across lines".
* Besides the NBSP character discussed above, implementors are reminded of the existence of the other "special" character in Latin-1, the "soft hyphen" character, also known as "discretionary hyphen", i.e. `E<173>` = `E<0xAD>` = `E<shy>`). This character expresses an optional hyphenation point. That is, it normally renders as nothing, but may render as a "-" if a formatter breaks the word at that point. Pod formatters should, as appropriate, do one of the following: 1) render this with a code with the same meaning (e.g., "\-" in RTF), 2) pass it through in the expectation that the formatter understands this character as such, or 3) delete it.
For example:
```
sigE<shy>action
manuE<shy>script
JarkE<shy>ko HieE<shy>taE<shy>nieE<shy>mi
```
These signal to a formatter that if it is to hyphenate "sigaction" or "manuscript", then it should be done as "sig-*[linebreak]*action" or "manu-*[linebreak]*script" (and if it doesn't hyphenate it, then the `E<shy>` doesn't show up at all). And if it is to hyphenate "Jarkko" and/or "Hietaniemi", it can do so only at the points where there is a `E<shy>` code.
In practice, it is anticipated that this character will not be used often, but formatters should either support it, or delete it.
* If you think that you want to add a new command to Pod (like, say, a "=biblio" command), consider whether you could get the same effect with a for or begin/end sequence: "=for biblio ..." or "=begin biblio" ... "=end biblio". Pod processors that don't understand "=for biblio", etc, will simply ignore it, whereas they may complain loudly if they see "=biblio".
* Throughout this document, "Pod" has been the preferred spelling for the name of the documentation format. One may also use "POD" or "pod". For the documentation that is (typically) in the Pod format, you may use "pod", or "Pod", or "POD". Understanding these distinctions is useful; but obsessing over how to spell them, usually is not.
About L<...> Codes
-------------------
As you can tell from a glance at <perlpod>, the L<...> code is the most complex of the Pod formatting codes. The points below will hopefully clarify what it means and how processors should deal with it.
* In parsing an L<...> code, Pod parsers must distinguish at least four attributes:
First: The link-text. If there is none, this must be `undef`. (E.g., in "L<Perl Functions|perlfunc>", the link-text is "Perl Functions". In "L<Time::HiRes>" and even "L<|Time::HiRes>", there is no link text. Note that link text may contain formatting.)
Second: The possibly inferred link-text; i.e., if there was no real link text, then this is the text that we'll infer in its place. (E.g., for "L<Getopt::Std>", the inferred link text is "Getopt::Std".)
Third: The name or URL, or `undef` if none. (E.g., in "L<Perl Functions|perlfunc>", the name (also sometimes called the page) is "perlfunc". In "L</CAVEATS>", the name is `undef`.)
Fourth: The section (AKA "item" in older perlpods), or `undef` if none. E.g., in "L<Getopt::Std/DESCRIPTION>", "DESCRIPTION" is the section. (Note that this is not the same as a manpage section like the "5" in "man 5 crontab". "Section Foo" in the Pod sense means the part of the text that's introduced by the heading or item whose text is "Foo".)
Pod parsers may also note additional attributes including:
Fifth: A flag for whether item 3 (if present) is a URL (like "http://lists.perl.org" is), in which case there should be no section attribute; a Pod name (like "perldoc" and "Getopt::Std" are); or possibly a man page name (like "crontab(5)" is).
Sixth: The raw original L<...> content, before text is split on "|", "/", etc, and before E<...> codes are expanded.
(The above were numbered only for concise reference below. It is not a requirement that these be passed as an actual list or array.)
For example:
```
L<Foo::Bar>
=> undef, # link text
"Foo::Bar", # possibly inferred link text
"Foo::Bar", # name
undef, # section
'pod', # what sort of link
"Foo::Bar" # original content
L<Perlport's section on NL's|perlport/Newlines>
=> "Perlport's section on NL's", # link text
"Perlport's section on NL's", # possibly inferred link text
"perlport", # name
"Newlines", # section
'pod', # what sort of link
"Perlport's section on NL's|perlport/Newlines"
# original content
L<perlport/Newlines>
=> undef, # link text
'"Newlines" in perlport', # possibly inferred link text
"perlport", # name
"Newlines", # section
'pod', # what sort of link
"perlport/Newlines" # original content
L<crontab(5)/"DESCRIPTION">
=> undef, # link text
'"DESCRIPTION" in crontab(5)', # possibly inferred link text
"crontab(5)", # name
"DESCRIPTION", # section
'man', # what sort of link
'crontab(5)/"DESCRIPTION"' # original content
L</Object Attributes>
=> undef, # link text
'"Object Attributes"', # possibly inferred link text
undef, # name
"Object Attributes", # section
'pod', # what sort of link
"/Object Attributes" # original content
L<https://www.perl.org/>
=> undef, # link text
"https://www.perl.org/", # possibly inferred link text
"https://www.perl.org/", # name
undef, # section
'url', # what sort of link
"https://www.perl.org/" # original content
L<Perl.org|https://www.perl.org/>
=> "Perl.org", # link text
"https://www.perl.org/", # possibly inferred link text
"https://www.perl.org/", # name
undef, # section
'url', # what sort of link
"Perl.org|https://www.perl.org/" # original content
```
Note that you can distinguish URL-links from anything else by the fact that they match `m/\A\w+:[^:\s]\S*\z/`. So `L<http://www.perl.com>` is a URL, but `L<HTTP::Response>` isn't.
* In case of L<...> codes with no "text|" part in them, older formatters have exhibited great variation in actually displaying the link or cross reference. For example, L<crontab(5)> would render as "the `crontab(5)` manpage", or "in the `crontab(5)` manpage" or just "`crontab(5)`".
Pod processors must now treat "text|"-less links as follows:
```
L<name> => L<name|name>
L</section> => L<"section"|/section>
L<name/section> => L<"section" in name|name/section>
```
* Note that section names might contain markup. I.e., if a section starts with:
```
=head2 About the C<-M> Operator
```
or with:
```
=item About the C<-M> Operator
```
then a link to it would look like this:
```
L<somedoc/About the C<-M> Operator>
```
Formatters may choose to ignore the markup for purposes of resolving the link and use only the renderable characters in the section name, as in:
```
<h1><a name="About_the_-M_Operator">About the <code>-M</code>
Operator</h1>
...
<a href="somedoc#About_the_-M_Operator">About the <code>-M</code>
Operator" in somedoc</a>
```
* Previous versions of perlpod distinguished `L<name/"section">` links from `L<name/item>` links (and their targets). These have been merged syntactically and semantically in the current specification, and *section* can refer either to a "=head*n* Heading Content" command or to a "=item Item Content" command. This specification does not specify what behavior should be in the case of a given document having several things all seeming to produce the same *section* identifier (e.g., in HTML, several things all producing the same *anchorname* in <a name="*anchorname*">...</a> elements). Where Pod processors can control this behavior, they should use the first such anchor. That is, `L<Foo/Bar>` refers to the *first* "Bar" section in Foo.
But for some processors/formats this cannot be easily controlled; as with the HTML example, the behavior of multiple ambiguous <a name="*anchorname*">...</a> is most easily just left up to browsers to decide.
* In a `L<text|...>` code, text may contain formatting codes for formatting or for E<...> escapes, as in:
```
L<B<ummE<234>stuff>|...>
```
For `L<...>` codes without a "name|" part, only `E<...>` and `Z<>` codes may occur. That is, authors should not use "`L<B<Foo::Bar>>`".
Note, however, that formatting codes and Z<>'s can occur in any and all parts of an L<...> (i.e., in *name*, *section*, *text*, and *url*).
Authors must not nest L<...> codes. For example, "L<The L<Foo::Bar> man page>" should be treated as an error.
* Note that Pod authors may use formatting codes inside the "text" part of "L<text|name>" (and so on for L<text|/"sec">).
In other words, this is valid:
```
Go read L<the docs on C<$.>|perlvar/"$.">
```
Some output formats that do allow rendering "L<...>" codes as hypertext, might not allow the link-text to be formatted; in that case, formatters will have to just ignore that formatting.
* At time of writing, `L<name>` values are of two types: either the name of a Pod page like `L<Foo::Bar>` (which might be a real Perl module or program in an @INC / PATH directory, or a .pod file in those places); or the name of a Unix man page, like `L<crontab(5)>`. In theory, `L<chmod>` is ambiguous between a Pod page called "chmod", or the Unix man page "chmod" (in whatever man-section). However, the presence of a string in parens, as in "crontab(5)", is sufficient to signal that what is being discussed is not a Pod page, and so is presumably a Unix man page. The distinction is of no importance to many Pod processors, but some processors that render to hypertext formats may need to distinguish them in order to know how to render a given `L<foo>` code.
* Previous versions of perlpod allowed for a `L<section>` syntax (as in `L<Object Attributes>`), which was not easily distinguishable from `L<name>` syntax and for `L<"section">` which was only slightly less ambiguous. This syntax is no longer in the specification, and has been replaced by the `L</section>` syntax (where the slash was formerly optional). Pod parsers should tolerate the `L<"section">` syntax, for a while at least. The suggested heuristic for distinguishing `L<section>` from `L<name>` is that if it contains any whitespace, it's a *section*. Pod processors should warn about this being deprecated syntax.
About =over...=back Regions
----------------------------
"=over"..."=back" regions are used for various kinds of list-like structures. (I use the term "region" here simply as a collective term for everything from the "=over" to the matching "=back".)
* The non-zero numeric *indentlevel* in "=over *indentlevel*" ... "=back" is used for giving the formatter a clue as to how many "spaces" (ems, or roughly equivalent units) it should tab over, although many formatters will have to convert this to an absolute measurement that may not exactly match with the size of spaces (or M's) in the document's base font. Other formatters may have to completely ignore the number. The lack of any explicit *indentlevel* parameter is equivalent to an *indentlevel* value of 4. Pod processors may complain if *indentlevel* is present but is not a positive number matching `m/\A(\d*\.)?\d+\z/`.
* Authors of Pod formatters are reminded that "=over" ... "=back" may map to several different constructs in your output format. For example, in converting Pod to (X)HTML, it can map to any of <ul>...</ul>, <ol>...</ol>, <dl>...</dl>, or <blockquote>...</blockquote>. Similarly, "=item" can map to <li> or <dt>.
* Each "=over" ... "=back" region should be one of the following:
+ An "=over" ... "=back" region containing only "=item \*" commands, each followed by some number of ordinary/verbatim paragraphs, other nested "=over" ... "=back" regions, "=for..." paragraphs, and "=begin"..."=end" regions.
(Pod processors must tolerate a bare "=item" as if it were "=item \*".) Whether "\*" is rendered as a literal asterisk, an "o", or as some kind of real bullet character, is left up to the Pod formatter, and may depend on the level of nesting.
+ An "=over" ... "=back" region containing only `m/\A=item\s+\d+\.?\s*\z/` paragraphs, each one (or each group of them) followed by some number of ordinary/verbatim paragraphs, other nested "=over" ... "=back" regions, "=for..." paragraphs, and/or "=begin"..."=end" codes. Note that the numbers must start at 1 in each section, and must proceed in order and without skipping numbers.
(Pod processors must tolerate lines like "=item 1" as if they were "=item 1.", with the period.)
+ An "=over" ... "=back" region containing only "=item [text]" commands, each one (or each group of them) followed by some number of ordinary/verbatim paragraphs, other nested "=over" ... "=back" regions, or "=for..." paragraphs, and "=begin"..."=end" regions.
The "=item [text]" paragraph should not match `m/\A=item\s+\d+\.?\s*\z/` or `m/\A=item\s+\*\s*\z/`, nor should it match just `m/\A=item\s*\z/`.
+ An "=over" ... "=back" region containing no "=item" paragraphs at all, and containing only some number of ordinary/verbatim paragraphs, and possibly also some nested "=over" ... "=back" regions, "=for..." paragraphs, and "=begin"..."=end" regions. Such an itemless "=over" ... "=back" region in Pod is equivalent in meaning to a "<blockquote>...</blockquote>" element in HTML.Note that with all the above cases, you can determine which type of "=over" ... "=back" you have, by examining the first (non-"=cut", non-"=pod") Pod paragraph after the "=over" command.
* Pod formatters *must* tolerate arbitrarily large amounts of text in the "=item *text...*" paragraph. In practice, most such paragraphs are short, as in:
```
=item For cutting off our trade with all parts of the world
```
But they may be arbitrarily long:
```
=item For transporting us beyond seas to be tried for pretended
offenses
=item He is at this time transporting large armies of foreign
mercenaries to complete the works of death, desolation and
tyranny, already begun with circumstances of cruelty and perfidy
scarcely paralleled in the most barbarous ages, and totally
unworthy the head of a civilized nation.
```
* Pod processors should tolerate "=item \*" / "=item *number*" commands with no accompanying paragraph. The middle item is an example:
```
=over
=item 1
Pick up dry cleaning.
=item 2
=item 3
Stop by the store. Get Abba Zabas, Stoli, and cheap lawn chairs.
=back
```
* No "=over" ... "=back" region can contain headings. Processors may treat such a heading as an error.
* Note that an "=over" ... "=back" region should have some content. That is, authors should not have an empty region like this:
```
=over
=back
```
Pod processors seeing such a contentless "=over" ... "=back" region, may ignore it, or may report it as an error.
* Processors must tolerate an "=over" list that goes off the end of the document (i.e., which has no matching "=back"), but they may warn about such a list.
* Authors of Pod formatters should note that this construct:
```
=item Neque
=item Porro
=item Quisquam Est
Qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut
labore et dolore magnam aliquam quaerat voluptatem.
=item Ut Enim
```
is semantically ambiguous, in a way that makes formatting decisions a bit difficult. On the one hand, it could be mention of an item "Neque", mention of another item "Porro", and mention of another item "Quisquam Est", with just the last one requiring the explanatory paragraph "Qui dolorem ipsum quia dolor..."; and then an item "Ut Enim". In that case, you'd want to format it like so:
```
Neque
Porro
Quisquam Est
Qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut
labore et dolore magnam aliquam quaerat voluptatem.
Ut Enim
```
But it could equally well be a discussion of three (related or equivalent) items, "Neque", "Porro", and "Quisquam Est", followed by a paragraph explaining them all, and then a new item "Ut Enim". In that case, you'd probably want to format it like so:
```
Neque
Porro
Quisquam Est
Qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut
labore et dolore magnam aliquam quaerat voluptatem.
Ut Enim
```
But (for the foreseeable future), Pod does not provide any way for Pod authors to distinguish which grouping is meant by the above "=item"-cluster structure. So formatters should format it like so:
```
Neque
Porro
Quisquam Est
Qui dolorem ipsum quia dolor sit amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt ut
labore et dolore magnam aliquam quaerat voluptatem.
Ut Enim
```
That is, there should be (at least roughly) equal spacing between items as between paragraphs (although that spacing may well be less than the full height of a line of text). This leaves it to the reader to use (con)textual cues to figure out whether the "Qui dolorem ipsum..." paragraph applies to the "Quisquam Est" item or to all three items "Neque", "Porro", and "Quisquam Est". While not an ideal situation, this is preferable to providing formatting cues that may be actually contrary to the author's intent.
About Data Paragraphs and "=begin/=end" Regions
------------------------------------------------
Data paragraphs are typically used for inlining non-Pod data that is to be used (typically passed through) when rendering the document to a specific format:
```
=begin rtf
\par{\pard\qr\sa4500{\i Printed\~\chdate\~\chtime}\par}
=end rtf
```
The exact same effect could, incidentally, be achieved with a single "=for" paragraph:
```
=for rtf \par{\pard\qr\sa4500{\i Printed\~\chdate\~\chtime}\par}
```
(Although that is not formally a data paragraph, it has the same meaning as one, and Pod parsers may parse it as one.)
Another example of a data paragraph:
```
=begin html
I like <em>PIE</em>!
<hr>Especially pecan pie!
=end html
```
If these were ordinary paragraphs, the Pod parser would try to expand the "E</em>" (in the first paragraph) as a formatting code, just like "E<lt>" or "E<eacute>". But since this is in a "=begin *identifier*"..."=end *identifier*" region *and* the identifier "html" doesn't begin have a ":" prefix, the contents of this region are stored as data paragraphs, instead of being processed as ordinary paragraphs (or if they began with a spaces and/or tabs, as verbatim paragraphs).
As a further example: At time of writing, no "biblio" identifier is supported, but suppose some processor were written to recognize it as a way of (say) denoting a bibliographic reference (necessarily containing formatting codes in ordinary paragraphs). The fact that "biblio" paragraphs were meant for ordinary processing would be indicated by prefacing each "biblio" identifier with a colon:
```
=begin :biblio
Wirth, Niklaus. 1976. I<Algorithms + Data Structures =
Programs.> Prentice-Hall, Englewood Cliffs, NJ.
=end :biblio
```
This would signal to the parser that paragraphs in this begin...end region are subject to normal handling as ordinary/verbatim paragraphs (while still tagged as meant only for processors that understand the "biblio" identifier). The same effect could be had with:
```
=for :biblio
Wirth, Niklaus. 1976. I<Algorithms + Data Structures =
Programs.> Prentice-Hall, Englewood Cliffs, NJ.
```
The ":" on these identifiers means simply "process this stuff normally, even though the result will be for some special target". I suggest that parser APIs report "biblio" as the target identifier, but also report that it had a ":" prefix. (And similarly, with the above "html", report "html" as the target identifier, and note the *lack* of a ":" prefix.)
Note that a "=begin *identifier*"..."=end *identifier*" region where *identifier* begins with a colon, *can* contain commands. For example:
```
=begin :biblio
Wirth's classic is available in several editions, including:
=for comment
hm, check abebooks.com for how much used copies cost.
=over
=item
Wirth, Niklaus. 1975. I<Algorithmen und Datenstrukturen.>
Teubner, Stuttgart. [Yes, it's in German.]
=item
Wirth, Niklaus. 1976. I<Algorithms + Data Structures =
Programs.> Prentice-Hall, Englewood Cliffs, NJ.
=back
=end :biblio
```
Note, however, a "=begin *identifier*"..."=end *identifier*" region where *identifier* does *not* begin with a colon, should not directly contain "=head1" ... "=head4" commands, nor "=over", nor "=back", nor "=item". For example, this may be considered invalid:
```
=begin somedata
This is a data paragraph.
=head1 Don't do this!
This is a data paragraph too.
=end somedata
```
A Pod processor may signal that the above (specifically the "=head1" paragraph) is an error. Note, however, that the following should *not* be treated as an error:
```
=begin somedata
This is a data paragraph.
=cut
# Yup, this isn't Pod anymore.
sub excl { (rand() > .5) ? "hoo!" : "hah!" }
=pod
This is a data paragraph too.
=end somedata
```
And this too is valid:
```
=begin someformat
This is a data paragraph.
And this is a data paragraph.
=begin someotherformat
This is a data paragraph too.
And this is a data paragraph too.
=begin :yetanotherformat
=head2 This is a command paragraph!
This is an ordinary paragraph!
And this is a verbatim paragraph!
=end :yetanotherformat
=end someotherformat
Another data paragraph!
=end someformat
```
The contents of the above "=begin :yetanotherformat" ... "=end :yetanotherformat" region *aren't* data paragraphs, because the immediately containing region's identifier (":yetanotherformat") begins with a colon. In practice, most regions that contain data paragraphs will contain *only* data paragraphs; however, the above nesting is syntactically valid as Pod, even if it is rare. However, the handlers for some formats, like "html", will accept only data paragraphs, not nested regions; and they may complain if they see (targeted for them) nested regions, or commands, other than "=end", "=pod", and "=cut".
Also consider this valid structure:
```
=begin :biblio
Wirth's classic is available in several editions, including:
=over
=item
Wirth, Niklaus. 1975. I<Algorithmen und Datenstrukturen.>
Teubner, Stuttgart. [Yes, it's in German.]
=item
Wirth, Niklaus. 1976. I<Algorithms + Data Structures =
Programs.> Prentice-Hall, Englewood Cliffs, NJ.
=back
Buy buy buy!
=begin html
<img src='wirth_spokesmodeling_book.png'>
<hr>
=end html
Now now now!
=end :biblio
```
There, the "=begin html"..."=end html" region is nested inside the larger "=begin :biblio"..."=end :biblio" region. Note that the content of the "=begin html"..."=end html" region is data paragraph(s), because the immediately containing region's identifier ("html") *doesn't* begin with a colon.
Pod parsers, when processing a series of data paragraphs one after another (within a single region), should consider them to be one large data paragraph that happens to contain blank lines. So the content of the above "=begin html"..."=end html" *may* be stored as two data paragraphs (one consisting of "<img src='wirth\_spokesmodeling\_book.png'>\n" and another consisting of "<hr>\n"), but *should* be stored as a single data paragraph (consisting of "<img src='wirth\_spokesmodeling\_book.png'>\n\n<hr>\n").
Pod processors should tolerate empty "=begin *something*"..."=end *something*" regions, empty "=begin :*something*"..."=end :*something*" regions, and contentless "=for *something*" and "=for :*something*" paragraphs. I.e., these should be tolerated:
```
=for html
=begin html
=end html
=begin :biblio
=end :biblio
```
Incidentally, note that there's no easy way to express a data paragraph starting with something that looks like a command. Consider:
```
=begin stuff
=shazbot
=end stuff
```
There, "=shazbot" will be parsed as a Pod command "shazbot", not as a data paragraph "=shazbot\n". However, you can express a data paragraph consisting of "=shazbot\n" using this code:
```
=for stuff =shazbot
```
The situation where this is necessary, is presumably quite rare.
Note that =end commands must match the currently open =begin command. That is, they must properly nest. For example, this is valid:
```
=begin outer
X
=begin inner
Y
=end inner
Z
=end outer
```
while this is invalid:
```
=begin outer
X
=begin inner
Y
=end outer
Z
=end inner
```
This latter is improper because when the "=end outer" command is seen, the currently open region has the formatname "inner", not "outer". (It just happens that "outer" is the format name of a higher-up region.) This is an error. Processors must by default report this as an error, and may halt processing the document containing that error. A corollary of this is that regions cannot "overlap". That is, the latter block above does not represent a region called "outer" which contains X and Y, overlapping a region called "inner" which contains Y and Z. But because it is invalid (as all apparently overlapping regions would be), it doesn't represent that, or anything at all.
Similarly, this is invalid:
```
=begin thing
=end hting
```
This is an error because the region is opened by "thing", and the "=end" tries to close "hting" [sic].
This is also invalid:
```
=begin thing
=end
```
This is invalid because every "=end" command must have a formatname parameter.
SEE ALSO
---------
<perlpod>, ["PODs: Embedded Documentation" in perlsyn](perlsyn#PODs%3A-Embedded-Documentation), <podchecker>
AUTHOR
------
Sean M. Burke
| programming_docs |
perl Pod::Simple::HTMLBatch Pod::Simple::HTMLBatch
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [FROM THE COMMAND LINE](#FROM-THE-COMMAND-LINE)
* [MAIN METHODS](#MAIN-METHODS)
+ [ACCESSOR METHODS](#ACCESSOR-METHODS)
* [NOTES ON CUSTOMIZATION](#NOTES-ON-CUSTOMIZATION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::HTMLBatch - convert several Pod files to several HTML files
SYNOPSIS
--------
```
perl -MPod::Simple::HTMLBatch -e 'Pod::Simple::HTMLBatch::go' in out
```
DESCRIPTION
-----------
This module is used for running batch-conversions of a lot of HTML documents
This class is NOT a subclass of Pod::Simple::HTML (nor of bad old Pod::Html) -- although it uses Pod::Simple::HTML for doing the conversion of each document.
The normal use of this class is like so:
```
use Pod::Simple::HTMLBatch;
my $batchconv = Pod::Simple::HTMLBatch->new;
$batchconv->some_option( some_value );
$batchconv->some_other_option( some_other_value );
$batchconv->batch_convert( \@search_dirs, $output_dir );
```
###
FROM THE COMMAND LINE
Note that this class also provides (but does not export) the function Pod::Simple::HTMLBatch::go. This is basically just a shortcut for `Pod::Simple::HTMLBatch->batch_convert(@ARGV)`. It's meant to be handy for calling from the command line.
However, the shortcut requires that you specify exactly two command-line arguments, `indirs` and `outdir`.
Example:
```
% mkdir out_html
% perl -MPod::Simple::HTMLBatch -e Pod::Simple::HTMLBatch::go @INC out_html
(to convert the pod from Perl's @INC
files under the directory ./out_html)
```
(Note that the command line there contains a literal atsign-I-N-C. This is handled as a special case by batch\_convert, in order to save you having to enter the odd-looking "" as the first command-line parameter when you mean "just use whatever's in @INC".)
Example:
```
% mkdir ../seekrut
% chmod og-rx ../seekrut
% perl -MPod::Simple::HTMLBatch -e Pod::Simple::HTMLBatch::go . ../seekrut
(to convert the pod under the current dir into HTML
files under the directory ./seekrut)
```
Example:
```
% perl -MPod::Simple::HTMLBatch -e Pod::Simple::HTMLBatch::go happydocs .
(to convert all pod from happydocs into the current directory)
```
MAIN METHODS
-------------
$batchconv = Pod::Simple::HTMLBatch->new; This creates a new batch converter. The method doesn't take parameters. To change the converter's attributes, use the ["ACCESSOR METHODS"" in "](#) below.
$batchconv->batch\_convert( *indirs*, *outdir* ); This searches the directories given in *indirs* and writes HTML files for each of these to a corresponding directory in *outdir*. The directory *outdir* must exist.
$batchconv->batch\_convert( undef , ...);
$batchconv->batch\_convert( q{@INC}, ...); These two values for *indirs* specify that the normal Perl @INC
$batchconv->batch\_convert( \@dirs , ...); This specifies that the input directories are the items in the arrayref `\@dirs`.
$batchconv->batch\_convert( "somedir" , ...); This specifies that the director "somedir" is the input. (This can be an absolute or relative path, it doesn't matter.)
A common value you might want would be just "." for the current directory:
```
$batchconv->batch_convert( "." , ...);
```
$batchconv->batch\_convert( 'somedir:someother:also' , ...); This specifies that you want the dirs "somedir", "someother", and "also" scanned, just as if you'd passed the arrayref `[qw( somedir someother also)]`. Note that a ":"-separator is normal under Unix, but Under MSWin, you'll need `'somedir;someother;also'` instead, since the pathsep on MSWin is ";" instead of ":". (And *that* is because ":" often comes up in paths, like `"c:/perl/lib"`.)
(Exactly what separator character should be used, is gotten from `$Config::Config{'path_sep'}`, via the [Config](config) module.)
$batchconv->batch\_convert( ... , undef ); This specifies that you want the HTML output to go into the current directory.
(Note that a missing or undefined value means a different thing in the first slot than in the second. That's so that `batch_convert()` with no arguments (or undef arguments) means "go from @INC, into the current directory.)
$batchconv->batch\_convert( ... , 'somedir' ); This specifies that you want the HTML output to go into the directory 'somedir'. (This can be an absolute or relative path, it doesn't matter.)
Note that you can also call `batch_convert` as a class method, like so:
```
Pod::Simple::HTMLBatch->batch_convert( ... );
```
That is just short for this:
```
Pod::Simple::HTMLBatch-> new-> batch_convert(...);
```
That is, it runs a conversion with default options, for whatever inputdirs and output dir you specify.
###
ACCESSOR METHODS
The following are all accessor methods -- that is, they don't do anything on their own, but just alter the contents of the conversion object, which comprises the options for this particular batch conversion.
We show the "put" form of the accessors below (i.e., the syntax you use for setting the accessor to a specific value). But you can also call each method with no parameters to get its current value. For example, `$self->contents_file()` returns the current value of the contents\_file attribute.
$batchconv->verbose( *nonnegative\_integer* ); This controls how verbose to be during batch conversion, as far as notes to STDOUT (or whatever is `select`'d) about how the conversion is going. If 0, no progress information is printed. If 1 (the default value), some progress information is printed. Higher values print more information.
$batchconv->index( *true-or-false* ); This controls whether or not each HTML page is liable to have a little table of contents at the top (which we call an "index" for historical reasons). This is true by default.
$batchconv->contents\_file( *filename* ); If set, should be the name of a file (in the output directory) to write the HTML index to. The default value is "index.html". If you set this to a false value, no contents file will be written.
$batchconv->contents\_page\_start( *HTML\_string* ); This specifies what string should be put at the beginning of the contents page. The default is a string more or less like this:
```
<html>
<head><title>Perl Documentation</title></head>
<body class='contentspage'>
<h1>Perl Documentation</h1>
```
$batchconv->contents\_page\_end( *HTML\_string* ); This specifies what string should be put at the end of the contents page. The default is a string more or less like this:
```
<p class='contentsfooty'>Generated by
Pod::Simple::HTMLBatch v3.01 under Perl v5.008
<br >At Fri May 14 22:26:42 2004 GMT,
which is Fri May 14 14:26:42 2004 local time.</p>
```
$batchconv->add\_css( $url ); TODO
$batchconv->add\_javascript( $url ); TODO
$batchconv->css\_flurry( *true-or-false* ); If true (the default value), we autogenerate some CSS files in the output directory, and set our HTML files to use those. TODO: continue
$batchconv->javascript\_flurry( *true-or-false* ); If true (the default value), we autogenerate a JavaScript in the output directory, and set our HTML files to use it. Currently, the JavaScript is used only to get the browser to remember what stylesheet it prefers. TODO: continue
$batchconv->no\_contents\_links( *true-or-false* ); TODO
$batchconv->html\_render\_class( *classname* ); This sets what class is used for rendering the files. The default is "Pod::Simple::HTML". If you set it to something else, it should probably be a subclass of Pod::Simple::HTML, and you should `require` or `use` that class so that's it's loaded before Pod::Simple::HTMLBatch tries loading it.
$batchconv->search\_class( *classname* ); This sets what class is used for searching for the files. The default is "Pod::Simple::Search". If you set it to something else, it should probably be a subclass of Pod::Simple::Search, and you should `require` or `use` that class so that's it's loaded before Pod::Simple::HTMLBatch tries loading it.
NOTES ON CUSTOMIZATION
-----------------------
TODO
```
call add_css($someurl) to add stylesheet as alternate
call add_css($someurl,1) to add as primary stylesheet
call add_javascript
subclass Pod::Simple::HTML and set $batchconv->html_render_class to
that classname
and maybe override
$page->batch_mode_page_object_init($self, $module, $infile, $outfile, $depth)
or maybe override
$batchconv->batch_mode_page_object_init($page, $module, $infile, $outfile, $depth)
subclass Pod::Simple::Search and set $batchconv->search_class to
that classname
```
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::HTMLBatch>, <perlpod>, <perlpodspec>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl perllol perllol
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Declaration and Access of Arrays of Arrays](#Declaration-and-Access-of-Arrays-of-Arrays)
+ [Growing Your Own](#Growing-Your-Own)
+ [Access and Printing](#Access-and-Printing)
+ [Slices](#Slices)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
perllol - Manipulating Arrays of Arrays in Perl
DESCRIPTION
-----------
###
Declaration and Access of Arrays of Arrays
The simplest two-level data structure to build in Perl is an array of arrays, sometimes casually called a list of lists. It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures.
An array of an array is just a regular old array @AoA that you can get at with two subscripts, like `$AoA[3][2]`. Here's a declaration of the array:
```
use v5.10; # so we can use say()
# assign to our array, an array of array references
@AoA = (
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
);
say $AoA[2][1];
bart
```
Now you should be very careful that the outer bracket type is a round one, that is, a parenthesis. That's because you're assigning to an @array, so you need parentheses. If you wanted there *not* to be an @AoA, but rather just a reference to it, you could do something more like this:
```
# assign a reference to array of array references
$ref_to_AoA = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
];
say $ref_to_AoA->[2][1];
bart
```
Notice that the outer bracket type has changed, and so our access syntax has also changed. That's because unlike C, in perl you can't freely interchange arrays and references thereto. $ref\_to\_AoA is a reference to an array, whereas @AoA is an array proper. Likewise, `$AoA[2]` is not an array, but an array ref. So how come you can write these:
```
$AoA[2][2]
$ref_to_AoA->[2][2]
```
instead of having to write these:
```
$AoA[2]->[2]
$ref_to_AoA->[2]->[2]
```
Well, that's because the rule is that on adjacent brackets only (whether square or curly), you are free to omit the pointer dereferencing arrow. But you cannot do so for the very first one if it's a scalar containing a reference, which means that $ref\_to\_AoA always needs it.
###
Growing Your Own
That's all well and good for declaration of a fixed data structure, but what if you wanted to add new elements on the fly, or build it up entirely from scratch?
First, let's look at reading it in from a file. This is something like adding a row at a time. We'll assume that there's a flat file in which each line is a row and each word an element. If you're trying to develop an @AoA array containing all these, here's the right way to do that:
```
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
```
You might also have loaded that from a function:
```
for $i ( 1 .. 10 ) {
$AoA[$i] = [ somefunc($i) ];
}
```
Or you might have had a temporary variable sitting around with the array in it.
```
for $i ( 1 .. 10 ) {
@tmp = somefunc($i);
$AoA[$i] = [ @tmp ];
}
```
It's important you make sure to use the `[ ]` array reference constructor. That's because this wouldn't work:
```
$AoA[$i] = @tmp; # WRONG!
```
The reason that doesn't do what you want is because assigning a named array like that to a scalar is taking an array in scalar context, which means just counts the number of elements in @tmp.
If you are running under `use strict` (and if you aren't, why in the world aren't you?), you'll have to add some declarations to make it happy:
```
use strict;
my(@AoA, @tmp);
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
```
Of course, you don't need the temporary array to have a name at all:
```
while (<>) {
push @AoA, [ split ];
}
```
You also don't have to use push(). You could just make a direct assignment if you knew where you wanted to put it:
```
my (@AoA, $i, $line);
for $i ( 0 .. 10 ) {
$line = <>;
$AoA[$i] = [ split " ", $line ];
}
```
or even just
```
my (@AoA, $i);
for $i ( 0 .. 10 ) {
$AoA[$i] = [ split " ", <> ];
}
```
You should in general be leery of using functions that could potentially return lists in scalar context without explicitly stating such. This would be clearer to the casual reader:
```
my (@AoA, $i);
for $i ( 0 .. 10 ) {
$AoA[$i] = [ split " ", scalar(<>) ];
}
```
If you wanted to have a $ref\_to\_AoA variable as a reference to an array, you'd have to do something like this:
```
while (<>) {
push @$ref_to_AoA, [ split ];
}
```
Now you can add new rows. What about adding new columns? If you're dealing with just matrices, it's often easiest to use simple assignment:
```
for $x (1 .. 10) {
for $y (1 .. 10) {
$AoA[$x][$y] = func($x, $y);
}
}
for $x ( 3, 7, 9 ) {
$AoA[$x][20] += func2($x);
}
```
It doesn't matter whether those elements are already there or not: it'll gladly create them for you, setting intervening elements to `undef` as need be.
If you wanted just to append to a row, you'd have to do something a bit funnier looking:
```
# add new columns to an existing row
push $AoA[0]->@*, "wilma", "betty"; # explicit deref
```
###
Access and Printing
Now it's time to print your data structure out. How are you going to do that? Well, if you want only one of the elements, it's trivial:
```
print $AoA[0][0];
```
If you want to print the whole thing, though, you can't say
```
print @AoA; # WRONG
```
because you'll get just references listed, and perl will never automatically dereference things for you. Instead, you have to roll yourself a loop or two. This prints the whole structure, using the shell-style for() construct to loop across the outer set of subscripts.
```
for $aref ( @AoA ) {
say "\t [ @$aref ],";
}
```
If you wanted to keep track of subscripts, you might do this:
```
for $i ( 0 .. $#AoA ) {
say "\t elt $i is [ @{$AoA[$i]} ],";
}
```
or maybe even this. Notice the inner loop.
```
for $i ( 0 .. $#AoA ) {
for $j ( 0 .. $#{$AoA[$i]} ) {
say "elt $i $j is $AoA[$i][$j]";
}
}
```
As you can see, it's getting a bit complicated. That's why sometimes is easier to take a temporary on your way through:
```
for $i ( 0 .. $#AoA ) {
$aref = $AoA[$i];
for $j ( 0 .. $#{$aref} ) {
say "elt $i $j is $AoA[$i][$j]";
}
}
```
Hmm... that's still a bit ugly. How about this:
```
for $i ( 0 .. $#AoA ) {
$aref = $AoA[$i];
$n = @$aref - 1;
for $j ( 0 .. $n ) {
say "elt $i $j is $AoA[$i][$j]";
}
}
```
When you get tired of writing a custom print for your data structures, you might look at the standard [Dumpvalue](dumpvalue) or <Data::Dumper> modules. The former is what the Perl debugger uses, while the latter generates parsable Perl code. For example:
```
use v5.14; # using the + prototype, new to v5.14
sub show(+) {
require Dumpvalue;
state $prettily = new Dumpvalue::
tick => q("),
compactDump => 1, # comment these two lines
# out
veryCompact => 1, # if you want a bigger
# dump
;
dumpValue $prettily @_;
}
# Assign a list of array references to an array.
my @AoA = (
[ "fred", "barney" ],
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
);
push $AoA[0]->@*, "wilma", "betty";
show @AoA;
```
will print out:
```
0 0..3 "fred" "barney" "wilma" "betty"
1 0..2 "george" "jane" "elroy"
2 0..2 "homer" "marge" "bart"
```
Whereas if you comment out the two lines I said you might wish to, then it shows it to you this way instead:
```
0 ARRAY(0x8031d0)
0 "fred"
1 "barney"
2 "wilma"
3 "betty"
1 ARRAY(0x803d40)
0 "george"
1 "jane"
2 "elroy"
2 ARRAY(0x803e10)
0 "homer"
1 "marge"
2 "bart"
```
### Slices
If you want to get at a slice (part of a row) in a multidimensional array, you're going to have to do some fancy subscripting. That's because while we have a nice synonym for single elements via the pointer arrow for dereferencing, no such convenience exists for slices.
Here's how to do one operation using a loop. We'll assume an @AoA variable as before.
```
@part = ();
$x = 4;
for ($y = 7; $y < 13; $y++) {
push @part, $AoA[$x][$y];
}
```
That same loop could be replaced with a slice operation:
```
@part = $AoA[4]->@[ 7..12 ];
```
Now, what if you wanted a *two-dimensional slice*, such as having $x run from 4..8 and $y run from 7 to 12? Hmm... here's the simple way:
```
@newAoA = ();
for ($startx = $x = 4; $x <= 8; $x++) {
for ($starty = $y = 7; $y <= 12; $y++) {
$newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y];
}
}
```
We can reduce some of the looping through slices
```
for ($x = 4; $x <= 8; $x++) {
push @newAoA, [ $AoA[$x]->@[ 7..12 ] ];
}
```
If you were into Schwartzian Transforms, you would probably have selected map for that
```
@newAoA = map { [ $AoA[$_]->@[ 7..12 ] ] } 4 .. 8;
```
Although if your manager accused you of seeking job security (or rapid insecurity) through inscrutable code, it would be hard to argue. :-) If I were you, I'd put that in a function:
```
@newAoA = splice_2D( \@AoA, 4 => 8, 7 => 12 );
sub splice_2D {
my $lrr = shift; # ref to array of array refs!
my ($x_lo, $x_hi,
$y_lo, $y_hi) = @_;
return map {
[ $lrr->[$_]->@[ $y_lo .. $y_hi ] ]
} $x_lo .. $x_hi;
}
```
SEE ALSO
---------
<perldata>, <perlref>, <perldsc>
AUTHOR
------
Tom Christiansen <*[email protected]*>
Last update: Tue Apr 26 18:30:55 MDT 2011
| programming_docs |
perl IO::Socket::INET IO::Socket::INET
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR](#CONSTRUCTOR)
+ [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Socket::INET - Object interface for AF\_INET domain sockets
SYNOPSIS
--------
```
use IO::Socket::INET;
```
DESCRIPTION
-----------
`IO::Socket::INET` provides an object interface to creating and using sockets in the AF\_INET domain. It is built upon the <IO::Socket> interface and inherits all the methods defined by <IO::Socket>.
CONSTRUCTOR
-----------
new ( [ARGS] ) Creates an `IO::Socket::INET` object, which is a reference to a newly created symbol (see the `Symbol` package). `new` optionally takes arguments, these arguments are in key-value pairs.
In addition to the key-value pairs accepted by <IO::Socket>, `IO::Socket::INET` provides.
```
PeerAddr Remote host address <hostname>[:<port>]
PeerHost Synonym for PeerAddr
PeerPort Remote port or service <service>[(<no>)] | <no>
LocalAddr Local host bind address hostname[:port]
LocalHost Synonym for LocalAddr
LocalPort Local host bind port <service>[(<no>)] | <no>
Proto Protocol name (or number) "tcp" | "udp" | ...
Type Socket type SOCK_STREAM | SOCK_DGRAM | ...
Listen Queue size for listen
ReuseAddr Set SO_REUSEADDR before binding
Reuse Set SO_REUSEADDR before binding (deprecated,
prefer ReuseAddr)
ReusePort Set SO_REUSEPORT before binding
Broadcast Set SO_BROADCAST before binding
Timeout Timeout value for various operations
MultiHomed Try all addresses for multi-homed hosts
Blocking Determine if connection will be blocking mode
```
If `Listen` is defined then a listen socket is created, else if the socket type, which is derived from the protocol, is SOCK\_STREAM then connect() is called. If the `Listen` argument is given, but false, the queue size will be set to 5.
Although it is not illegal, the use of `MultiHomed` on a socket which is in non-blocking mode is of little use. This is because the first connect will never fail with a timeout as the connect call will not block.
The `PeerAddr` can be a hostname or the IP-address on the "xx.xx.xx.xx" form. The `PeerPort` can be a number or a symbolic service name. The service name might be followed by a number in parenthesis which is used if the service is not known by the system. The `PeerPort` specification can also be embedded in the `PeerAddr` by preceding it with a ":".
If `Proto` is not given and you specify a symbolic `PeerPort` port, then the constructor will try to derive `Proto` from the service name. As a last resort `Proto` "tcp" is assumed. The `Type` parameter will be deduced from `Proto` if not specified.
If the constructor is only passed a single argument, it is assumed to be a `PeerAddr` specification.
If `Blocking` is set to 0, the connection will be in nonblocking mode. If not specified it defaults to 1 (blocking mode).
Examples:
```
$sock = IO::Socket::INET->new(PeerAddr => 'www.perl.org',
PeerPort => 'http(80)',
Proto => 'tcp');
$sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)');
$sock = IO::Socket::INET->new(Listen => 5,
LocalAddr => 'localhost',
LocalPort => 9000,
Proto => 'tcp');
$sock = IO::Socket::INET->new('127.0.0.1:25');
$sock = IO::Socket::INET->new(
PeerPort => 9999,
PeerAddr => inet_ntoa(INADDR_BROADCAST),
Proto => 'udp',
LocalAddr => 'localhost',
Broadcast => 1 )
or die "Can't bind : $IO::Socket::errstr\n";
```
If the constructor fails it will return `undef` and set the `$IO::Socket::errstr` package variable to contain an error message.
```
$sock = IO::Socket::INET->new(...)
or die "Cannot create socket - $IO::Socket::errstr\n";
```
For legacy reasons the error message is also set into the global `$@` variable, and you may still find older code which looks here instead.
```
$sock = IO::Socket::INET->new(...)
or die "Cannot create socket - $@\n";
```
### METHODS
sockaddr () Return the address part of the sockaddr structure for the socket
sockport () Return the port number that the socket is using on the local host
sockhost () Return the address part of the sockaddr structure for the socket in a text form xx.xx.xx.xx
peeraddr () Return the address part of the sockaddr structure for the socket on the peer host
peerport () Return the port number for the socket on the peer host.
peerhost () Return the address part of the sockaddr structure for the socket on the peer host in a text form xx.xx.xx.xx
SEE ALSO
---------
[Socket](socket), <IO::Socket>
AUTHOR
------
Graham Barr. Currently maintained by the Perl Porters. Please report all bugs at <https://github.com/Perl/perl5/issues>.
COPYRIGHT
---------
Copyright (c) 1996-8 Graham Barr <[email protected]>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Pod::Perldoc::ToRtf Pod::Perldoc::ToRtf
===================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc::ToRtf - let Perldoc render Pod as RTF
SYNOPSIS
--------
```
perldoc -o rtf Some::Modulename
```
DESCRIPTION
-----------
This is a "plug-in" class that allows Perldoc to use Pod::Simple::RTF as a formatter class.
This is actually a Pod::Simple::RTF subclass, and inherits all its options.
You have to have Pod::Simple::RTF installed (from the Pod::Simple dist), or this module won't work.
If Perldoc is running under MSWin and uses this class as a formatter, the output will be opened with *write.exe* or whatever program is specified in the environment variable `RTFREADER`. For example, to specify that RTF files should be opened the same as they are when you double-click them, you would do `set RTFREADER=start.exe` in your *autoexec.bat*.
Handy tip: put `set PERLDOC=-ortf` in your *autoexec.bat* and that will set this class as the default formatter to run when you do `perldoc whatever`.
SEE ALSO
---------
<Pod::Simple::RTF>, <Pod::Simple>, <Pod::Perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl Pod::Simple::DumpAsXML Pod::Simple::DumpAsXML
======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::DumpAsXML -- turn Pod into XML
SYNOPSIS
--------
```
perl -MPod::Simple::DumpAsXML -e \
"exit Pod::Simple::DumpAsXML->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
Pod::Simple::DumpAsXML is a subclass of <Pod::Simple> that parses Pod and turns it into indented and wrapped XML. This class is of interest to people writing Pod formatters based on Pod::Simple.
Pod::Simple::DumpAsXML inherits methods from <Pod::Simple>.
SEE ALSO
---------
<Pod::Simple::XMLOutStream> is rather like this class. Pod::Simple::XMLOutStream's output is space-padded in a way that's better for sending to an XML processor (that is, it has no ignorable whitespace). But Pod::Simple::DumpAsXML's output is much more human-readable, being (more-or-less) one token per line, with line-wrapping.
<Pod::Simple::DumpAsText> is rather like this class, except that it doesn't dump with XML syntax. Try them and see which one you like best!
<Pod::Simple>, <Pod::Simple::DumpAsXML>
The older libraries <Pod::PXML>, <Pod::XML>, <Pod::SAX>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl Carp Carp
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Forcing a Stack Trace](#Forcing-a-Stack-Trace)
+ [Stack Trace formatting](#Stack-Trace-formatting)
* [GLOBAL VARIABLES](#GLOBAL-VARIABLES)
+ [$Carp::MaxEvalLen](#%24Carp::MaxEvalLen)
+ [$Carp::MaxArgLen](#%24Carp::MaxArgLen)
+ [$Carp::MaxArgNums](#%24Carp::MaxArgNums)
+ [$Carp::Verbose](#%24Carp::Verbose)
+ [$Carp::RefArgFormatter](#%24Carp::RefArgFormatter)
+ [@CARP\_NOT](#@CARP_NOT)
+ [%Carp::Internal](#%25Carp::Internal)
+ [%Carp::CarpInternal](#%25Carp::CarpInternal)
+ [$Carp::CarpLevel](#%24Carp::CarpLevel)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
* [CONTRIBUTING](#CONTRIBUTING)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENSE](#LICENSE)
NAME
----
Carp - alternative warn and die for modules
SYNOPSIS
--------
```
use Carp;
# warn user (from perspective of caller)
carp "string trimmed to 80 chars";
# die of errors (from perspective of caller)
croak "We're outta here!";
# die of errors with stack backtrace
confess "not implemented";
# cluck, longmess and shortmess not exported by default
use Carp qw(cluck longmess shortmess);
cluck "This is how we got here!"; # warn with stack backtrace
$long_message = longmess( "message from cluck() or confess()" );
$short_message = shortmess( "message from carp() or croak()" );
```
DESCRIPTION
-----------
The Carp routines are useful in your own modules because they act like `die()` or `warn()`, but with a message which is more likely to be useful to a user of your module. In the case of `cluck()` and `confess()`, that context is a summary of every call in the call-stack; `longmess()` returns the contents of the error message.
For a shorter message you can use `carp()` or `croak()` which report the error as being from where your module was called. `shortmess()` returns the contents of this error message. There is no guarantee that that is where the error was, but it is a good educated guess.
`Carp` takes care not to clobber the status variables `$!` and `$^E` in the course of assembling its error messages. This means that a `$SIG{__DIE__}` or `$SIG{__WARN__}` handler can capture the error information held in those variables, if it is required to augment the error message, and if the code calling `Carp` left useful values there. Of course, `Carp` can't guarantee the latter.
You can also alter the way the output and logic of `Carp` works, by changing some global variables in the `Carp` namespace. See the section on `GLOBAL VARIABLES` below.
Here is a more complete description of how `carp` and `croak` work. What they do is search the call-stack for a function call stack where they have not been told that there shouldn't be an error. If every call is marked safe, they give up and give a full stack backtrace instead. In other words they presume that the first likely looking potential suspect is guilty. Their rules for telling whether a call shouldn't generate errors work as follows:
1. Any call from a package to itself is safe.
2. Packages claim that there won't be errors on calls to or from packages explicitly marked as safe by inclusion in `@CARP_NOT`, or (if that array is empty) `@ISA`. The ability to override what @ISA says is new in 5.8.
3. The trust in item 2 is transitive. If A trusts B, and B trusts C, then A trusts C. So if you do not override `@ISA` with `@CARP_NOT`, then this trust relationship is identical to, "inherits from".
4. Any call from an internal Perl module is safe. (Nothing keeps user modules from marking themselves as internal to Perl, but this practice is discouraged.)
5. Any call to Perl's warning system (eg Carp itself) is safe. (This rule is what keeps it from reporting the error at the point where you call `carp` or `croak`.)
6. `$Carp::CarpLevel` can be set to skip a fixed number of additional call levels. Using this is not recommended because it is very difficult to get it to behave correctly.
###
Forcing a Stack Trace
As a debugging aid, you can force Carp to treat a croak as a confess and a carp as a cluck across *all* modules. In other words, force a detailed stack trace to be given. This can be very helpful when trying to understand why, or from where, a warning or error is being generated.
This feature is enabled by 'importing' the non-existent symbol 'verbose'. You would typically enable it by saying
```
perl -MCarp=verbose script.pl
```
or by including the string `-MCarp=verbose` in the PERL5OPT environment variable.
Alternately, you can set the global variable `$Carp::Verbose` to true. See the `GLOBAL VARIABLES` section below.
###
Stack Trace formatting
At each stack level, the subroutine's name is displayed along with its parameters. For simple scalars, this is sufficient. For complex data types, such as objects and other references, this can simply display `'HASH(0x1ab36d8)'`.
Carp gives two ways to control this.
1. For objects, a method, `CARP_TRACE`, will be called, if it exists. If this method doesn't exist, or it recurses into `Carp`, or it otherwise throws an exception, this is skipped, and Carp moves on to the next option, otherwise checking stops and the string returned is used. It is recommended that the object's type is part of the string to make debugging easier.
2. For any type of reference, `$Carp::RefArgFormatter` is checked (see below). This variable is expected to be a code reference, and the current parameter is passed in. If this function doesn't exist (the variable is undef), or it recurses into `Carp`, or it otherwise throws an exception, this is skipped, and Carp moves on to the next option, otherwise checking stops and the string returned is used.
3. Otherwise, if neither `CARP_TRACE` nor `$Carp::RefArgFormatter` is available, stringify the value ignoring any overloading.
GLOBAL VARIABLES
-----------------
###
$Carp::MaxEvalLen
This variable determines how many characters of a string-eval are to be shown in the output. Use a value of `0` to show all text.
Defaults to `0`.
###
$Carp::MaxArgLen
This variable determines how many characters of each argument to a function to print. Use a value of `0` to show the full length of the argument.
Defaults to `64`.
###
$Carp::MaxArgNums
This variable determines how many arguments to each function to show. Use a false value to show all arguments to a function call. To suppress all arguments, use `-1` or `'0 but true'`.
Defaults to `8`.
###
$Carp::Verbose
This variable makes `carp()` and `croak()` generate stack backtraces just like `cluck()` and `confess()`. This is how `use Carp 'verbose'` is implemented internally.
Defaults to `0`.
###
$Carp::RefArgFormatter
This variable sets a general argument formatter to display references. Plain scalars and objects that implement `CARP_TRACE` will not go through this formatter. Calling `Carp` from within this function is not supported.
```
local $Carp::RefArgFormatter = sub {
require Data::Dumper;
Data::Dumper->Dump($_[0]); # not necessarily safe
};
```
###
@CARP\_NOT
This variable, *in your package*, says which packages are *not* to be considered as the location of an error. The `carp()` and `cluck()` functions will skip over callers when reporting where an error occurred.
NB: This variable must be in the package's symbol table, thus:
```
# These work
our @CARP_NOT; # file scope
use vars qw(@CARP_NOT); # package scope
@My::Package::CARP_NOT = ... ; # explicit package variable
# These don't work
sub xyz { ... @CARP_NOT = ... } # w/o declarations above
my @CARP_NOT; # even at top-level
```
Example of use:
```
package My::Carping::Package;
use Carp;
our @CARP_NOT;
sub bar { .... or _error('Wrong input') }
sub _error {
# temporary control of where'ness, __PACKAGE__ is implicit
local @CARP_NOT = qw(My::Friendly::Caller);
carp(@_)
}
```
This would make `Carp` report the error as coming from a caller not in `My::Carping::Package`, nor from `My::Friendly::Caller`.
Also read the ["DESCRIPTION"](#DESCRIPTION) section above, about how `Carp` decides where the error is reported from.
Use `@CARP_NOT`, instead of `$Carp::CarpLevel`.
Overrides `Carp`'s use of `@ISA`.
###
%Carp::Internal
This says what packages are internal to Perl. `Carp` will never report an error as being from a line in a package that is internal to Perl. For example:
```
$Carp::Internal{ (__PACKAGE__) }++;
# time passes...
sub foo { ... or confess("whatever") };
```
would give a full stack backtrace starting from the first caller outside of \_\_PACKAGE\_\_. (Unless that package was also internal to Perl.)
###
%Carp::CarpInternal
This says which packages are internal to Perl's warning system. For generating a full stack backtrace this is the same as being internal to Perl, the stack backtrace will not start inside packages that are listed in `%Carp::CarpInternal`. But it is slightly different for the summary message generated by `carp` or `croak`. There errors will not be reported on any lines that are calling packages in `%Carp::CarpInternal`.
For example `Carp` itself is listed in `%Carp::CarpInternal`. Therefore the full stack backtrace from `confess` will not start inside of `Carp`, and the short message from calling `croak` is not placed on the line where `croak` was called.
###
$Carp::CarpLevel
This variable determines how many additional call frames are to be skipped that would not otherwise be when reporting where an error occurred on a call to one of `Carp`'s functions. It is fairly easy to count these call frames on calls that generate a full stack backtrace. However it is much harder to do this accounting for calls that generate a short message. Usually people skip too many call frames. If they are lucky they skip enough that `Carp` goes all of the way through the call stack, realizes that something is wrong, and then generates a full stack backtrace. If they are unlucky then the error is reported from somewhere misleading very high in the call stack.
Therefore it is best to avoid `$Carp::CarpLevel`. Instead use `@CARP_NOT`, `%Carp::Internal` and `%Carp::CarpInternal`.
Defaults to `0`.
BUGS
----
The Carp routines don't handle exception objects currently. If called with a first argument that is a reference, they simply call die() or warn(), as appropriate.
SEE ALSO
---------
<Carp::Always>, <Carp::Clan>
CONTRIBUTING
------------
[Carp](carp) is maintained by the perl 5 porters as part of the core perl 5 version control repository. Please see the <perlhack> perldoc for how to submit patches and contribute to it.
AUTHOR
------
The Carp module first appeared in Larry Wall's perl 5.000 distribution. Since then it has been modified by several of the perl 5 porters. Andrew Main (Zefram) <[email protected]> divested Carp into an independent distribution.
COPYRIGHT
---------
Copyright (C) 1994-2013 Larry Wall
Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <[email protected]>
LICENSE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl IO IO
==
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DEPRECATED](#DEPRECATED)
NAME
----
IO - load various IO modules
SYNOPSIS
--------
```
use IO qw(Handle File); # loads IO modules, here IO::Handle, IO::File
use IO; # DEPRECATED
```
DESCRIPTION
-----------
`IO` provides a simple mechanism to load several of the IO modules in one go. The IO modules belonging to the core are:
```
IO::Handle
IO::Seekable
IO::File
IO::Pipe
IO::Socket
IO::Dir
IO::Select
IO::Poll
```
Some other IO modules don't belong to the perl core but can be loaded as well if they have been installed from CPAN. You can discover which ones exist with this query: <https://metacpan.org/search?q=IO%3A%3A>.
For more information on any of these modules, please see its respective documentation.
DEPRECATED
----------
```
use IO; # loads all the modules listed below
```
The loaded modules are IO::Handle, IO::Seekable, IO::File, IO::Pipe, IO::Socket, IO::Dir. You should instead explicitly import the IO modules you want.
perl Net::SMTP Net::SMTP
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Class Methods](#Class-Methods)
* [Object Methods](#Object-Methods)
+ [Addresses](#Addresses)
* [EXAMPLES](#EXAMPLES)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::SMTP - Simple Mail Transfer Protocol Client
SYNOPSIS
--------
```
use Net::SMTP;
# Constructors
$smtp = Net::SMTP->new('mailhost');
$smtp = Net::SMTP->new('mailhost', Timeout => 60);
```
DESCRIPTION
-----------
This module implements a client interface to the SMTP and ESMTP protocol, enabling a perl5 application to talk to SMTP servers. This documentation assumes that you are familiar with the concepts of the SMTP protocol described in RFC2821. With <IO::Socket::SSL> installed it also provides support for implicit and explicit TLS encryption, i.e. SMTPS or SMTP+STARTTLS.
The Net::SMTP class is a subclass of Net::Cmd and (depending on avaibility) of IO::Socket::IP, IO::Socket::INET6 or IO::Socket::INET.
###
Class Methods
`new([$host][, %options])`
This is the constructor for a new Net::SMTP object. `$host` is the name of the remote host to which an SMTP connection is required.
On failure `undef` will be returned and `$@` will contain the reason for the failure.
`$host` is optional. If `$host` is not given then it may instead be passed as the `Host` option described below. If neither is given then the `SMTP_Hosts` specified in `Net::Config` will be used.
`%options` are passed in a hash like fashion, using key and value pairs. Possible options are:
**Hello** - SMTP requires that you identify yourself. This option specifies a string to pass as your mail domain. If not given localhost.localdomain will be used.
**SendHello** - If false then the EHLO (or HELO) command that is normally sent when constructing the object will not be sent. In that case the command will have to be sent manually by calling `hello()` instead.
**Host** - SMTP host to connect to. It may be a single scalar (hostname[:port]), as defined for the `PeerAddr` option in <IO::Socket::INET>, or a reference to an array with hosts to try in turn. The ["host"](#host) method will return the value which was used to connect to the host. Format - `PeerHost` from <IO::Socket::INET> new method.
**Port** - port to connect to. Default - 25 for plain SMTP and 465 for immediate SSL.
**SSL** - If the connection should be done from start with SSL, contrary to later upgrade with `starttls`. You can use SSL arguments as documented in <IO::Socket::SSL>, but it will usually use the right arguments already.
**LocalAddr** and **LocalPort** - These parameters are passed directly to IO::Socket to allow binding the socket to a specific local address and port.
**Domain** - This parameter is passed directly to IO::Socket and makes it possible to enforce IPv4 connections even if <IO::Socket::IP> is used as super class. Alternatively **Family** can be used.
**Timeout** - Maximum time, in seconds, to wait for a response from the SMTP server (default: 120)
**ExactAddresses** - If true then all `$address` arguments must be as defined by `addr-spec` in RFC2822. If not given, or false, then Net::SMTP will attempt to extract the address from the value passed.
**Debug** - Enable debugging information
Example:
```
$smtp = Net::SMTP->new('mailhost',
Hello => 'my.mail.domain',
Timeout => 30,
Debug => 1,
);
# the same
$smtp = Net::SMTP->new(
Host => 'mailhost',
Hello => 'my.mail.domain',
Timeout => 30,
Debug => 1,
);
# the same with direct SSL
$smtp = Net::SMTP->new('mailhost',
Hello => 'my.mail.domain',
Timeout => 30,
Debug => 1,
SSL => 1,
);
# Connect to the default server from Net::config
$smtp = Net::SMTP->new(
Hello => 'my.mail.domain',
Timeout => 30,
);
```
Object Methods
---------------
Unless otherwise stated all methods return either a *true* or *false* value, with *true* meaning that the operation was a success. When a method states that it returns a value, failure will be returned as *undef* or an empty list.
`Net::SMTP` inherits from `Net::Cmd` so methods defined in `Net::Cmd` may be used to send commands to the remote SMTP server in addition to the methods documented here.
`banner()`
Returns the banner message which the server replied with when the initial connection was made.
`domain()`
Returns the domain that the remote SMTP server identified itself as during connection.
`hello($domain)`
Tell the remote server the mail domain which you are in using the EHLO command (or HELO if EHLO fails). Since this method is invoked automatically when the Net::SMTP object is constructed the user should normally not have to call it manually.
`host()`
Returns the value used by the constructor, and passed to IO::Socket::INET, to connect to the host.
`etrn($domain)`
Request a queue run for the `$domain` given.
`starttls(%sslargs)`
Upgrade existing plain connection to SSL. You can use SSL arguments as documented in <IO::Socket::SSL>, but it will usually use the right arguments already.
`auth($username, $password)`
`auth($sasl)`
Attempt SASL authentication. Requires Authen::SASL module. The first form constructs a new Authen::SASL object using the given username and password; the second form uses the given Authen::SASL object.
`mail($address[, %options])`
`send($address)`
`send_or_mail($address)`
`send_and_mail($address)`
Send the appropriate command to the server MAIL, SEND, SOML or SAML. `$address` is the address of the sender. This initiates the sending of a message. The method `recipient` should be called for each address that the message is to be sent to.
The `mail` method can take some additional ESMTP `%options` which is passed in hash like fashion, using key and value pairs. Possible options are:
```
Size => <bytes>
Return => "FULL" | "HDRS"
Bits => "7" | "8" | "binary"
Transaction => <ADDRESS>
Envelope => <ENVID> # xtext-encodes its argument
ENVID => <ENVID> # similar to Envelope, but expects argument encoded
XVERP => 1
AUTH => <submitter> # encoded address according to RFC 2554
```
The `Return` and `Envelope` parameters are used for DSN (Delivery Status Notification).
The submitter address in `AUTH` option is expected to be in a format as required by RFC 2554, in an RFC2821-quoted form and xtext-encoded, or <> .
`reset()`
Reset the status of the server. This may be called after a message has been initiated, but before any data has been sent, to cancel the sending of the message.
`recipient($address[, $address[, ...]][, %options])`
Notify the server that the current message should be sent to all of the addresses given. Each address is sent as a separate command to the server. Should the sending of any address result in a failure then the process is aborted and a *false* value is returned. It is up to the user to call `reset` if they so desire.
The `recipient` method can also pass additional case-sensitive `%options` as an anonymous hash using key and value pairs. Possible options are:
```
Notify => ['NEVER'] or ['SUCCESS','FAILURE','DELAY'] (see below)
ORcpt => <ORCPT>
SkipBad => 1 (to ignore bad addresses)
```
If `SkipBad` is true the `recipient` will not return an error when a bad address is encountered and it will return an array of addresses that did succeed.
```
$smtp->recipient($recipient1,$recipient2); # Good
$smtp->recipient($recipient1,$recipient2, { SkipBad => 1 }); # Good
$smtp->recipient($recipient1,$recipient2, { Notify => ['FAILURE','DELAY'], SkipBad => 1 }); # Good
@goodrecips=$smtp->recipient(@recipients, { Notify => ['FAILURE'], SkipBad => 1 }); # Good
$smtp->recipient("$recipient,$recipient2"); # BAD
```
Notify is used to request Delivery Status Notifications (DSNs), but your SMTP/ESMTP service may not respect this request depending upon its version and your site's SMTP configuration.
Leaving out the Notify option usually defaults an SMTP service to its default behavior equivalent to ['FAILURE'] notifications only, but again this may be dependent upon your site's SMTP configuration.
The NEVER keyword must appear by itself if used within the Notify option and "requests that a DSN not be returned to the sender under any conditions."
```
{Notify => ['NEVER']}
$smtp->recipient(@recipients, { Notify => ['NEVER'], SkipBad => 1 }); # Good
```
You may use any combination of these three values 'SUCCESS','FAILURE','DELAY' in the anonymous array reference as defined by RFC3461 (see <https://www.ietf.org/rfc/rfc3461.txt> for more information. Note: quotations in this topic from same.).
A Notify parameter of 'SUCCESS' or 'FAILURE' "requests that a DSN be issued on successful delivery or delivery failure, respectively."
A Notify parameter of 'DELAY' "indicates the sender's willingness to receive delayed DSNs. Delayed DSNs may be issued if delivery of a message has been delayed for an unusual amount of time (as determined by the Message Transfer Agent (MTA) at which the message is delayed), but the final delivery status (whether successful or failure) cannot be determined. The absence of the DELAY keyword in a NOTIFY parameter requests that a "delayed" DSN NOT be issued under any conditions."
```
{Notify => ['SUCCESS','FAILURE','DELAY']}
$smtp->recipient(@recipients, { Notify => ['FAILURE','DELAY'], SkipBad => 1 }); # Good
```
ORcpt is also part of the SMTP DSN extension according to RFC3461. It is used to pass along the original recipient that the mail was first sent to. The machine that generates a DSN will use this address to inform the sender, because he can't know if recipients get rewritten by mail servers. It is expected to be in a format as required by RFC3461, xtext-encoded.
`to($address[, $address[, ...]])`
`cc($address[, $address[, ...]])`
`bcc($address[, $address[, ...]])`
Synonyms for `recipient`.
`data([$data])`
Initiate the sending of the data from the current message.
`$data` may be a reference to a list or a list and must be encoded by the caller to octets of whatever encoding is required, e.g. by using the Encode module's `encode()` function.
If specified the contents of `$data` and a termination string `".\r\n"` is sent to the server. The result will be true if the data was accepted.
If `$data` is not specified then the result will indicate that the server wishes the data to be sent. The data must then be sent using the `datasend` and `dataend` methods described in <Net::Cmd>.
`bdat($data)`
`bdatlast($data)`
Use the alternate `$data` command "BDAT" of the data chunking service extension defined in RFC1830 for efficiently sending large MIME messages.
`expand($address)`
Request the server to expand the given address Returns an array which contains the text read from the server.
`verify($address)`
Verify that `$address` is a legitimate mailing address.
Most sites usually disable this feature in their SMTP service configuration. Use "Debug => 1" option under new() to see if disabled.
`help([$subject])`
Request help text from the server. Returns the text or undef upon failure
`quit()`
Send the QUIT command to the remote SMTP server and close the socket connection.
`can_inet6()`
Returns whether we can use IPv6.
`can_ssl()`
Returns whether we can use SSL.
### Addresses
Net::SMTP attempts to DWIM with addresses that are passed. For example an application might extract The From: line from an email and pass that to mail(). While this may work, it is not recommended. The application should really use a module like <Mail::Address> to extract the mail address and pass that.
If `ExactAddresses` is passed to the constructor, then addresses should be a valid rfc2821-quoted address, although Net::SMTP will accept the address surrounded by angle brackets.
```
funny user@domain WRONG
"funny user"@domain RIGHT, recommended
<"funny user"@domain> OK
```
EXAMPLES
--------
This example prints the mail domain name of the SMTP server known as mailhost:
```
#!/usr/local/bin/perl -w
use Net::SMTP;
$smtp = Net::SMTP->new('mailhost');
print $smtp->domain,"\n";
$smtp->quit;
```
This example sends a small message to the postmaster at the SMTP server known as mailhost:
```
#!/usr/local/bin/perl -w
use Net::SMTP;
my $smtp = Net::SMTP->new('mailhost');
$smtp->mail($ENV{USER});
if ($smtp->to('postmaster')) {
$smtp->data();
$smtp->datasend("To: postmaster\n");
$smtp->datasend("\n");
$smtp->datasend("A simple test message\n");
$smtp->dataend();
} else {
print "Error: ", $smtp->message();
}
$smtp->quit;
```
EXPORTS
-------
*None*.
KNOWN BUGS
-----------
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
SEE ALSO
---------
<Net::Cmd>, <IO::Socket::SSL>.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 1995-2004 Graham Barr. All rights reserved.
Copyright (C) 2013-2016, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
perl VMS::Stdio VMS::Stdio
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [REVISION](#REVISION)
NAME
----
VMS::Stdio - standard I/O functions via VMS extensions
SYNOPSIS
--------
```
use VMS::Stdio qw( &flush &getname &remove &rewind &setdef &sync
&tmpnam &vmsopen &vmssysopen &waitfh &writeof );
setdef("new:[default.dir]");
$uniquename = tmpnam;
$fh = vmsopen("my.file","rfm=var","alq=100",...) or die $!;
$name = getname($fh);
print $fh "Hello, world!\n";
flush($fh);
sync($fh);
rewind($fh);
$line = <$fh>;
undef $fh; # closes file
$fh = vmssysopen("another.file", O_RDONLY | O_NDELAY, 0, "ctx=bin");
sysread($fh,$data,128);
waitfh($fh);
close($fh);
remove("another.file");
writeof($pipefh);
binmode($fh);
```
DESCRIPTION
-----------
This package gives Perl scripts access via VMS extensions to several C stdio operations not available through Perl's CORE I/O functions. The specific routines are described below. These functions are prototyped as unary operators, with the exception of `vmsopen` and `vmssysopen`, which can take any number of arguments, and `tmpnam`, which takes none.
All of the routines are available for export, though none are exported by default. All of the constants used by `vmssysopen` to specify access modes are exported by default. The routines are associated with the Exporter tag FUNCTIONS, and the constants are associated with the Exporter tag CONSTANTS, so you can more easily choose what you'd like to import:
```
# import constants, but not functions
use VMS::Stdio; # same as use VMS::Stdio qw( :DEFAULT );
# import functions, but not constants
use VMS::Stdio qw( !:CONSTANTS :FUNCTIONS );
# import both
use VMS::Stdio qw( :CONSTANTS :FUNCTIONS );
# import neither
use VMS::Stdio ();
```
Of course, you can also choose to import specific functions by name, as usual.
This package `ISA` IO::File, so that you can call IO::File methods on the handles returned by `vmsopen` and `vmssysopen`. The IO::File package is not initialized, however, until you actually call a method that VMS::Stdio doesn't provide. This is done to save startup time for users who don't wish to use the IO::File methods.
**Note:** In order to conform to naming conventions for Perl extensions and functions, the name of this package was changed to from VMS::stdio to VMS::Stdio as of Perl 5.002, and the names of some routines were changed. For many releases, calls to the old VMS::stdio routines would generate a warning, and then route to the equivalent VMS::Stdio function. This compatibility interface has now been removed.
binmode This function causes the file handle to be reopened with the CRTL's carriage control processing disabled; its effect is the same as that of the `b` access mode in `vmsopen`. After the file is reopened, the file pointer is positioned as close to its position before the call as possible (*i.e.* as close as fsetpos() can get it -- for some record-structured files, it's not possible to return to the exact byte offset in the file). Because the file must be reopened, this function cannot be used on temporary-delete files. `binmode` returns true if successful, and `undef` if not.
Note that the effect of `binmode` differs from that of the binmode() function on operating systems such as Windows and MSDOS, and is not needed to process most types of file.
flush This function causes the contents of stdio buffers for the specified file handle to be flushed. If `undef` is used as the argument to `flush`, all currently open file handles are flushed. Like the CRTL fflush() routine, it does not flush any underlying RMS buffers for the file, so the data may not be flushed all the way to the disk. `flush` returns a true value if successful, and `undef` if not.
getname The `getname` function returns the file specification associated with a Perl I/O handle. If an error occurs, it returns `undef`.
remove This function deletes the file named in its argument, returning a true value if successful and `undef` if not. It differs from the CORE Perl function `unlink` in that it does not try to reset file protection if the original protection does not give you delete access to the file (cf. <perlvms>). In other words, `remove` is equivalent to
```
unlink($file) if VMS::Filespec::candelete($file);
```
rewind `rewind` resets the current position of the specified file handle to the beginning of the file. It's really just a convenience method equivalent in effect to `seek($fh,0,0)`. It returns a true value if successful, and `undef` if it fails.
setdef This function sets the default device and directory for the process. It is identical to the built-in chdir() operator, except that the change persists after Perl exits. It returns a true value on success, and `undef` if it encounters an error.
sync This function flushes buffered data for the specified file handle from stdio and RMS buffers all the way to disk. If successful, it returns a true value; otherwise, it returns `undef`.
tmpnam The `tmpnam` function returns a unique string which can be used as a filename when creating temporary files. If, for some reason, it is unable to generate a name, it returns `undef`.
vmsopen The `vmsopen` function enables you to specify optional RMS arguments to the VMS CRTL when opening a file. Its operation is similar to the built-in Perl `open` function (see <perlfunc> for a complete description), but it will only open normal files; it cannot open pipes or duplicate existing I/O handles. Up to 8 optional arguments may follow the file name. These arguments should be strings which specify optional file characteristics as allowed by the CRTL. (See the CRTL reference manual description of creat() and fopen() for details.) If successful, `vmsopen` returns a VMS::Stdio file handle; if an error occurs, it returns `undef`.
You can use the file handle returned by `vmsopen` just as you would any other Perl file handle. The class VMS::Stdio ISA IO::File, so you can call IO::File methods using the handle returned by `vmsopen`. However, `use`ing VMS::Stdio does not automatically `use` IO::File; you must do so explicitly in your program if you want to call IO::File methods. This is done to avoid the overhead of initializing the IO::File package in programs which intend to use the handle returned by `vmsopen` as a normal Perl file handle only. When the scalar containing a VMS::Stdio file handle is overwritten, `undef`d, or goes out of scope, the associated file is closed automatically.
File characteristic options:
alq=INTEGER Sets the allocation quantity for this file
bls=INTEGER File blocksize
ctx=STRING Sets the context for the file. Takes one of these arguments:
bin Disables LF to CRLF translation
cvt Negates previous setting of `ctx=noctx`
nocvt Disables conversion of FORTRAN carriage control
rec Force record-mode access
stm Force stream mode
xplct Causes records to be flushed *only* when the file is closed, or when an explicit flush is done
deq=INTEGER Sets the default extension quantity
dna=FILESPEC Sets the default filename string. Used to fill in any missing pieces of the filename passed.
fop=STRING File processing option. Takes one or more of the following (in a comma-separated list if there's more than one)
ctg Contiguous.
cbt Contiguous-best-try.
dfw Deferred write; only applicable to files opened for shared access.
dlt Delete file on close.
tef Truncate at end-of-file.
cif Create if nonexistent.
sup Supersede.
scf Submit as command file on close.
spl Spool to system printer on close.
tmd Temporary delete.
tmp Temporary (no file directory).
nef Not end-of-file.
rck Read check compare operation.
wck Write check compare operation.
mxv Maximize version number.
rwo Rewind file on open.
pos Current position.
rwc Rewind file on close.
sqo File can only be processed in a sequential manner.
fsz=INTEGER Fixed header size
gbc=INTEGER Global buffers requested for the file
mbc=INTEGER Multiblock count
mbf=INTEGER Bultibuffer count
mrs=INTEGER Maximum record size
rat=STRING File record attributes. Takes one of the following:
cr Carriage-return control.
blk Disallow records to span block boundaries.
ftn FORTRAN print control.
none Explicitly forces no carriage control.
prn Print file format.
rfm=STRING File record format. Takes one of the following:
fix Fixed-length record format.
stm RMS stream record format.
stmlf Stream format with line-feed terminator.
stmcr Stream format with carriage-return terminator.
var Variable-length record format.
vfc Variable-length record with fixed control.
udf Undefined format
rop=STRING Record processing operations. Takes one or more of the following in a comma-separated list:
asy Asynchronous I/O.
cco Cancel Ctrl/O (used with Terminal I/O).
cvt Capitalizes characters on a read from the terminal.
eof Positions the record stream to the end-of-file for the connect operation only.
nlk Do not lock record.
pmt Enables use of the prompt specified by pmt=usr-prmpt on input from the terminal.
pta Eliminates any information in the type-ahead buffer on a read from the terminal.
rea Locks record for a read operation for this process, while allowing other accessors to read the record.
rlk Locks record for write.
rne Suppresses echoing of input data on the screen as it is entered on the keyboard.
rnf Indicates that Ctrl/U, Ctrl/R, and DELETE are not to be considered control commands on terminal input, but are to be passed to the application program.
rrl Reads regardless of lock.
syncsts Returns success status of RMS$\_SYNCH if the requested service completes its task immediately.
tmo Timeout I/O.
tpt Allows put/write services using sequential record access mode to occur at any point in the file, truncating the file at that point.
ulk Prohibits RMS from automatically unlocking records.
wat Wait until record is available, if currently locked by another stream.
rah Read ahead.
wbh Write behind.
rtv=INTEGER The number of retrieval pointers that RMS has to maintain (0 to 127255)
shr=STRING File sharing options. Choose one of the following:
del Allows users to delete.
get Allows users to read.
mse Allows mainstream access.
nil Prohibits file sharing.
put Allows users to write.
upd Allows users to update.
upi Allows one or more writers.
tmo=INTEGER I/O timeout value
vmssysopen This function bears the same relationship to the CORE function `sysopen` as `vmsopen` does to `open`. Its first three arguments are the name, access flags, and permissions for the file. Like `vmsopen`, it takes up to 8 additional string arguments which specify file characteristics. Its return value is identical to that of `vmsopen`.
The symbolic constants for the mode argument are exported by VMS::Stdio by default, and are also exported by the Fcntl package.
waitfh This function causes Perl to wait for the completion of an I/O operation on the file handle specified as its argument. It is used with handles opened for asynchronous I/O, and performs its task by calling the CRTL routine fwait().
writeof This function writes an EOF to a file handle, if the device driver supports this operation. Its primary use is to send an EOF to a subprocess through a pipe opened for writing without closing the pipe. It returns a true value if successful, and `undef` if it encounters an error.
REVISION
--------
This document was last revised on 13-Oct-1998, for Perl 5.004, 5.005, and 5.6.0.
| programming_docs |
perl autodie::skip autodie::skip
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNPOSIS](#SYNPOSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
autodie::skip - Skip a package when throwing autodie exceptions
SYNPOSIS
--------
```
use parent qw(autodie::skip);
```
DESCRIPTION
-----------
This dummy class exists to signal that the class inheriting it should be skipped when reporting exceptions from autodie. This is useful for utility classes like <Path::Tiny> that wish to report the location of where they were called on failure.
If your class has a better way of doing roles, then you should not load this class and instead simply say that your class *DOES* `autodie::skip` instead.
AUTHOR
------
Copyright 2013, Paul Fenwick <[email protected]>
LICENSE
-------
This module is free software. You may distribute it under the same terms as Perl itself.
SEE ALSO
---------
<autodie>, <autodie::exception>
perl IO::Uncompress::Unzip IO::Uncompress::Unzip
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [unzip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#unzip-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [read](#read)
+ [read](#read1)
+ [getline](#getline)
+ [getc](#getc)
+ [ungetc](#ungetc)
+ [inflateSync](#inflateSync)
+ [getHeaderInfo](#getHeaderInfo)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [nextStream](#nextStream)
+ [trailingData](#trailingData)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
+ [Working with Net::FTP](#Working-with-Net::FTP)
+ [Walking through a zip file](#Walking-through-a-zip-file)
+ [Unzipping a complete zip file to disk](#Unzipping-a-complete-zip-file-to-disk)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::Unzip - Read zip files/buffers
SYNOPSIS
--------
```
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
my $status = unzip $input => $output [,OPTS]
or die "unzip failed: $UnzipError\n";
my $z = IO::Uncompress::Unzip->new( $input [OPTS] )
or die "unzip failed: $UnzipError\n";
$status = $z->read($buffer)
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$line = $z->getline()
$char = $z->getc()
$char = $z->ungetc()
$char = $z->opened()
$status = $z->inflateSync()
$data = $z->trailingData()
$status = $z->nextStream()
$data = $z->getHeaderInfo()
$z->tell()
$z->seek($position, $whence)
$z->binmode()
$z->fileno()
$z->eof()
$z->close()
$UnzipError ;
# IO::File mode
<$z>
read($z, $buffer);
read($z, $buffer, $length);
read($z, $buffer, $length, $offset);
tell($z)
seek($z, $position, $whence)
binmode($z)
fileno($z)
eof($z)
close($z)
```
DESCRIPTION
-----------
This module provides a Perl interface that allows the reading of zlib files/buffers.
For writing zip files/buffers, see the companion module IO::Compress::Zip.
The primary purpose of this module is to provide *streaming* read access to zip files and buffers.
At present the following compression methods are supported by IO::Uncompress::Unzip
Store (0)
Deflate (8)
Bzip2 (12) To read Bzip2 content, the module `IO::Uncompress::Bunzip2` must be installed.
Lzma (14) To read LZMA content, the module `IO::Uncompress::UnLzma` must be installed.
Xz (95) To read Xz content, the module `IO::Uncompress::UnXz` must be installed.
Zstandard (93) To read Zstandard content, the module `IO::Uncompress::UnZstd` must be installed.
Functional Interface
---------------------
A top-level function, `unzip`, is provided to carry out "one-shot" uncompression between buffers and/or files. For finer control over the uncompression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
unzip $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "unzip failed: $UnzipError\n";
```
The functional interface needs Perl5.005 or better.
###
unzip $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`unzip` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the compressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is uncompressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `unzip` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the uncompressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the uncompressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the uncompressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the uncompressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the uncompressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `unzip` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple compressed files/buffers and `$output_filename_or_reference` is a single file/buffer, after uncompression `$output_filename_or_reference` will contain a concatenation of all the uncompressed data from each of the input files/buffers.
###
Optional Parameters
The optional parameters for the one-shot function `unzip` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `unzip` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `unzip` has completed.
This parameter defaults to 0.
`BinModeOut => 0|1`
This option is now a no-op. All files will be written in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all uncompressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any uncompressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any uncompressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any uncompressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all uncompressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any uncompressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all uncompressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any uncompressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any uncompressed data is output.
Defaults to 0.
`MultiStream => 0|1`
If the input file/buffer contains multiple compressed data streams, this option will uncompress the whole lot as a single data stream.
Defaults to 0.
`TrailingData => $scalar`
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option.
### Examples
Say you have a zip file, `file1.zip`, that only contains a single member, you can read it and write the uncompressed data to the file `file1.txt` like this.
```
use strict ;
use warnings ;
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
my $input = "file1.zip";
my $output = "file1.txt";
unzip $input => $output
or die "unzip failed: $UnzipError\n";
```
If you have a zip file that contains multiple members and want to read a specific member from the file, say `"data1"`, use the `Name` option
```
use strict ;
use warnings ;
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
my $input = "file1.zip";
my $output = "file1.txt";
unzip $input => $output, Name => "data1"
or die "unzip failed: $UnzipError\n";
```
Alternatively, if you want to read the `"data1"` member into memory, use a scalar reference for the `output` parameter.
```
use strict ;
use warnings ;
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
my $input = "file1.zip";
my $output ;
unzip $input => \$output, Name => "data1"
or die "unzip failed: $UnzipError\n";
# $output now contains the uncompressed data
```
To read from an existing Perl filehandle, `$input`, and write the uncompressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
use IO::File ;
my $input = IO::File->new( "<file1.zip" )
or die "Cannot open 'file1.zip': $!\n" ;
my $buffer ;
unzip $input => \$buffer
or die "unzip failed: $UnzipError\n";
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::Unzip is shown below
```
my $z = IO::Uncompress::Unzip->new( $input [OPTS] )
or die "IO::Uncompress::Unzip failed: $UnzipError\n";
```
Returns an `IO::Uncompress::Unzip` object on success and undef on failure. The variable `$UnzipError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::Unzip can be used exactly like an <IO::File> filehandle. This means that all normal input file operations can be carried out with `$z`. For example, to read a line from a compressed file/buffer you can use either of these forms
```
$line = $z->getline();
$line = <$z>;
```
The mandatory parameter `$input` is used to determine the source of the compressed data. This parameter can take one of three forms.
A filename If the `$input` parameter is a scalar, it is assumed to be a filename. This file will be opened for reading and the compressed data will be read from it.
A filehandle If the `$input` parameter is a filehandle, the compressed data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input` is a scalar reference, the compressed data will be read from `$$input`.
###
Constructor Options
The option names defined below are case insensitive and can be optionally prefixed by a '-'. So all of the following are valid
```
-AutoClose
-autoclose
AUTOCLOSE
autoclose
```
OPTS is a combination of the following options:
`Name => "membername"`
Open "membername" from the zip file for reading.
`Efs => 0| 1`
When this option is set to true AND the zip archive being read has the "Language Encoding Flag" (EFS) set, the member name is assumed to be encoded in UTF-8.
If the member name in the zip archive is not valid UTF-8 when this optionn is true, the script will die with an error message.
Note that this option only works with Perl 5.8.4 or better.
This option defaults to **false**.
`AutoClose => 0|1`
This option is only valid when the `$input` parameter is a filehandle. If specified, and the value is true, it will result in the file being closed once either the `close` method is called or the IO::Uncompress::Unzip object is destroyed.
This parameter defaults to 0.
`MultiStream => 0|1`
Treats the complete zip file/buffer as a single compressed data stream. When reading in multi-stream mode each member of the zip file/buffer will be uncompressed in turn until the end of the file/buffer is encountered.
This parameter defaults to 0.
`Prime => $string`
This option will uncompress the contents of `$string` before processing the input file/buffer.
This option can be useful when the compressed data is embedded in another file/data structure and it is not possible to work out where the compressed data begins without having to read the first few bytes. If this is the case, the uncompression can be *primed* with these bytes using this option.
`Transparent => 0|1`
If this option is set and the input file/buffer is not compressed data, the module will allow reading of it anyway.
In addition, if the input file/buffer does contain compressed data and there is non-compressed data immediately following it, setting this option will make this module treat the whole file/buffer as a single data stream.
This option defaults to 1.
`BlockSize => $num`
When reading the compressed input data, IO::Uncompress::Unzip will read it in blocks of `$num` bytes.
This option defaults to 4096.
`InputLength => $size`
When present this option will limit the number of compressed bytes read from the input file/buffer to `$size`. This option can be used in the situation where there is useful data directly after the compressed data stream and you know beforehand the exact length of the compressed data stream.
This option is mostly used when reading from a filehandle, in which case the file pointer will be left pointing to the first byte directly after the compressed data stream.
This option defaults to off.
`Append => 0|1`
This option controls what the `read` method does with uncompressed data.
If set to 1, all uncompressed data will be appended to the output parameter of the `read` method.
If set to 0, the contents of the output parameter of the `read` method will be overwritten by the uncompressed data.
Defaults to 0.
`Strict => 0|1`
This option controls whether the extra checks defined below are used when carrying out the decompression. When Strict is on, the extra tests are carried out, when Strict is off they are not.
The default for this option is off.
### Examples
TODO
Methods
-------
### read
Usage is
```
$status = $z->read($buffer)
```
Reads a block of compressed data (the size of the compressed block is determined by the `Buffer` option in the constructor), uncompresses it and writes any uncompressed data into `$buffer`. If the `Append` parameter is set in the constructor, the uncompressed data will be appended to the `$buffer` parameter. Otherwise `$buffer` will be overwritten.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### read
Usage is
```
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$status = read($z, $buffer, $length)
$status = read($z, $buffer, $length, $offset)
```
Attempt to read `$length` bytes of uncompressed data into `$buffer`.
The main difference between this form of the `read` method and the previous one, is that this one will attempt to return *exactly* `$length` bytes. The only circumstances that this function will not is if end-of-file or an IO error is encountered.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### getline
Usage is
```
$line = $z->getline()
$line = <$z>
```
Reads a single line.
This method fully supports the use of the variable `$/` (or `$INPUT_RECORD_SEPARATOR` or `$RS` when `English` is in use) to determine what constitutes an end of line. Paragraph mode, record mode and file slurp mode are all supported.
### getc
Usage is
```
$char = $z->getc()
```
Read a single character.
### ungetc
Usage is
```
$char = $z->ungetc($string)
```
### inflateSync
Usage is
```
$status = $z->inflateSync()
```
TODO
### getHeaderInfo
Usage is
```
$hdr = $z->getHeaderInfo();
@hdrs = $z->getHeaderInfo();
```
This method returns either a hash reference (in scalar context) or a list or hash references (in array context) that contains information about each of the header fields in the compressed data stream(s).
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the end of the compressed input stream has been reached.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the input file/buffer. It is a fatal error to attempt to seek backward.
Note that the implementation of `seek` in this module does not provide true random access to a compressed file/buffer. It works by uncompressing data from the current offset in the file/buffer until it reaches the uncompressed offset specified in the parameters to `seek`. For very small files this may be acceptable behaviour. For large files it may cause an unacceptable delay.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
Returns the current uncompressed line number. If `EXPR` is present it has the effect of setting the line number. Note that setting the line number does not change the current position within the file/buffer being read.
The contents of `$/` are used to determine what constitutes a line terminator.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Uncompress::Unzip object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Uncompress::Unzip object was created, and the object is associated with a file, the underlying file will also be closed.
### nextStream
Usage is
```
my $status = $z->nextStream();
```
Skips to the next compressed data stream in the input file/buffer. If a new compressed data stream is found, the eof marker will be cleared and `$.` will be reset to 0.
If trailing data is present immediately after the zip archive and the `Transparent` option is enabled, this method will consider that trailing data to be another member of the zip archive.
Returns 1 if a new stream was found, 0 if none was found, and -1 if an error was encountered.
### trailingData
Usage is
```
my $data = $z->trailingData();
```
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete. It only makes sense to call this method once the end of the compressed data stream has been encountered.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option in the constructor.
Importing
---------
No symbolic constants are required by IO::Uncompress::Unzip at present.
:all Imports `unzip` and `$UnzipError`. Same as doing this
```
use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
```
EXAMPLES
--------
###
Working with Net::FTP
See [IO::Compress::FAQ](IO::Compress::FAQ#Compressed-files-and-Net%3A%3AFTP)
###
Walking through a zip file
The code below can be used to traverse a zip file, one compressed data stream at a time.
```
use IO::Uncompress::Unzip qw($UnzipError);
my $zipfile = "somefile.zip";
my $u = IO::Uncompress::Unzip->new( $zipfile )
or die "Cannot open $zipfile: $UnzipError";
my $status;
for ($status = 1; $status > 0; $status = $u->nextStream())
{
my $name = $u->getHeaderInfo()->{Name};
warn "Processing member $name\n" ;
my $buff;
while (($status = $u->read($buff)) > 0) {
# Do something here
}
last if $status < 0;
}
die "Error processing $zipfile: $!\n"
if $status < 0 ;
```
Each individual compressed data stream is read until the logical end-of-file is reached. Then `nextStream` is called. This will skip to the start of the next compressed data stream and clear the end-of-file flag.
It is also worth noting that `nextStream` can be called at any time -- you don't have to wait until you have exhausted a compressed data stream before skipping to the next one.
###
Unzipping a complete zip file to disk
Daniel S. Sterling has written a script that uses `IO::Uncompress::UnZip` to read a zip file and unzip its contents to disk.
The script is available from <https://gist.github.com/eqhmcow/5389877>
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Uncompress::RawInflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
For RFC 1950, 1951 and 1952 see <https://datatracker.ietf.org/doc/html/rfc1950>, <https://datatracker.ietf.org/doc/html/rfc1951> and <https://datatracker.ietf.org/doc/html/rfc1952>
The *zlib* compression library was written by Jean-loup Gailly `[email protected]` and Mark Adler `[email protected]`.
The primary site for the *zlib* compression library is <http://www.zlib.org>.
The primary site for gzip is <http://www.gzip.org>.
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl perlhpux perlhpux
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Using perl as shipped with HP-UX](#Using-perl-as-shipped-with-HP-UX)
+ [Using perl from HP's porting centre](#Using-perl-from-HP's-porting-centre)
+ [Other prebuilt perl binaries](#Other-prebuilt-perl-binaries)
+ [Compiling Perl 5 on HP-UX](#Compiling-Perl-5-on-HP-UX)
+ [PA-RISC](#PA-RISC)
+ [PA-RISC 1.0](#PA-RISC-1.0)
+ [PA-RISC 1.1](#PA-RISC-1.1)
+ [PA-RISC 2.0](#PA-RISC-2.0)
+ [Portability Between PA-RISC Versions](#Portability-Between-PA-RISC-Versions)
+ [Itanium Processor Family (IPF) and HP-UX](#Itanium-Processor-Family-(IPF)-and-HP-UX)
+ [Itanium, Itanium 2 & Madison 6](#Itanium,-Itanium-2-&-Madison-6)
+ [HP-UX versions](#HP-UX-versions)
+ [Building Dynamic Extensions on HP-UX](#Building-Dynamic-Extensions-on-HP-UX)
+ [The HP ANSI C Compiler](#The-HP-ANSI-C-Compiler)
+ [The GNU C Compiler](#The-GNU-C-Compiler)
+ [Using Large Files with Perl on HP-UX](#Using-Large-Files-with-Perl-on-HP-UX)
+ [Threaded Perl on HP-UX](#Threaded-Perl-on-HP-UX)
+ [64-bit Perl on HP-UX](#64-bit-Perl-on-HP-UX)
+ [Oracle on HP-UX](#Oracle-on-HP-UX)
+ [GDBM and Threads on HP-UX](#GDBM-and-Threads-on-HP-UX)
+ [NFS filesystems and utime(2) on HP-UX](#NFS-filesystems-and-utime(2)-on-HP-UX)
+ [HP-UX Kernel Parameters (maxdsiz) for Compiling Perl](#HP-UX-Kernel-Parameters-(maxdsiz)-for-Compiling-Perl)
* [nss\_delete core dump from op/pwent or op/grent](#nss_delete-core-dump-from-op/pwent-or-op/grent)
* [error: pasting ")" and "l" does not give a valid preprocessing token](#error:-pasting-%22)%22-and-%22l%22-does-not-give-a-valid-preprocessing-token)
* [Redeclaration of "sendpath" with a different storage class specifier](#Redeclaration-of-%22sendpath%22-with-a-different-storage-class-specifier)
* [Miscellaneous](#Miscellaneous)
* [AUTHOR](#AUTHOR)
NAME
----
perlhpux - Perl version 5 on Hewlett-Packard Unix (HP-UX) systems
DESCRIPTION
-----------
This document describes various features of HP's Unix operating system (HP-UX) that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
Using perl as shipped with HP-UX
Application release September 2001, HP-UX 11.00 is the first to ship with Perl. By the time it was perl-5.6.1 in /opt/perl. The first occurrence is on CD 5012-7954 and can be installed using
```
swinstall -s /cdrom perl
```
assuming you have mounted that CD on /cdrom.
That build was a portable hppa-1.1 multithread build that supports large files compiled with gcc-2.9-hppa-991112.
If you perform a new installation, then (a newer) Perl will be installed automatically. Pre-installed HP-UX systems now have more recent versions of Perl and the updated modules.
The official (threaded) builds from HP, as they are shipped on the Application DVD/CD's are available on <http://www.software.hp.com/portal/swdepot/displayProductInfo.do?productNumber=PERL> for both PA-RISC and IPF (Itanium Processor Family). They are built with the HP ANSI-C compiler. Up till 5.8.8 that was done by ActiveState.
To see what version is included on the DVD (assumed here to be mounted on /cdrom), issue this command:
```
# swlist -s /cdrom perl
# perl D.5.8.8.B 5.8.8 Perl Programming Language
perl.Perl5-32 D.5.8.8.B 32-bit 5.8.8 Perl Programming Language
with Extensions
perl.Perl5-64 D.5.8.8.B 64-bit 5.8.8 Perl Programming Language
with Extensions
```
To see what is installed on your system:
```
# swlist -R perl
# perl E.5.8.8.J Perl Programming Language
# perl.Perl5-32 E.5.8.8.J 32-bit Perl Programming Language
with Extensions
perl.Perl5-32.PERL-MAN E.5.8.8.J 32-bit Perl Man Pages for IA
perl.Perl5-32.PERL-RUN E.5.8.8.J 32-bit Perl Binaries for IA
# perl.Perl5-64 E.5.8.8.J 64-bit Perl Programming Language
with Extensions
perl.Perl5-64.PERL-MAN E.5.8.8.J 64-bit Perl Man Pages for IA
perl.Perl5-64.PERL-RUN E.5.8.8.J 64-bit Perl Binaries for IA
```
###
Using perl from HP's porting centre
HP porting centre tries to keep up with customer demand and release updates from the Open Source community. Having precompiled Perl binaries available is obvious, though "up-to-date" is something relative. At the moment of writing perl-5.10.1 and 5.28.0 were available.
The HP porting centres are limited in what systems they are allowed to port to and they usually choose the two most recent OS versions available.
HP has asked the porting centre to move Open Source binaries from /opt to /usr/local, so binaries produced since the start of July 2002 are located in /usr/local.
One of HP porting centres URL's is <http://hpux.connect.org.uk/> The port currently available is built with GNU gcc. As porting modern GNU gcc is extremely hard on HP-UX, they are stuck at version gcc-4.2.3.
###
Other prebuilt perl binaries
To get more perl depots for the whole range of HP-UX, visit H.Merijn Brand's site at <http://mirrors.develooper.com/hpux/#Perl>. Carefully read the notes to see if the available versions suit your needs.
###
Compiling Perl 5 on HP-UX
When compiling Perl, you must use an ANSI C compiler. The C compiler that ships with all HP-UX systems is a K&R compiler that should only be used to build new kernels.
Perl can be compiled with either HP's ANSI C compiler or with gcc. The former is recommended, as not only can it compile Perl with no difficulty, but also can take advantage of features listed later that require the use of HP compiler-specific command-line flags.
If you decide to use gcc, make sure your installation is recent and complete, and be sure to read the Perl INSTALL file for more gcc-specific details.
###
PA-RISC
The last and final version of PA-RISC is 2.0, HP no longer sells any system with these CPU's.
HP's HP9000 Unix systems run on HP's own Precision Architecture (PA-RISC) chip. HP-UX used to run on the Motorola MC68000 family of chips, but any machine with this chip in it is quite obsolete and this document will not attempt to address issues for compiling Perl on the Motorola chipset. Even though PA-RISC hardware is not sold anymore, a lot of machines still running on these CPU's can be found in the wild.
The last order date for HP 9000 systems was December 31, 2008.
HP PA-RISC systems are usually referred to with model description "HP 9000". The last CPU in this series is the PA-8900. Support for PA-RISC architectured machines officially ended as shown in the following table:
```
PA-RISC End-of-Life Roadmap
+--------+----------------+----------------+-----------------+
| HP9000 | Superdome | PA-8700 | Spring 2011 |
| 4-128 | | PA-8800/sx1000 | Summer 2012 |
| cores | | PA-8900/sx1000 | 2014 |
| | | PA-8900/sx2000 | 2015 |
+--------+----------------+----------------+-----------------+
| HP9000 | rp7410, rp8400 | PA-8700 | Spring 2011 |
| 2-32 | rp7420, rp8420 | PA-8800/sx1000 | 2012 |
| cores | rp7440, rp8440 | PA-8900/sx1000 | Autumn 2013 |
| | | PA-8900/sx2000 | 2015 |
+--------+----------------+----------------+-----------------+
| HP9000 | rp44x0 | PA-8700 | Spring 2011 |
| 1-8 | | PA-8800/rp44x0 | 2012 |
| cores | | PA-8900/rp44x0 | 2014 |
+--------+----------------+----------------+-----------------+
| HP9000 | rp34x0 | PA-8700 | Spring 2011 |
| 1-4 | | PA-8800/rp34x0 | 2012 |
| cores | | PA-8900/rp34x0 | 2014 |
+--------+----------------+----------------+-----------------+
```
A complete list of models at the time the OS was built is in the file /usr/sam/lib/mo/sched.models. The first column corresponds to the last part of the output of the "model" command. The second column is the PA-RISC version and the third column is the exact chip type used. (Start browsing at the bottom to prevent confusion ;-)
```
# model
9000/800/L1000-44
# grep L1000-44 /usr/sam/lib/mo/sched.models
L1000-44 2.0 PA8500
```
###
PA-RISC 1.0
The original version of PA-RISC, HP no longer sells any system with this chip.
The following systems contained PA-RISC 1.0 chips:
```
600, 635, 645, 808, 815, 822, 825, 832, 834, 835, 840, 842, 845, 850,
852, 855, 860, 865, 870, 890
```
###
PA-RISC 1.1
An upgrade to the PA-RISC design, it shipped for many years in many different system.
The following systems contain with PA-RISC 1.1 chips:
```
705, 710, 712, 715, 720, 722, 725, 728, 730, 735, 742, 743, 744, 745,
747, 750, 755, 770, 777, 778, 779, 800, 801, 803, 806, 807, 809, 811,
813, 816, 817, 819, 821, 826, 827, 829, 831, 837, 839, 841, 847, 849,
851, 856, 857, 859, 867, 869, 877, 887, 891, 892, 897, A180, A180C,
B115, B120, B132L, B132L+, B160L, B180L, C100, C110, C115, C120,
C160L, D200, D210, D220, D230, D250, D260, D310, D320, D330, D350,
D360, D410, DX0, DX5, DXO, E25, E35, E45, E55, F10, F20, F30, G30,
G40, G50, G60, G70, H20, H30, H40, H50, H60, H70, I30, I40, I50, I60,
I70, J200, J210, J210XC, K100, K200, K210, K220, K230, K400, K410,
K420, S700i, S715, S744, S760, T500, T520
```
###
PA-RISC 2.0
The most recent upgrade to the PA-RISC design, it added support for 64-bit integer data.
As of the date of this document's last update, the following systems contain PA-RISC 2.0 chips:
```
700, 780, 781, 782, 783, 785, 802, 804, 810, 820, 861, 871, 879, 889,
893, 895, 896, 898, 899, A400, A500, B1000, B2000, C130, C140, C160,
C180, C180+, C180-XP, C200+, C400+, C3000, C360, C3600, CB260, D270,
D280, D370, D380, D390, D650, J220, J2240, J280, J282, J400, J410,
J5000, J5500XM, J5600, J7000, J7600, K250, K260, K260-EG, K270, K360,
K370, K380, K450, K460, K460-EG, K460-XP, K470, K570, K580, L1000,
L2000, L3000, N4000, R380, R390, SD16000, SD32000, SD64000, T540,
T600, V2000, V2200, V2250, V2500, V2600
```
Just before HP took over Compaq, some systems were renamed. the link that contained the explanation is dead, so here's a short summary:
```
HP 9000 A-Class servers, now renamed HP Server rp2400 series.
HP 9000 L-Class servers, now renamed HP Server rp5400 series.
HP 9000 N-Class servers, now renamed HP Server rp7400.
rp2400, rp2405, rp2430, rp2450, rp2470, rp3410, rp3440, rp4410,
rp4440, rp5400, rp5405, rp5430, rp5450, rp5470, rp7400, rp7405,
rp7410, rp7420, rp7440, rp8400, rp8420, rp8440, Superdome
```
The current naming convention is:
```
aadddd
||||`+- 00 - 99 relative capacity & newness (upgrades, etc.)
|||`--- unique number for each architecture to ensure different
||| systems do not have the same numbering across
||| architectures
||`---- 1 - 9 identifies family and/or relative positioning
||
|`----- c = ia32 (cisc)
| p = pa-risc
| x = ia-64 (Itanium & Itanium 2)
| h = housing
`------ t = tower
r = rack optimized
s = super scalable
b = blade
sa = appliance
```
###
Portability Between PA-RISC Versions
An executable compiled on a PA-RISC 2.0 platform will not execute on a PA-RISC 1.1 platform, even if they are running the same version of HP-UX. If you are building Perl on a PA-RISC 2.0 platform and want that Perl to also run on a PA-RISC 1.1, the compiler flags +DAportable and +DS32 should be used.
It is no longer possible to compile PA-RISC 1.0 executables on either the PA-RISC 1.1 or 2.0 platforms. The command-line flags are accepted, but the resulting executable will not run when transferred to a PA-RISC 1.0 system.
###
Itanium Processor Family (IPF) and HP-UX
HP-UX also runs on the newer Itanium processor. This requires the use of HP-UX version 11.23 (11i v2) or 11.31 (11i v3), and with the exception of a few differences detailed below and in later sections, Perl should compile with no problems.
Although PA-RISC binaries can run on Itanium systems, you should not attempt to use a PA-RISC version of Perl on an Itanium system. This is because shared libraries created on an Itanium system cannot be loaded while running a PA-RISC executable.
HP Itanium 2 systems are usually referred to with model description "HP Integrity".
###
Itanium, Itanium 2 & Madison 6
HP also ships servers with the 128-bit Itanium processor(s). The cx26x0 is told to have Madison 6. As of the date of this document's last update, the following systems contain Itanium or Itanium 2 chips (this is likely to be out of date):
```
BL60p, BL860c, BL870c, BL890c, cx2600, cx2620, rx1600, rx1620, rx2600,
rx2600hptc, rx2620, rx2660, rx2800, rx3600, rx4610, rx4640, rx5670,
rx6600, rx7420, rx7620, rx7640, rx8420, rx8620, rx8640, rx9610,
sx1000, sx2000
```
To see all about your machine, type
```
# model
ia64 hp server rx2600
# /usr/contrib/bin/machinfo
```
###
HP-UX versions
Not all architectures (PA = PA-RISC, IPF = Itanium Processor Family) support all versions of HP-UX, here is a short list
```
HP-UX version Kernel Architecture End-of-factory support
------------- ------ ------------ ----------------------------------
10.20 32 bit PA 30-Jun-2003
11.00 32/64 PA 31-Dec-2006
11.11 11i v1 32/64 PA 31-Dec-2015
11.22 11i v2 64 IPF 30-Apr-2004
11.23 11i v2 64 PA & IPF 31-Dec-2015
11.31 11i v3 64 PA & IPF 31-Dec-2020 (PA) 31-Dec-2025 (IPF)
```
See for the full list of hardware/OS support and expected end-of-life <https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>
###
Building Dynamic Extensions on HP-UX
HP-UX supports dynamically loadable libraries (shared libraries). Shared libraries end with the suffix .sl. On Itanium systems, they end with the suffix .so.
Shared libraries created on a platform using a particular PA-RISC version are not usable on platforms using an earlier PA-RISC version by default. However, this backwards compatibility may be enabled using the same +DAportable compiler flag (with the same PA-RISC 1.0 caveat mentioned above).
Shared libraries created on an Itanium platform cannot be loaded on a PA-RISC platform. Shared libraries created on a PA-RISC platform can only be loaded on an Itanium platform if it is a PA-RISC executable that is attempting to load the PA-RISC library. A PA-RISC shared library cannot be loaded into an Itanium executable nor vice-versa.
To create a shared library, the following steps must be performed:
```
1. Compile source modules with +z or +Z flag to create a .o module
which contains Position-Independent Code (PIC). The linker will
tell you in the next step if +Z was needed.
(For gcc, the appropriate flag is -fpic or -fPIC.)
2. Link the shared library using the -b flag. If the code calls
any functions in other system libraries (e.g., libm), it must
be included on this line.
```
(Note that these steps are usually handled automatically by the extension's Makefile).
If these dependent libraries are not listed at shared library creation time, you will get fatal "Unresolved symbol" errors at run time when the library is loaded.
You may create a shared library that refers to another library, which may be either an archive library or a shared library. If this second library is a shared library, this is called a "dependent library". The dependent library's name is recorded in the main shared library, but it is not linked into the shared library. Instead, it is loaded when the main shared library is loaded. This can cause problems if you build an extension on one system and move it to another system where the libraries may not be located in the same place as on the first system.
If the referred library is an archive library, then it is treated as a simple collection of .o modules (all of which must contain PIC). These modules are then linked into the shared library.
Note that it is okay to create a library which contains a dependent library that is already linked into perl.
Some extensions, like DB\_File and Compress::Zlib use/require prebuilt libraries for the perl extensions/modules to work. If these libraries are built using the default configuration, it might happen that you run into an error like "invalid loader fixup" during load phase. HP is aware of this problem. Search the HP-UX cxx-dev forums for discussions about the subject. The short answer is that **everything** (all libraries, everything) must be compiled with `+z` or `+Z` to be PIC (position independent code). (For gcc, that would be `-fpic` or `-fPIC`). In HP-UX 11.00 or newer the linker error message should tell the name of the offending object file.
A more general approach is to intervene manually, as with an example for the DB\_File module, which requires SleepyCat's libdb.sl:
```
# cd .../db-3.2.9/build_unix
# vi Makefile
... add +Z to all cflags to create shared objects
CFLAGS= -c $(CPPFLAGS) +Z -Ae +O2 +Onolimit \
-I/usr/local/include -I/usr/include/X11R6
CXXFLAGS= -c $(CPPFLAGS) +Z -Ae +O2 +Onolimit \
-I/usr/local/include -I/usr/include/X11R6
# make clean
# make
# mkdir tmp
# cd tmp
# ar x ../libdb.a
# ld -b -o libdb-3.2.sl *.o
# mv libdb-3.2.sl /usr/local/lib
# rm *.o
# cd /usr/local/lib
# rm -f libdb.sl
# ln -s libdb-3.2.sl libdb.sl
# cd .../DB_File-1.76
# make distclean
# perl Makefile.PL
# make
# make test
# make install
```
As of db-4.2.x it is no longer needed to do this by hand. Sleepycat has changed the configuration process to add +z on HP-UX automatically.
```
# cd .../db-4.2.25/build_unix
# env CFLAGS=+DD64 LDFLAGS=+DD64 ../dist/configure
```
should work to generate 64bit shared libraries for HP-UX 11.00 and 11i.
It is no longer possible to link PA-RISC 1.0 shared libraries (even though the command-line flags are still present).
PA-RISC and Itanium object files are not interchangeable. Although you may be able to use ar to create an archive library of PA-RISC object files on an Itanium system, you cannot link against it using an Itanium link editor.
###
The HP ANSI C Compiler
When using this compiler to build Perl, you should make sure that the flag -Aa is added to the cpprun and cppstdin variables in the config.sh file (though see the section on 64-bit perl below). If you are using a recent version of the Perl distribution, these flags are set automatically.
Even though HP-UX 10.20 and 11.00 are not actively maintained by HP anymore, updates for the HP ANSI C compiler are still available from time to time, and it might be advisable to see if updates are applicable. At the moment of writing, the latests available patches for 11.00 that should be applied are PHSS\_35098, PHSS\_35175, PHSS\_35100, PHSS\_33036, and PHSS\_33902). If you have a SUM account, you can use it to search for updates/patches. Enter "ANSI" as keyword.
###
The GNU C Compiler
When you are going to use the GNU C compiler (gcc), and you don't have gcc yet, you can either build it yourself (if you feel masochistic enough) from the sources (available from e.g. <http://gcc.gnu.org/mirrors.html>) or fetch a prebuilt binary from the HP porting center at <http://hpux.connect.org.uk/hppd/cgi-bin/search?term=gcc&Search=Search> or from the DSPP (you need to be a member) at <http://h21007.www2.hp.com/portal/site/dspp/menuitem.863c3e4cbcdc3f3515b49c108973a801?ciid=2a08725cc2f02110725cc2f02110275d6e10RCRD&jumpid=reg_r1002_usen_c-001_title_r0001> (Browse through the list, because there are often multiple versions of the same package available).
Most mentioned distributions are depots. H.Merijn Brand has made prebuilt gcc binaries available on <http://mirrors.develooper.com/hpux/> and/or <http://www.cmve.net/~merijn/> for HP-UX 10.20 (only 32bit), HP-UX 11.00, HP-UX 11.11 (HP-UX 11i v1), and HP-UX 11.23 (HP-UX 11i v2 PA-RISC) in both 32- and 64-bit versions. For HP-UX 11.23 IPF and HP-UX 11.31 IPF depots are available too. The IPF versions do not need two versions of GNU gcc.
On PA-RISC you need a different compiler for 32-bit applications and for 64-bit applications. On PA-RISC, 32-bit objects and 64-bit objects do not mix. Period. There is no different behaviour for HP C-ANSI-C or GNU gcc. So if you require your perl binary to use 64-bit libraries, like Oracle-64bit, you MUST build a 64-bit perl.
Building a 64-bit capable gcc on PA-RISC from source is possible only when you have the HP C-ANSI C compiler or an already working 64-bit binary of gcc available. Best performance for perl is achieved with HP's native compiler.
###
Using Large Files with Perl on HP-UX
Beginning with HP-UX version 10.20, files larger than 2GB (2^31 bytes) may be created and manipulated. Three separate methods of doing this are available. Of these methods, the best method for Perl is to compile using the -Duselargefiles flag to Configure. This causes Perl to be compiled using structures and functions in which these are 64 bits wide, rather than 32 bits wide. (Note that this will only work with HP's ANSI C compiler. If you want to compile Perl using gcc, you will have to get a version of the compiler that supports 64-bit operations. See above for where to find it.)
There are some drawbacks to this approach. One is that any extension which calls any file-manipulating C function will need to be recompiled (just follow the usual "perl Makefile.PL; make; make test; make install" procedure).
The list of functions that will need to recompiled is: creat, fgetpos, fopen, freopen, fsetpos, fstat, fstatvfs, fstatvfsdev, ftruncate, ftw, lockf, lseek, lstat, mmap, nftw, open, prealloc, stat, statvfs, statvfsdev, tmpfile, truncate, getrlimit, setrlimit
Another drawback is only valid for Perl versions before 5.6.0. This drawback is that the seek and tell functions (both the builtin version and POSIX module version) will not perform correctly.
It is strongly recommended that you use this flag when you run Configure. If you do not do this, but later answer the question about large files when Configure asks you, you may get a configuration that cannot be compiled, or that does not function as expected.
###
Threaded Perl on HP-UX
It is possible to compile a version of threaded Perl on any version of HP-UX before 10.30, but it is strongly suggested that you be running on HP-UX 11.00 at least.
To compile Perl with threads, add -Dusethreads to the arguments of Configure. Verify that the -D\_POSIX\_C\_SOURCE=199506L compiler flag is automatically added to the list of flags. Also make sure that -lpthread is listed before -lc in the list of libraries to link Perl with. The hints provided for HP-UX during Configure will try very hard to get this right for you.
HP-UX versions before 10.30 require a separate installation of a POSIX threads library package. Two examples are the HP DCE package, available on "HP-UX Hardware Extensions 3.0, Install and Core OS, Release 10.20, April 1999 (B3920-13941)" or the Freely available PTH package, available on H.Merijn's site (<http://mirrors.develooper.com/hpux/>). The use of PTH will be unsupported in perl-5.12 and up and is rather buggy in 5.11.x.
If you are going to use the HP DCE package, the library used for threading is /usr/lib/libcma.sl, but there have been multiple updates of that library over time. Perl will build with the first version, but it will not pass the test suite. Older Oracle versions might be a compelling reason not to update that library, otherwise please find a newer version in one of the following patches: PHSS\_19739, PHSS\_20608, or PHSS\_23672
reformatted output:
```
d3:/usr/lib 106 > what libcma-*.1
libcma-00000.1:
HP DCE/9000 1.5 Module: libcma.sl (Export)
Date: Apr 29 1996 22:11:24
libcma-19739.1:
HP DCE/9000 1.5 PHSS_19739-40 Module: libcma.sl (Export)
Date: Sep 4 1999 01:59:07
libcma-20608.1:
HP DCE/9000 1.5 PHSS_20608 Module: libcma.1 (Export)
Date: Dec 8 1999 18:41:23
libcma-23672.1:
HP DCE/9000 1.5 PHSS_23672 Module: libcma.1 (Export)
Date: Apr 9 2001 10:01:06
d3:/usr/lib 107 >
```
If you choose for the PTH package, use swinstall to install pth in the default location (/opt/pth), and then make symbolic links to the libraries from /usr/lib
```
# cd /usr/lib
# ln -s /opt/pth/lib/libpth* .
```
For building perl to support Oracle, it needs to be linked with libcl and libpthread. So even if your perl is an unthreaded build, these libraries might be required. See "Oracle on HP-UX" below.
###
64-bit Perl on HP-UX
Beginning with HP-UX 11.00, programs compiled under HP-UX can take advantage of the LP64 programming environment (LP64 means Longs and Pointers are 64 bits wide), in which scalar variables will be able to hold numbers larger than 2^32 with complete precision. Perl has proven to be consistent and reliable in 64bit mode since 5.8.1 on all HP-UX 11.xx.
As of the date of this document, Perl is fully 64-bit compliant on HP-UX 11.00 and up for both cc- and gcc builds. If you are about to build a 64-bit perl with GNU gcc, please read the gcc section carefully.
Should a user have the need for compiling Perl in the LP64 environment, use the -Duse64bitall flag to Configure. This will force Perl to be compiled in a pure LP64 environment (with the +DD64 flag for HP C-ANSI-C, with no additional options for GNU gcc 64-bit on PA-RISC, and with -mlp64 for GNU gcc on Itanium). If you want to compile Perl using gcc, you will have to get a version of the compiler that supports 64-bit operations.)
You can also use the -Duse64bitint flag to Configure. Although there are some minor differences between compiling Perl with this flag versus the -Duse64bitall flag, they should not be noticeable from a Perl user's perspective. When configuring -Duse64bitint using a 64bit gcc on a pa-risc architecture, -Duse64bitint is silently promoted to -Duse64bitall.
In both cases, it is strongly recommended that you use these flags when you run Configure. If you do not use do this, but later answer the questions about 64-bit numbers when Configure asks you, you may get a configuration that cannot be compiled, or that does not function as expected.
###
Oracle on HP-UX
Using perl to connect to Oracle databases through DBI and DBD::Oracle has caused a lot of people many headaches. Read README.hpux in the DBD::Oracle for much more information. The reason to mention it here is that Oracle requires a perl built with libcl and libpthread, the latter even when perl is build without threads. Building perl using all defaults, but still enabling to build DBD::Oracle later on can be achieved using
```
Configure -A prepend:libswanted='cl pthread ' ...
```
Do not forget the space before the trailing quote.
Also note that this does not (yet) work with all configurations, it is known to fail with 64-bit versions of GCC.
###
GDBM and Threads on HP-UX
If you attempt to compile Perl with (POSIX) threads on an 11.X system and also link in the GDBM library, then Perl will immediately core dump when it starts up. The only workaround at this point is to relink the GDBM library under 11.X, then relink it into Perl.
the error might show something like:
Pthread internal error: message: \_\_libc\_reinit() failed, file: ../pthreads/pthread.c, line: 1096 Return Pointer is 0xc082bf33 sh: 5345 Quit(coredump)
and Configure will give up.
###
NFS filesystems and utime(2) on HP-UX
If you are compiling Perl on a remotely-mounted NFS filesystem, the test io/fs.t may fail on test #18. This appears to be a bug in HP-UX and no fix is currently available.
###
HP-UX Kernel Parameters (maxdsiz) for Compiling Perl
By default, HP-UX comes configured with a maximum data segment size of 64MB. This is too small to correctly compile Perl with the maximum optimization levels. You can increase the size of the maxdsiz kernel parameter through the use of SAM.
When using the GUI version of SAM, click on the Kernel Configuration icon, then the Configurable Parameters icon. Scroll down and select the maxdsiz line. From the Actions menu, select the Modify Configurable Parameter item. Insert the new formula into the Formula/Value box. Then follow the instructions to rebuild your kernel and reboot your system.
In general, a value of 256MB (or "256\*1024\*1024") is sufficient for Perl to compile at maximum optimization.
nss\_delete core dump from op/pwent or op/grent
------------------------------------------------
You may get a bus error core dump from the op/pwent or op/grent tests. If compiled with -g you will see a stack trace much like the following:
```
#0 0xc004216c in () from /usr/lib/libc.2
#1 0xc00d7550 in __nss_src_state_destr () from /usr/lib/libc.2
#2 0xc00d7768 in __nss_src_state_destr () from /usr/lib/libc.2
#3 0xc00d78a8 in nss_delete () from /usr/lib/libc.2
#4 0xc01126d8 in endpwent () from /usr/lib/libc.2
#5 0xd1950 in Perl_pp_epwent () from ./perl
#6 0x94d3c in Perl_runops_standard () from ./perl
#7 0x23728 in S_run_body () from ./perl
#8 0x23428 in perl_run () from ./perl
#9 0x2005c in main () from ./perl
```
The key here is the `nss_delete` call. One workaround for this bug seems to be to create add to the file */etc/nsswitch.conf* (at least) the following lines
```
group: files
passwd: files
```
Whether you are using NIS does not matter. Amazingly enough, the same bug also affects Solaris.
error: pasting ")" and "l" does not give a valid preprocessing token
---------------------------------------------------------------------
There seems to be a broken system header file in HP-UX 11.00 that breaks perl building in 32bit mode with GNU gcc-4.x causing this error. The same file for HP-UX 11.11 (even though the file is older) does not show this failure, and has the correct definition, so the best fix is to patch the header to match:
```
--- /usr/include/inttypes.h 2001-04-20 18:42:14 +0200
+++ /usr/include/inttypes.h 2000-11-14 09:00:00 +0200
@@ -72,7 +72,7 @@
#define UINT32_C(__c) __CONCAT_U__(__c)
#else /* __LP64 */
#define INT32_C(__c) __CONCAT__(__c,l)
-#define UINT32_C(__c) __CONCAT__(__CONCAT_U__(__c),l)
+#define UINT32_C(__c) __CONCAT__(__c,ul)
#endif /* __LP64 */
#define INT64_C(__c) __CONCAT_L__(__c,l)
```
Redeclaration of "sendpath" with a different storage class specifier
---------------------------------------------------------------------
The following compilation warnings may happen in HP-UX releases earlier than 11.31 but are harmless:
```
cc: "/usr/include/sys/socket.h", line 535: warning 562:
Redeclaration of "sendfile" with a different storage class
specifier: "sendfile" will have internal linkage.
cc: "/usr/include/sys/socket.h", line 536: warning 562:
Redeclaration of "sendpath" with a different storage class
specifier: "sendpath" will have internal linkage.
```
They seem to be caused by broken system header files, and also other open source projects are seeing them. The following HP-UX patches should make the warnings go away:
```
CR JAGae12001: PHNE_27063
Warning 562 on sys/socket.h due to redeclaration of prototypes
CR JAGae16787:
Warning 562 from socket.h sendpath/sendfile -D_FILEFFSET_BITS=64
CR JAGae73470 (11.23)
ER: Compiling socket.h with cc -D_FILEFFSET_BITS=64 warning 267/562
```
Miscellaneous
-------------
HP-UX 11 Y2K patch "Y2K-1100 B.11.00.B0125 HP-UX Core OS Year 2000 Patch Bundle" has been reported to break the io/fs test #18 which tests whether utime() can change timestamps. The Y2K patch seems to break utime() so that over NFS the timestamps do not get changed (on local filesystems utime() still works). This has probably been fixed on your system by now.
AUTHOR
------
H.Merijn Brand <[email protected]> Jeff Okamoto <[email protected]>
With much assistance regarding shared libraries from Marc Sabatella.
| programming_docs |
perl TAP::Parser::Source TAP::Parser::Source
===================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [raw](#raw)
- [meta](#meta)
- [has\_meta](#has_meta)
- [config](#config)
- [merge](#merge)
- [switches](#switches)
- [test\_args](#test_args)
- [assemble\_meta](#assemble_meta)
- [shebang](#shebang)
- [config\_for](#config_for)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::Source - a TAP source & meta data about it
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Source;
my $source = TAP::Parser::Source->new;
$source->raw( \'reference to raw TAP source' )
->config( \%config )
->merge( $boolean )
->switches( \@switches )
->test_args( \@args )
->assemble_meta;
do { ... } if $source->meta->{is_file};
# see assemble_meta for a full list of data available
```
DESCRIPTION
-----------
A TAP *source* is something that produces a stream of TAP for the parser to consume, such as an executable file, a text file, an archive, an IO handle, a database, etc. `TAP::Parser::Source`s encapsulate these *raw* sources, and provide some useful meta data about them. They are used by <TAP::Parser::SourceHandler>s, which do whatever is required to produce & capture a stream of TAP from the *raw* source, and package it up in a <TAP::Parser::Iterator> for the parser to consume.
Unless you're writing a new <TAP::Parser::SourceHandler>, a plugin or subclassing <TAP::Parser>, you probably won't need to use this module directly.
METHODS
-------
###
Class Methods
#### `new`
```
my $source = TAP::Parser::Source->new;
```
Returns a new `TAP::Parser::Source` object.
###
Instance Methods
#### `raw`
```
my $raw = $source->raw;
$source->raw( $some_value );
```
Chaining getter/setter for the raw TAP source. This is a reference, as it may contain large amounts of data (eg: raw TAP).
#### `meta`
```
my $meta = $source->meta;
$source->meta({ %some_value });
```
Chaining getter/setter for meta data about the source. This defaults to an empty hashref. See ["assemble\_meta"](#assemble_meta) for more info.
#### `has_meta`
True if the source has meta data.
#### `config`
```
my $config = $source->config;
$source->config({ %some_value });
```
Chaining getter/setter for the source's configuration, if any has been provided by the user. How it's used is up to you. This defaults to an empty hashref. See ["config\_for"](#config_for) for more info.
#### `merge`
```
my $merge = $source->merge;
$source->config( $bool );
```
Chaining getter/setter for the flag that dictates whether STDOUT and STDERR should be merged (where appropriate). Defaults to undef.
#### `switches`
```
my $switches = $source->switches;
$source->config([ @switches ]);
```
Chaining getter/setter for the list of command-line switches that should be passed to the source (where appropriate). Defaults to undef.
#### `test_args`
```
my $test_args = $source->test_args;
$source->config([ @test_args ]);
```
Chaining getter/setter for the list of command-line arguments that should be passed to the source (where appropriate). Defaults to undef.
#### `assemble_meta`
```
my $meta = $source->assemble_meta;
```
Gathers meta data about the ["raw"](#raw) source, stashes it in ["meta"](#meta) and returns it as a hashref. This is done so that the <TAP::Parser::SourceHandler>s don't have to repeat common checks. Currently this includes:
```
is_scalar => $bool,
is_hash => $bool,
is_array => $bool,
# for scalars:
length => $n
has_newlines => $bool
# only done if the scalar looks like a filename
is_file => $bool,
is_dir => $bool,
is_symlink => $bool,
file => {
# only done if the scalar looks like a filename
basename => $string, # including ext
dir => $string,
ext => $string,
lc_ext => $string,
# system checks
exists => $bool,
stat => [ ... ], # perldoc -f stat
empty => $bool,
size => $n,
text => $bool,
binary => $bool,
read => $bool,
write => $bool,
execute => $bool,
setuid => $bool,
setgid => $bool,
sticky => $bool,
is_file => $bool,
is_dir => $bool,
is_symlink => $bool,
# only done if the file's a symlink
lstat => [ ... ], # perldoc -f lstat
# only done if the file's a readable text file
shebang => $first_line,
}
# for arrays:
size => $n,
```
#### `shebang`
Get the shebang line for a script file.
```
my $shebang = TAP::Parser::Source->shebang( $some_script );
```
May be called as a class method
#### `config_for`
```
my $config = $source->config_for( $class );
```
Returns ["config"](#config) for the $class given. Class names may be fully qualified or abbreviated, eg:
```
# these are equivalent
$source->config_for( 'Perl' );
$source->config_for( 'TAP::Parser::SourceHandler::Perl' );
```
If a fully qualified $class is given, its abbreviated version is checked first.
AUTHORS
-------
Steve Purkis.
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler>
perl perluniintro perluniintro
============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Unicode](#Unicode)
+ [Perl's Unicode Support](#Perl's-Unicode-Support)
+ [Perl's Unicode Model](#Perl's-Unicode-Model)
+ [Unicode and EBCDIC](#Unicode-and-EBCDIC)
+ [Creating Unicode](#Creating-Unicode)
- [Earlier releases caveats](#Earlier-releases-caveats)
+ [Handling Unicode](#Handling-Unicode)
+ [Legacy Encodings](#Legacy-Encodings)
+ [Unicode I/O](#Unicode-I/O)
+ [Displaying Unicode As Text](#Displaying-Unicode-As-Text)
+ [Special Cases](#Special-Cases)
+ [Advanced Topics](#Advanced-Topics)
+ [Miscellaneous](#Miscellaneous)
+ [Questions With Answers](#Questions-With-Answers)
+ [Hexadecimal Notation](#Hexadecimal-Notation)
+ [Further Resources](#Further-Resources)
* [UNICODE IN OLDER PERLS](#UNICODE-IN-OLDER-PERLS)
* [SEE ALSO](#SEE-ALSO)
* [ACKNOWLEDGMENTS](#ACKNOWLEDGMENTS)
* [AUTHOR, COPYRIGHT, AND LICENSE](#AUTHOR,-COPYRIGHT,-AND-LICENSE)
NAME
----
perluniintro - Perl Unicode introduction
DESCRIPTION
-----------
This document gives a general idea of Unicode and how to use Unicode in Perl. See ["Further Resources"](#Further-Resources) for references to more in-depth treatments of Unicode.
### Unicode
Unicode is a character set standard which plans to codify all of the writing systems of the world, plus many other symbols.
Unicode and ISO/IEC 10646 are coordinated standards that unify almost all other modern character set standards, covering more than 80 writing systems and hundreds of languages, including all commercially-important modern languages. All characters in the largest Chinese, Japanese, and Korean dictionaries are also encoded. The standards will eventually cover almost all characters in more than 250 writing systems and thousands of languages. Unicode 1.0 was released in October 1991, and 6.0 in October 2010.
A Unicode *character* is an abstract entity. It is not bound to any particular integer width, especially not to the C language `char`. Unicode is language-neutral and display-neutral: it does not encode the language of the text, and it does not generally define fonts or other graphical layout details. Unicode operates on characters and on text built from those characters.
Unicode defines characters like `LATIN CAPITAL LETTER A` or `GREEK SMALL LETTER ALPHA` and unique numbers for the characters, in this case 0x0041 and 0x03B1, respectively. These unique numbers are called *code points*. A code point is essentially the position of the character within the set of all possible Unicode characters, and thus in Perl, the term *ordinal* is often used interchangeably with it.
The Unicode standard prefers using hexadecimal notation for the code points. If numbers like `0x0041` are unfamiliar to you, take a peek at a later section, ["Hexadecimal Notation"](#Hexadecimal-Notation). The Unicode standard uses the notation `U+0041 LATIN CAPITAL LETTER A`, to give the hexadecimal code point and the normative name of the character.
Unicode also defines various *properties* for the characters, like "uppercase" or "lowercase", "decimal digit", or "punctuation"; these properties are independent of the names of the characters. Furthermore, various operations on the characters like uppercasing, lowercasing, and collating (sorting) are defined.
A Unicode *logical* "character" can actually consist of more than one internal *actual* "character" or code point. For Western languages, this is adequately modelled by a *base character* (like `LATIN CAPITAL LETTER A`) followed by one or more *modifiers* (like `COMBINING ACUTE ACCENT`). This sequence of base character and modifiers is called a *combining character sequence*. Some non-western languages require more complicated models, so Unicode created the *grapheme cluster* concept, which was later further refined into the *extended grapheme cluster*. For example, a Korean Hangul syllable is considered a single logical character, but most often consists of three actual Unicode characters: a leading consonant followed by an interior vowel followed by a trailing consonant.
Whether to call these extended grapheme clusters "characters" depends on your point of view. If you are a programmer, you probably would tend towards seeing each element in the sequences as one unit, or "character". However from the user's point of view, the whole sequence could be seen as one "character" since that's probably what it looks like in the context of the user's language. In this document, we take the programmer's point of view: one "character" is one Unicode code point.
For some combinations of base character and modifiers, there are *precomposed* characters. There is a single character equivalent, for example, for the sequence `LATIN CAPITAL LETTER A` followed by `COMBINING ACUTE ACCENT`. It is called `LATIN CAPITAL LETTER A WITH ACUTE`. These precomposed characters are, however, only available for some combinations, and are mainly meant to support round-trip conversions between Unicode and legacy standards (like ISO 8859). Using sequences, as Unicode does, allows for needing fewer basic building blocks (code points) to express many more potential grapheme clusters. To support conversion between equivalent forms, various *normalization forms* are also defined. Thus, `LATIN CAPITAL LETTER A WITH ACUTE` is in *Normalization Form Composed*, (abbreviated NFC), and the sequence `LATIN CAPITAL LETTER A` followed by `COMBINING ACUTE ACCENT` represents the same character in *Normalization Form Decomposed* (NFD).
Because of backward compatibility with legacy encodings, the "a unique number for every character" idea breaks down a bit: instead, there is "at least one number for every character". The same character could be represented differently in several legacy encodings. The converse is not true: some code points do not have an assigned character. Firstly, there are unallocated code points within otherwise used blocks. Secondly, there are special Unicode control characters that do not represent true characters.
When Unicode was first conceived, it was thought that all the world's characters could be represented using a 16-bit word; that is a maximum of `0x10000` (or 65,536) characters would be needed, from `0x0000` to `0xFFFF`. This soon proved to be wrong, and since Unicode 2.0 (July 1996), Unicode has been defined all the way up to 21 bits (`0x10FFFF`), and Unicode 3.1 (March 2001) defined the first characters above `0xFFFF`. The first `0x10000` characters are called the *Plane 0*, or the *Basic Multilingual Plane* (BMP). With Unicode 3.1, 17 (yes, seventeen) planes in all were defined--but they are nowhere near full of defined characters, yet.
When a new language is being encoded, Unicode generally will choose a `block` of consecutive unallocated code points for its characters. So far, the number of code points in these blocks has always been evenly divisible by 16. Extras in a block, not currently needed, are left unallocated, for future growth. But there have been occasions when a later release needed more code points than the available extras, and a new block had to allocated somewhere else, not contiguous to the initial one, to handle the overflow. Thus, it became apparent early on that "block" wasn't an adequate organizing principle, and so the `Script` property was created. (Later an improved script property was added as well, the `Script_Extensions` property.) Those code points that are in overflow blocks can still have the same script as the original ones. The script concept fits more closely with natural language: there is `Latin` script, `Greek` script, and so on; and there are several artificial scripts, like `Common` for characters that are used in multiple scripts, such as mathematical symbols. Scripts usually span varied parts of several blocks. For more information about scripts, see ["Scripts" in perlunicode](perlunicode#Scripts). The division into blocks exists, but it is almost completely accidental--an artifact of how the characters have been and still are allocated. (Note that this paragraph has oversimplified things for the sake of this being an introduction. Unicode doesn't really encode languages, but the writing systems for them--their scripts; and one script can be used by many languages. Unicode also encodes things that aren't really about languages, such as symbols like `BAGGAGE CLAIM`.)
The Unicode code points are just abstract numbers. To input and output these abstract numbers, the numbers must be *encoded* or *serialised* somehow. Unicode defines several *character encoding forms*, of which *UTF-8* is the most popular. UTF-8 is a variable length encoding that encodes Unicode characters as 1 to 4 bytes. Other encodings include UTF-16 and UTF-32 and their big- and little-endian variants (UTF-8 is byte-order independent). The ISO/IEC 10646 defines the UCS-2 and UCS-4 encoding forms.
For more information about encodings--for instance, to learn what *surrogates* and *byte order marks* (BOMs) are--see <perlunicode>.
###
Perl's Unicode Support
Starting from Perl v5.6.0, Perl has had the capacity to handle Unicode natively. Perl v5.8.0, however, is the first recommended release for serious Unicode work. The maintenance release 5.6.1 fixed many of the problems of the initial Unicode implementation, but for example regular expressions still do not work with Unicode in 5.6.1. Perl v5.14.0 is the first release where Unicode support is (almost) seamlessly integratable without some gotchas. (There are a few exceptions. Firstly, some differences in [quotemeta](perlfunc#quotemeta) were fixed starting in Perl 5.16.0. Secondly, some differences in [the range operator](perlop#Range-Operators) were fixed starting in Perl 5.26.0. Thirdly, some differences in [split](perlfunc#split) were fixed started in Perl 5.28.0.)
To enable this seamless support, you should `use feature 'unicode_strings'` (which is automatically selected if you `use v5.12` or higher). See <feature>. (5.14 also fixes a number of bugs and departures from the Unicode standard.)
Before Perl v5.8.0, the use of `use utf8` was used to declare that operations in the current block or file would be Unicode-aware. This model was found to be wrong, or at least clumsy: the "Unicodeness" is now carried with the data, instead of being attached to the operations. Starting with Perl v5.8.0, only one case remains where an explicit `use utf8` is needed: if your Perl script itself is encoded in UTF-8, you can use UTF-8 in your identifier names, and in string and regular expression literals, by saying `use utf8`. This is not the default because scripts with legacy 8-bit data in them would break. See <utf8>.
###
Perl's Unicode Model
Perl supports both pre-5.6 strings of eight-bit native bytes, and strings of Unicode characters. The general principle is that Perl tries to keep its data as eight-bit bytes for as long as possible, but as soon as Unicodeness cannot be avoided, the data is transparently upgraded to Unicode. Prior to Perl v5.14.0, the upgrade was not completely transparent (see ["The "Unicode Bug"" in perlunicode](perlunicode#The-%22Unicode-Bug%22)), and for backwards compatibility, full transparency is not gained unless `use feature 'unicode_strings'` (see <feature>) or `use v5.12` (or higher) is selected.
Internally, Perl currently uses either whatever the native eight-bit character set of the platform (for example Latin-1) is, defaulting to UTF-8, to encode Unicode strings. Specifically, if all code points in the string are `0xFF` or less, Perl uses the native eight-bit character set. Otherwise, it uses UTF-8.
A user of Perl does not normally need to know nor care how Perl happens to encode its internal strings, but it becomes relevant when outputting Unicode strings to a stream without a PerlIO layer (one with the "default" encoding). In such a case, the raw bytes used internally (the native character set or UTF-8, as appropriate for each string) will be used, and a "Wide character" warning will be issued if those strings contain a character beyond 0x00FF.
For example,
```
perl -e 'print "\x{DF}\n", "\x{0100}\x{DF}\n"'
```
produces a fairly useless mixture of native bytes and UTF-8, as well as a warning:
```
Wide character in print at ...
```
To output UTF-8, use the `:encoding` or `:utf8` output layer. Prepending
```
binmode(STDOUT, ":utf8");
```
to this sample program ensures that the output is completely UTF-8, and removes the program's warning.
You can enable automatic UTF-8-ification of your standard file handles, default `open()` layer, and `@ARGV` by using either the `-C` command line switch or the `PERL_UNICODE` environment variable, see [perlrun](perlrun#-C-%5Bnumber%2Flist%5D) for the documentation of the `-C` switch.
Note that this means that Perl expects other software to work the same way: if Perl has been led to believe that STDIN should be UTF-8, but then STDIN coming in from another command is not UTF-8, Perl will likely complain about the malformed UTF-8.
All features that combine Unicode and I/O also require using the new PerlIO feature. Almost all Perl 5.8 platforms do use PerlIO, though: you can see whether yours is by running "perl -V" and looking for `useperlio=define`.
###
Unicode and EBCDIC
Perl 5.8.0 added support for Unicode on EBCDIC platforms. This support was allowed to lapse in later releases, but was revived in 5.22. Unicode support is somewhat more complex to implement since additional conversions are needed. See <perlebcdic> for more information.
On EBCDIC platforms, the internal Unicode encoding form is UTF-EBCDIC instead of UTF-8. The difference is that as UTF-8 is "ASCII-safe" in that ASCII characters encode to UTF-8 as-is, while UTF-EBCDIC is "EBCDIC-safe", in that all the basic characters (which includes all those that have ASCII equivalents (like `"A"`, `"0"`, `"%"`, *etc.*) are the same in both EBCDIC and UTF-EBCDIC. Often, documentation will use the term "UTF-8" to mean UTF-EBCDIC as well. This is the case in this document.
###
Creating Unicode
This section applies fully to Perls starting with v5.22. Various caveats for earlier releases are in the ["Earlier releases caveats"](#Earlier-releases-caveats) subsection below.
To create Unicode characters in literals, use the `\N{...}` notation in double-quoted strings:
```
my $smiley_from_name = "\N{WHITE SMILING FACE}";
my $smiley_from_code_point = "\N{U+263a}";
```
Similarly, they can be used in regular expression literals
```
$smiley =~ /\N{WHITE SMILING FACE}/;
$smiley =~ /\N{U+263a}/;
```
or, starting in v5.32:
```
$smiley =~ /\p{Name=WHITE SMILING FACE}/;
$smiley =~ /\p{Name=whitesmilingface}/;
```
At run-time you can use:
```
use charnames ();
my $hebrew_alef_from_name
= charnames::string_vianame("HEBREW LETTER ALEF");
my $hebrew_alef_from_code_point = charnames::string_vianame("U+05D0");
```
Naturally, `ord()` will do the reverse: it turns a character into a code point.
There are other runtime options as well. You can use `pack()`:
```
my $hebrew_alef_from_code_point = pack("U", 0x05d0);
```
Or you can use `chr()`, though it is less convenient in the general case:
```
$hebrew_alef_from_code_point = chr(utf8::unicode_to_native(0x05d0));
utf8::upgrade($hebrew_alef_from_code_point);
```
The `utf8::unicode_to_native()` and `utf8::upgrade()` aren't needed if the argument is above 0xFF, so the above could have been written as
```
$hebrew_alef_from_code_point = chr(0x05d0);
```
since 0x5d0 is above 255.
`\x{}` and `\o{}` can also be used to specify code points at compile time in double-quotish strings, but, for backward compatibility with older Perls, the same rules apply as with `chr()` for code points less than 256.
`utf8::unicode_to_native()` is used so that the Perl code is portable to EBCDIC platforms. You can omit it if you're *really* sure no one will ever want to use your code on a non-ASCII platform. Starting in Perl v5.22, calls to it on ASCII platforms are optimized out, so there's no performance penalty at all in adding it. Or you can simply use the other constructs that don't require it.
See ["Further Resources"](#Further-Resources) for how to find all these names and numeric codes.
####
Earlier releases caveats
On EBCDIC platforms, prior to v5.22, using `\N{U+...}` doesn't work properly.
Prior to v5.16, using `\N{...}` with a character name (as opposed to a `U+...` code point) required a `use charnames :full`.
Prior to v5.14, there were some bugs in `\N{...}` with a character name (as opposed to a `U+...` code point).
`charnames::string_vianame()` was introduced in v5.14. Prior to that, `charnames::vianame()` should work, but only if the argument is of the form `"U+..."`. Your best bet there for runtime Unicode by character name is probably:
```
use charnames ();
my $hebrew_alef_from_name
= pack("U", charnames::vianame("HEBREW LETTER ALEF"));
```
###
Handling Unicode
Handling Unicode is for the most part transparent: just use the strings as usual. Functions like `index()`, `length()`, and `substr()` will work on the Unicode characters; regular expressions will work on the Unicode characters (see <perlunicode> and <perlretut>).
Note that Perl considers grapheme clusters to be separate characters, so for example
```
print length("\N{LATIN CAPITAL LETTER A}\N{COMBINING ACUTE ACCENT}"),
"\n";
```
will print 2, not 1. The only exception is that regular expressions have `\X` for matching an extended grapheme cluster. (Thus `\X` in a regular expression would match the entire sequence of both the example characters.)
Life is not quite so transparent, however, when working with legacy encodings, I/O, and certain special cases:
###
Legacy Encodings
When you combine legacy data and Unicode, the legacy data needs to be upgraded to Unicode. Normally the legacy data is assumed to be ISO 8859-1 (or EBCDIC, if applicable).
The `Encode` module knows about many encodings and has interfaces for doing conversions between those encodings:
```
use Encode 'decode';
$data = decode("iso-8859-3", $data); # convert from legacy
```
###
Unicode I/O
Normally, writing out Unicode data
```
print FH $some_string_with_unicode, "\n";
```
produces raw bytes that Perl happens to use to internally encode the Unicode string. Perl's internal encoding depends on the system as well as what characters happen to be in the string at the time. If any of the characters are at code points `0x100` or above, you will get a warning. To ensure that the output is explicitly rendered in the encoding you desire--and to avoid the warning--open the stream with the desired encoding. Some examples:
```
open FH, ">:utf8", "file";
open FH, ">:encoding(ucs2)", "file";
open FH, ">:encoding(UTF-8)", "file";
open FH, ">:encoding(shift_jis)", "file";
```
and on already open streams, use `binmode()`:
```
binmode(STDOUT, ":utf8");
binmode(STDOUT, ":encoding(ucs2)");
binmode(STDOUT, ":encoding(UTF-8)");
binmode(STDOUT, ":encoding(shift_jis)");
```
The matching of encoding names is loose: case does not matter, and many encodings have several aliases. Note that the `:utf8` layer must always be specified exactly like that; it is *not* subject to the loose matching of encoding names. Also note that currently `:utf8` is unsafe for input, because it accepts the data without validating that it is indeed valid UTF-8; you should instead use `:encoding(UTF-8)` (with or without a hyphen).
See [PerlIO](perlio) for the `:utf8` layer, <PerlIO::encoding> and <Encode::PerlIO> for the `:encoding()` layer, and <Encode::Supported> for many encodings supported by the `Encode` module.
Reading in a file that you know happens to be encoded in one of the Unicode or legacy encodings does not magically turn the data into Unicode in Perl's eyes. To do that, specify the appropriate layer when opening files
```
open(my $fh,'<:encoding(UTF-8)', 'anything');
my $line_of_unicode = <$fh>;
open(my $fh,'<:encoding(Big5)', 'anything');
my $line_of_unicode = <$fh>;
```
The I/O layers can also be specified more flexibly with the `open` pragma. See <open>, or look at the following example.
```
use open ':encoding(UTF-8)'; # input/output default encoding will be
# UTF-8
open X, ">file";
print X chr(0x100), "\n";
close X;
open Y, "<file";
printf "%#x\n", ord(<Y>); # this should print 0x100
close Y;
```
With the `open` pragma you can use the `:locale` layer
```
BEGIN { $ENV{LC_ALL} = $ENV{LANG} = 'ru_RU.KOI8-R' }
# the :locale will probe the locale environment variables like
# LC_ALL
use open OUT => ':locale'; # russki parusski
open(O, ">koi8");
print O chr(0x430); # Unicode CYRILLIC SMALL LETTER A = KOI8-R 0xc1
close O;
open(I, "<koi8");
printf "%#x\n", ord(<I>), "\n"; # this should print 0xc1
close I;
```
These methods install a transparent filter on the I/O stream that converts data from the specified encoding when it is read in from the stream. The result is always Unicode.
The <open> pragma affects all the `open()` calls after the pragma by setting default layers. If you want to affect only certain streams, use explicit layers directly in the `open()` call.
You can switch encodings on an already opened stream by using `binmode()`; see ["binmode" in perlfunc](perlfunc#binmode).
The `:locale` does not currently work with `open()` and `binmode()`, only with the `open` pragma. The `:utf8` and `:encoding(...)` methods do work with all of `open()`, `binmode()`, and the `open` pragma.
Similarly, you may use these I/O layers on output streams to automatically convert Unicode to the specified encoding when it is written to the stream. For example, the following snippet copies the contents of the file "text.jis" (encoded as ISO-2022-JP, aka JIS) to the file "text.utf8", encoded as UTF-8:
```
open(my $nihongo, '<:encoding(iso-2022-jp)', 'text.jis');
open(my $unicode, '>:utf8', 'text.utf8');
while (<$nihongo>) { print $unicode $_ }
```
The naming of encodings, both by the `open()` and by the `open` pragma allows for flexible names: `koi8-r` and `KOI8R` will both be understood.
Common encodings recognized by ISO, MIME, IANA, and various other standardisation organisations are recognised; for a more detailed list see <Encode::Supported>.
`read()` reads characters and returns the number of characters. `seek()` and `tell()` operate on byte counts, as does `sysseek()`.
`sysread()` and `syswrite()` should not be used on file handles with character encoding layers, they behave badly, and that behaviour has been deprecated since perl 5.24.
Notice that because of the default behaviour of not doing any conversion upon input if there is no default layer, it is easy to mistakenly write code that keeps on expanding a file by repeatedly encoding the data:
```
# BAD CODE WARNING
open F, "file";
local $/; ## read in the whole file of 8-bit characters
$t = <F>;
close F;
open F, ">:encoding(UTF-8)", "file";
print F $t; ## convert to UTF-8 on output
close F;
```
If you run this code twice, the contents of the *file* will be twice UTF-8 encoded. A `use open ':encoding(UTF-8)'` would have avoided the bug, or explicitly opening also the *file* for input as UTF-8.
**NOTE**: the `:utf8` and `:encoding` features work only if your Perl has been built with [PerlIO](perlio), which is the default on most systems.
###
Displaying Unicode As Text
Sometimes you might want to display Perl scalars containing Unicode as simple ASCII (or EBCDIC) text. The following subroutine converts its argument so that Unicode characters with code points greater than 255 are displayed as `\x{...}`, control characters (like `\n`) are displayed as `\x..`, and the rest of the characters as themselves:
```
sub nice_string {
join("",
map { $_ > 255 # if wide character...
? sprintf("\\x{%04X}", $_) # \x{...}
: chr($_) =~ /[[:cntrl:]]/ # else if control character...
? sprintf("\\x%02X", $_) # \x..
: quotemeta(chr($_)) # else quoted or as themselves
} unpack("W*", $_[0])); # unpack Unicode characters
}
```
For example,
```
nice_string("foo\x{100}bar\n")
```
returns the string
```
'foo\x{0100}bar\x0A'
```
which is ready to be printed.
(`\\x{}` is used here instead of `\\N{}`, since it's most likely that you want to see what the native values are.)
###
Special Cases
* Starting in Perl 5.28, it is illegal for bit operators, like `~`, to operate on strings containing code points above 255.
* The vec() function may produce surprising results if used on strings containing characters with ordinal values above 255. In such a case, the results are consistent with the internal encoding of the characters, but not with much else. So don't do that, and starting in Perl 5.28, a deprecation message is issued if you do so, becoming illegal in Perl 5.32.
* Peeking At Perl's Internal Encoding
Normal users of Perl should never care how Perl encodes any particular Unicode string (because the normal ways to get at the contents of a string with Unicode--via input and output--should always be via explicitly-defined I/O layers). But if you must, there are two ways of looking behind the scenes.
One way of peeking inside the internal encoding of Unicode characters is to use `unpack("C*", ...` to get the bytes of whatever the string encoding happens to be, or `unpack("U0..", ...)` to get the bytes of the UTF-8 encoding:
```
# this prints c4 80 for the UTF-8 bytes 0xc4 0x80
print join(" ", unpack("U0(H2)*", pack("U", 0x100))), "\n";
```
Yet another way would be to use the Devel::Peek module:
```
perl -MDevel::Peek -e 'Dump(chr(0x100))'
```
That shows the `UTF8` flag in FLAGS and both the UTF-8 bytes and Unicode characters in `PV`. See also later in this document the discussion about the `utf8::is_utf8()` function.
###
Advanced Topics
* String Equivalence
The question of string equivalence turns somewhat complicated in Unicode: what do you mean by "equal"?
(Is `LATIN CAPITAL LETTER A WITH ACUTE` equal to `LATIN CAPITAL LETTER A`?)
The short answer is that by default Perl compares equivalence (`eq`, `ne`) based only on code points of the characters. In the above case, the answer is no (because 0x00C1 != 0x0041). But sometimes, any CAPITAL LETTER A's should be considered equal, or even A's of any case.
The long answer is that you need to consider character normalization and casing issues: see <Unicode::Normalize>, Unicode Technical Report #15, [Unicode Normalization Forms](https://www.unicode.org/reports/tr15) and sections on case mapping in the [Unicode Standard](https://www.unicode.org).
As of Perl 5.8.0, the "Full" case-folding of *Case Mappings/SpecialCasing* is implemented, but bugs remain in `qr//i` with them, mostly fixed by 5.14, and essentially entirely by 5.18.
* String Collation
People like to see their strings nicely sorted--or as Unicode parlance goes, collated. But again, what do you mean by collate?
(Does `LATIN CAPITAL LETTER A WITH ACUTE` come before or after `LATIN CAPITAL LETTER A WITH GRAVE`?)
The short answer is that by default, Perl compares strings (`lt`, `le`, `cmp`, `ge`, `gt`) based only on the code points of the characters. In the above case, the answer is "after", since `0x00C1` > `0x00C0`.
The long answer is that "it depends", and a good answer cannot be given without knowing (at the very least) the language context. See <Unicode::Collate>, and *Unicode Collation Algorithm* <https://www.unicode.org/reports/tr10/>
### Miscellaneous
* Character Ranges and Classes
Character ranges in regular expression bracketed character classes ( e.g., `/[a-z]/`) and in the `tr///` (also known as `y///`) operator are not magically Unicode-aware. What this means is that `[A-Za-z]` will not magically start to mean "all alphabetic letters" (not that it does mean that even for 8-bit characters; for those, if you are using locales (<perllocale>), use `/[[:alpha:]]/`; and if not, use the 8-bit-aware property `\p{alpha}`).
All the properties that begin with `\p` (and its inverse `\P`) are actually character classes that are Unicode-aware. There are dozens of them, see <perluniprops>.
Starting in v5.22, you can use Unicode code points as the end points of regular expression pattern character ranges, and the range will include all Unicode code points that lie between those end points, inclusive.
```
qr/ [ \N{U+03} - \N{U+20} ] /xx
```
includes the code points `\N{U+03}`, `\N{U+04}`, ..., `\N{U+20}`.
This also works for ranges in `tr///` starting in Perl v5.24.
* String-To-Number Conversions
Unicode does define several other decimal--and numeric--characters besides the familiar 0 to 9, such as the Arabic and Indic digits. Perl does not support string-to-number conversion for digits other than ASCII `0` to `9` (and ASCII `a` to `f` for hexadecimal). To get safe conversions from any Unicode string, use ["num()" in Unicode::UCD](Unicode::UCD#num%28%29).
###
Questions With Answers
* Will My Old Scripts Break?
Very probably not. Unless you are generating Unicode characters somehow, old behaviour should be preserved. About the only behaviour that has changed and which could start generating Unicode is the old behaviour of `chr()` where supplying an argument more than 255 produced a character modulo 255. `chr(300)`, for example, was equal to `chr(45)` or "-" (in ASCII), now it is LATIN CAPITAL LETTER I WITH BREVE.
* How Do I Make My Scripts Work With Unicode?
Very little work should be needed since nothing changes until you generate Unicode data. The most important thing is getting input as Unicode; for that, see the earlier I/O discussion. To get full seamless Unicode support, add `use feature 'unicode_strings'` (or `use v5.12` or higher) to your script.
* How Do I Know Whether My String Is In Unicode?
You shouldn't have to care. But you may if your Perl is before 5.14.0 or you haven't specified `use feature 'unicode_strings'` or `use 5.012` (or higher) because otherwise the rules for the code points in the range 128 to 255 are different depending on whether the string they are contained within is in Unicode or not. (See ["When Unicode Does Not Happen" in perlunicode](perlunicode#When-Unicode-Does-Not-Happen).)
To determine if a string is in Unicode, use:
```
print utf8::is_utf8($string) ? 1 : 0, "\n";
```
But note that this doesn't mean that any of the characters in the string are necessary UTF-8 encoded, or that any of the characters have code points greater than 0xFF (255) or even 0x80 (128), or that the string has any characters at all. All the `is_utf8()` does is to return the value of the internal "utf8ness" flag attached to the `$string`. If the flag is off, the bytes in the scalar are interpreted as a single byte encoding. If the flag is on, the bytes in the scalar are interpreted as the (variable-length, potentially multi-byte) UTF-8 encoded code points of the characters. Bytes added to a UTF-8 encoded string are automatically upgraded to UTF-8. If mixed non-UTF-8 and UTF-8 scalars are merged (double-quoted interpolation, explicit concatenation, or printf/sprintf parameter substitution), the result will be UTF-8 encoded as if copies of the byte strings were upgraded to UTF-8: for example,
```
$a = "ab\x80c";
$b = "\x{100}";
print "$a = $b\n";
```
the output string will be UTF-8-encoded `ab\x80c = \x{100}\n`, but `$a` will stay byte-encoded.
Sometimes you might really need to know the byte length of a string instead of the character length. For that use the `bytes` pragma and the `length()` function:
```
my $unicode = chr(0x100);
print length($unicode), "\n"; # will print 1
use bytes;
print length($unicode), "\n"; # will print 2
# (the 0xC4 0x80 of the UTF-8)
no bytes;
```
* How Do I Find Out What Encoding a File Has?
You might try <Encode::Guess>, but it has a number of limitations.
* How Do I Detect Data That's Not Valid In a Particular Encoding?
Use the `Encode` package to try converting it. For example,
```
use Encode 'decode';
if (eval { decode('UTF-8', $string, Encode::FB_CROAK); 1 }) {
# $string is valid UTF-8
} else {
# $string is not valid UTF-8
}
```
Or use `unpack` to try decoding it:
```
use warnings;
@chars = unpack("C0U*", $string_of_bytes_that_I_think_is_utf8);
```
If invalid, a `Malformed UTF-8 character` warning is produced. The "C0" means "process the string character per character". Without that, the `unpack("U*", ...)` would work in `U0` mode (the default if the format string starts with `U`) and it would return the bytes making up the UTF-8 encoding of the target string, something that will always work.
* How Do I Convert Binary Data Into a Particular Encoding, Or Vice Versa?
This probably isn't as useful as you might think. Normally, you shouldn't need to.
In one sense, what you are asking doesn't make much sense: encodings are for characters, and binary data are not "characters", so converting "data" into some encoding isn't meaningful unless you know in what character set and encoding the binary data is in, in which case it's not just binary data, now is it?
If you have a raw sequence of bytes that you know should be interpreted via a particular encoding, you can use `Encode`:
```
use Encode 'from_to';
from_to($data, "iso-8859-1", "UTF-8"); # from latin-1 to UTF-8
```
The call to `from_to()` changes the bytes in `$data`, but nothing material about the nature of the string has changed as far as Perl is concerned. Both before and after the call, the string `$data` contains just a bunch of 8-bit bytes. As far as Perl is concerned, the encoding of the string remains as "system-native 8-bit bytes".
You might relate this to a fictional 'Translate' module:
```
use Translate;
my $phrase = "Yes";
Translate::from_to($phrase, 'english', 'deutsch');
## phrase now contains "Ja"
```
The contents of the string changes, but not the nature of the string. Perl doesn't know any more after the call than before that the contents of the string indicates the affirmative.
Back to converting data. If you have (or want) data in your system's native 8-bit encoding (e.g. Latin-1, EBCDIC, etc.), you can use pack/unpack to convert to/from Unicode.
```
$native_string = pack("W*", unpack("U*", $Unicode_string));
$Unicode_string = pack("U*", unpack("W*", $native_string));
```
If you have a sequence of bytes you **know** is valid UTF-8, but Perl doesn't know it yet, you can make Perl a believer, too:
```
$Unicode = $bytes;
utf8::decode($Unicode);
```
or:
```
$Unicode = pack("U0a*", $bytes);
```
You can find the bytes that make up a UTF-8 sequence with
```
@bytes = unpack("C*", $Unicode_string)
```
and you can create well-formed Unicode with
```
$Unicode_string = pack("U*", 0xff, ...)
```
* How Do I Display Unicode? How Do I Input Unicode?
See <http://www.alanwood.net/unicode/> and <http://www.cl.cam.ac.uk/~mgk25/unicode.html>
* How Does Unicode Work With Traditional Locales?
If your locale is a UTF-8 locale, starting in Perl v5.26, Perl works well for all categories; before this, starting with Perl v5.20, it works for all categories but `LC_COLLATE`, which deals with sorting and the `cmp` operator. But note that the standard `<Unicode::Collate>` and `<Unicode::Collate::Locale>` modules offer much more powerful solutions to collation issues, and work on earlier releases.
For other locales, starting in Perl 5.16, you can specify
```
use locale ':not_characters';
```
to get Perl to work well with them. The catch is that you have to translate from the locale character set to/from Unicode yourself. See ["Unicode I/O"](#Unicode-I%2FO) above for how to
```
use open ':locale';
```
to accomplish this, but full details are in ["Unicode and UTF-8" in perllocale](perllocale#Unicode-and-UTF-8), including gotchas that happen if you don't specify `:not_characters`.
###
Hexadecimal Notation
The Unicode standard prefers using hexadecimal notation because that more clearly shows the division of Unicode into blocks of 256 characters. Hexadecimal is also simply shorter than decimal. You can use decimal notation, too, but learning to use hexadecimal just makes life easier with the Unicode standard. The `U+HHHH` notation uses hexadecimal, for example.
The `0x` prefix means a hexadecimal number, the digits are 0-9 *and* a-f (or A-F, case doesn't matter). Each hexadecimal digit represents four bits, or half a byte. `print 0x..., "\n"` will show a hexadecimal number in decimal, and `printf "%x\n", $decimal` will show a decimal number in hexadecimal. If you have just the "hex digits" of a hexadecimal number, you can use the `hex()` function.
```
print 0x0009, "\n"; # 9
print 0x000a, "\n"; # 10
print 0x000f, "\n"; # 15
print 0x0010, "\n"; # 16
print 0x0011, "\n"; # 17
print 0x0100, "\n"; # 256
print 0x0041, "\n"; # 65
printf "%x\n", 65; # 41
printf "%#x\n", 65; # 0x41
print hex("41"), "\n"; # 65
```
###
Further Resources
* Unicode Consortium
<https://www.unicode.org/>
* Unicode FAQ
<https://www.unicode.org/faq/>
* Unicode Glossary
<https://www.unicode.org/glossary/>
* Unicode Recommended Reading List
The Unicode Consortium has a list of articles and books, some of which give a much more in depth treatment of Unicode: <http://unicode.org/resources/readinglist.html>
* Unicode Useful Resources
<https://www.unicode.org/unicode/onlinedat/resources.html>
* Unicode and Multilingual Support in HTML, Fonts, Web Browsers and Other Applications
<http://www.alanwood.net/unicode/>
* UTF-8 and Unicode FAQ for Unix/Linux
<http://www.cl.cam.ac.uk/~mgk25/unicode.html>
* Legacy Character Sets
<http://www.czyborra.com/> <http://www.eki.ee/letter/>
* You can explore various information from the Unicode data files using the `Unicode::UCD` module.
UNICODE IN OLDER PERLS
-----------------------
If you cannot upgrade your Perl to 5.8.0 or later, you can still do some Unicode processing by using the modules `Unicode::String`, `Unicode::Map8`, and `Unicode::Map`, available from CPAN. If you have the GNU recode installed, you can also use the Perl front-end `Convert::Recode` for character conversions.
The following are fast conversions from ISO 8859-1 (Latin-1) bytes to UTF-8 bytes and back, the code works even with older Perl 5 versions.
```
# ISO 8859-1 to UTF-8
s/([\x80-\xFF])/chr(0xC0|ord($1)>>6).chr(0x80|ord($1)&0x3F)/eg;
# UTF-8 to ISO 8859-1
s/([\xC2\xC3])([\x80-\xBF])/chr(ord($1)<<6&0xC0|ord($2)&0x3F)/eg;
```
SEE ALSO
---------
<perlunitut>, <perlunicode>, [Encode](encode), <open>, <utf8>, <bytes>, <perlretut>, <perlrun>, <Unicode::Collate>, <Unicode::Normalize>, <Unicode::UCD>
ACKNOWLEDGMENTS
---------------
Thanks to the kind readers of the [email protected], [email protected], [email protected], and [email protected] mailing lists for their valuable feedback.
AUTHOR, COPYRIGHT, AND LICENSE
-------------------------------
Copyright 2001-2011 Jarkko Hietaniemi <[email protected]>. Now maintained by Perl 5 Porters.
This document may be distributed under the same terms as Perl itself.
| programming_docs |
perl ExtUtils::MM_OS2 ExtUtils::MM\_OS2
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
NAME
----
ExtUtils::MM\_OS2 - methods to override UN\*X behaviour in ExtUtils::MakeMaker
SYNOPSIS
--------
```
use ExtUtils::MM_OS2; # Done internally by ExtUtils::MakeMaker if needed
```
DESCRIPTION
-----------
See <ExtUtils::MM_Unix> for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics.
METHODS
-------
init\_dist Define TO\_UNIX to convert OS2 linefeeds to Unix style.
init\_linker os\_flavor OS/2 is OS/2
xs\_static\_lib\_is\_xs
perl CPAN::Meta::Requirements CPAN::Meta::Requirements
========================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [add\_minimum](#add_minimum)
+ [add\_maximum](#add_maximum)
+ [add\_exclusion](#add_exclusion)
+ [exact\_version](#exact_version)
+ [add\_requirements](#add_requirements)
+ [accepts\_module](#accepts_module)
+ [clear\_requirement](#clear_requirement)
+ [requirements\_for\_module](#requirements_for_module)
+ [structured\_requirements\_for\_module](#structured_requirements_for_module)
+ [required\_modules](#required_modules)
+ [clone](#clone)
+ [is\_simple](#is_simple)
+ [is\_finalized](#is_finalized)
+ [finalize](#finalize)
+ [as\_string\_hash](#as_string_hash)
+ [add\_string\_requirement](#add_string_requirement)
+ [from\_string\_hash](#from_string_hash)
* [SUPPORT](#SUPPORT)
+ [Bugs / Feature Requests](#Bugs-/-Feature-Requests)
+ [Source Code](#Source-Code)
* [AUTHORS](#AUTHORS)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Requirements - a set of version requirements for a CPAN dist
VERSION
-------
version 2.140
SYNOPSIS
--------
```
use CPAN::Meta::Requirements;
my $build_requires = CPAN::Meta::Requirements->new;
$build_requires->add_minimum('Library::Foo' => 1.208);
$build_requires->add_minimum('Library::Foo' => 2.602);
$build_requires->add_minimum('Module::Bar' => 'v1.2.3');
$METAyml->{build_requires} = $build_requires->as_string_hash;
```
DESCRIPTION
-----------
A CPAN::Meta::Requirements object models a set of version constraints like those specified in the *META.yml* or *META.json* files in CPAN distributions, and as defined by <CPAN::Meta::Spec>; It can be built up by adding more and more constraints, and it will reduce them to the simplest representation.
Logically impossible constraints will be identified immediately by thrown exceptions.
METHODS
-------
### new
```
my $req = CPAN::Meta::Requirements->new;
```
This returns a new CPAN::Meta::Requirements object. It takes an optional hash reference argument. Currently, only one key is supported:
* `bad_version_hook` -- if provided, when a version cannot be parsed into a version object, this code reference will be called with the invalid version string as first argument, and the module name as second argument. It must return a valid version object.
All other keys are ignored.
### add\_minimum
```
$req->add_minimum( $module => $version );
```
This adds a new minimum version requirement. If the new requirement is redundant to the existing specification, this has no effect.
Minimum requirements are inclusive. `$version` is required, along with any greater version number.
This method returns the requirements object.
### add\_maximum
```
$req->add_maximum( $module => $version );
```
This adds a new maximum version requirement. If the new requirement is redundant to the existing specification, this has no effect.
Maximum requirements are inclusive. No version strictly greater than the given version is allowed.
This method returns the requirements object.
### add\_exclusion
```
$req->add_exclusion( $module => $version );
```
This adds a new excluded version. For example, you might use these three method calls:
```
$req->add_minimum( $module => '1.00' );
$req->add_maximum( $module => '1.82' );
$req->add_exclusion( $module => '1.75' );
```
Any version between 1.00 and 1.82 inclusive would be acceptable, except for 1.75.
This method returns the requirements object.
### exact\_version
```
$req->exact_version( $module => $version );
```
This sets the version required for the given module to *exactly* the given version. No other version would be considered acceptable.
This method returns the requirements object.
### add\_requirements
```
$req->add_requirements( $another_req_object );
```
This method adds all the requirements in the given CPAN::Meta::Requirements object to the requirements object on which it was called. If there are any conflicts, an exception is thrown.
This method returns the requirements object.
### accepts\_module
```
my $bool = $req->accepts_module($module => $version);
```
Given an module and version, this method returns true if the version specification for the module accepts the provided version. In other words, given:
```
Module => '>= 1.00, < 2.00'
```
We will accept 1.00 and 1.75 but not 0.50 or 2.00.
For modules that do not appear in the requirements, this method will return true.
### clear\_requirement
```
$req->clear_requirement( $module );
```
This removes the requirement for a given module from the object.
This method returns the requirements object.
### requirements\_for\_module
```
$req->requirements_for_module( $module );
```
This returns a string containing the version requirements for a given module in the format described in <CPAN::Meta::Spec> or undef if the given module has no requirements. This should only be used for informational purposes such as error messages and should not be interpreted or used for comparison (see ["accepts\_module"](#accepts_module) instead).
### structured\_requirements\_for\_module
```
$req->structured_requirements_for_module( $module );
```
This returns a data structure containing the version requirements for a given module or undef if the given module has no requirements. This should not be used for version checks (see ["accepts\_module"](#accepts_module) instead).
Added in version 2.134.
### required\_modules
This method returns a list of all the modules for which requirements have been specified.
### clone
```
$req->clone;
```
This method returns a clone of the invocant. The clone and the original object can then be changed independent of one another.
### is\_simple
This method returns true if and only if all requirements are inclusive minimums -- that is, if their string expression is just the version number.
### is\_finalized
This method returns true if the requirements have been finalized by having the `finalize` method called on them.
### finalize
This method marks the requirements finalized. Subsequent attempts to change the requirements will be fatal, *if* they would result in a change. If they would not alter the requirements, they have no effect.
If a finalized set of requirements is cloned, the cloned requirements are not also finalized.
### as\_string\_hash
This returns a reference to a hash describing the requirements using the strings in the <CPAN::Meta::Spec> specification.
For example after the following program:
```
my $req = CPAN::Meta::Requirements->new;
$req->add_minimum('CPAN::Meta::Requirements' => 0.102);
$req->add_minimum('Library::Foo' => 1.208);
$req->add_maximum('Library::Foo' => 2.602);
$req->add_minimum('Module::Bar' => 'v1.2.3');
$req->add_exclusion('Module::Bar' => 'v1.2.8');
$req->exact_version('Xyzzy' => '6.01');
my $hashref = $req->as_string_hash;
```
`$hashref` would contain:
```
{
'CPAN::Meta::Requirements' => '0.102',
'Library::Foo' => '>= 1.208, <= 2.206',
'Module::Bar' => '>= v1.2.3, != v1.2.8',
'Xyzzy' => '== 6.01',
}
```
### add\_string\_requirement
```
$req->add_string_requirement('Library::Foo' => '>= 1.208, <= 2.206');
$req->add_string_requirement('Library::Foo' => v1.208);
```
This method parses the passed in string and adds the appropriate requirement for the given module. A version can be a Perl "v-string". It understands version ranges as described in the ["Version Ranges" in CPAN::Meta::Spec](CPAN::Meta::Spec#Version-Ranges). For example:
1.3
>= 1.3
<= 1.3
== 1.3
!= 1.3
> 1.3
< 1.3
>= 1.3, != 1.5, <= 2.0 A version number without an operator is equivalent to specifying a minimum (`>=`). Extra whitespace is allowed.
### from\_string\_hash
```
my $req = CPAN::Meta::Requirements->from_string_hash( \%hash );
my $req = CPAN::Meta::Requirements->from_string_hash( \%hash, \%opts );
```
This is an alternate constructor for a CPAN::Meta::Requirements object. It takes a hash of module names and version requirement strings and returns a new CPAN::Meta::Requirements object. As with add\_string\_requirement, a version can be a Perl "v-string". Optionally, you can supply a hash-reference of options, exactly as with the ["new"](#new) method.
SUPPORT
-------
###
Bugs / Feature Requests
Please report any bugs or feature requests through the issue tracker at <https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements/issues>. You will be notified automatically of any progress on your issue.
###
Source Code
This is open source software. The code repository is available for public review and contribution under the terms of the license.
<https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements>
```
git clone https://github.com/Perl-Toolchain-Gang/CPAN-Meta-Requirements.git
```
AUTHORS
-------
* David Golden <[email protected]>
* Ricardo Signes <[email protected]>
CONTRIBUTORS
------------
* Ed J <[email protected]>
* Karen Etheridge <[email protected]>
* Leon Timmermans <[email protected]>
* robario <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by David Golden and Ricardo Signes.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl Encode::CN Encode::CN
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Encode::CN - China-based Chinese Encodings
SYNOPSIS
--------
```
use Encode qw/encode decode/;
$euc_cn = encode("euc-cn", $utf8); # loads Encode::CN implicitly
$utf8 = decode("euc-cn", $euc_cn); # ditto
```
DESCRIPTION
-----------
This module implements China-based Chinese charset encodings. Encodings supported are as follows.
```
Canonical Alias Description
--------------------------------------------------------------------
euc-cn /\beuc.*cn$/i EUC (Extended Unix Character)
/\bcn.*euc$/i
/\bGB[-_ ]?2312(?:\D.*$|$)/i (see below)
gb2312-raw The raw (low-bit) GB2312 character map
gb12345-raw Traditional chinese counterpart to
GB2312 (raw)
iso-ir-165 GB2312 + GB6345 + GB8565 + additions
MacChineseSimp GB2312 + Apple Additions
cp936 Code Page 936, also known as GBK
(Extended GuoBiao)
hz 7-bit escaped GB2312 encoding
--------------------------------------------------------------------
```
To find how to use this module in detail, see [Encode](encode).
NOTES
-----
Due to size concerns, `GB 18030` (an extension to `GBK`) is distributed separately on CPAN, under the name <Encode::HanExtra>. That module also contains extra Taiwan-based encodings.
BUGS
----
When you see `charset=gb2312` on mails and web pages, they really mean `euc-cn` encodings. To fix that, `gb2312` is aliased to `euc-cn`. Use `gb2312-raw` when you really mean it.
The ASCII region (0x00-0x7f) is preserved for all encodings, even though this conflicts with mappings by the Unicode Consortium.
SEE ALSO
---------
[Encode](encode)
perl TAP::Parser::YAMLish::Reader TAP::Parser::YAMLish::Reader
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [read](#read)
- [get\_raw](#get_raw)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
TAP::Parser::YAMLish::Reader - Read YAMLish data from iterator
VERSION
-------
Version 3.44
SYNOPSIS
--------
DESCRIPTION
-----------
Note that parts of this code were derived from <YAML::Tiny> with the permission of Adam Kennedy.
METHODS
-------
###
Class Methods
#### `new`
The constructor `new` creates and returns an empty `TAP::Parser::YAMLish::Reader` object.
```
my $reader = TAP::Parser::YAMLish::Reader->new;
```
###
Instance Methods
#### `read`
```
my $got = $reader->read($iterator);
```
Read YAMLish from a <TAP::Parser::Iterator> and return the data structure it represents.
#### `get_raw`
```
my $source = $reader->get_source;
```
Return the raw YAMLish source from the most recent `read`.
AUTHOR
------
Andy Armstrong, <[email protected]>
Adam Kennedy wrote <YAML::Tiny> which provided the template and many of the YAML matching regular expressions for this module.
SEE ALSO
---------
<YAML::Tiny>, [YAML](yaml), <YAML::Syck>, <Config::Tiny>, <CSS::Tiny>, <http://use.perl.org/~Alias/journal/29427>
COPYRIGHT
---------
Copyright 2007-2011 Andy Armstrong.
Portions copyright 2006-2008 Adam Kennedy.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.
perl Memoize::Expire Memoize::Expire
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [INTERFACE](#INTERFACE)
* [ALTERNATIVES](#ALTERNATIVES)
* [CAVEATS](#CAVEATS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Memoize::Expire - Plug-in module for automatic expiration of memoized values
SYNOPSIS
--------
```
use Memoize;
use Memoize::Expire;
tie my %cache => 'Memoize::Expire',
LIFETIME => $lifetime, # In seconds
NUM_USES => $n_uses;
memoize 'function', SCALAR_CACHE => [HASH => \%cache ];
```
DESCRIPTION
-----------
Memoize::Expire is a plug-in module for Memoize. It allows the cached values for memoized functions to expire automatically. This manual assumes you are already familiar with the Memoize module. If not, you should study that manual carefully first, paying particular attention to the HASH feature.
Memoize::Expire is a layer of software that you can insert in between Memoize itself and whatever underlying package implements the cache. The layer presents a hash variable whose values expire whenever they get too old, have been used too often, or both. You tell `Memoize` to use this forgetful hash as its cache instead of the default, which is an ordinary hash.
To specify a real-time timeout, supply the `LIFETIME` option with a numeric value. Cached data will expire after this many seconds, and will be looked up afresh when it expires. When a data item is looked up afresh, its lifetime is reset.
If you specify `NUM_USES` with an argument of *n*, then each cached data item will be discarded and looked up afresh after the *n*th time you access it. When a data item is looked up afresh, its number of uses is reset.
If you specify both arguments, data will be discarded from the cache when either expiration condition holds.
Memoize::Expire uses a real hash internally to store the cached data. You can use the `HASH` option to Memoize::Expire to supply a tied hash in place of the ordinary hash that Memoize::Expire will normally use. You can use this feature to add Memoize::Expire as a layer in between a persistent disk hash and Memoize. If you do this, you get a persistent disk cache whose entries expire automatically. For example:
```
# Memoize
# |
# Memoize::Expire enforces data expiration policy
# |
# DB_File implements persistence of data in a disk file
# |
# Disk file
use Memoize;
use Memoize::Expire;
use DB_File;
# Set up persistence
tie my %disk_cache => 'DB_File', $filename, O_CREAT|O_RDWR, 0666];
# Set up expiration policy, supplying persistent hash as a target
tie my %cache => 'Memoize::Expire',
LIFETIME => $lifetime, # In seconds
NUM_USES => $n_uses,
HASH => \%disk_cache;
# Set up memoization, supplying expiring persistent hash for cache
memoize 'function', SCALAR_CACHE => [ HASH => \%cache ];
```
INTERFACE
---------
There is nothing special about Memoize::Expire. It is just an example. If you don't like the policy that it implements, you are free to write your own expiration policy module that implements whatever policy you desire. Here is how to do that. Let us suppose that your module will be named MyExpirePolicy.
Short summary: You need to create a package that defines four methods:
TIEHASH Construct and return cache object.
EXISTS Given a function argument, is the corresponding function value in the cache, and if so, is it fresh enough to use?
FETCH Given a function argument, look up the corresponding function value in the cache and return it.
STORE Given a function argument and the corresponding function value, store them into the cache.
CLEAR (Optional.) Flush the cache completely.
The user who wants the memoization cache to be expired according to your policy will say so by writing
```
tie my %cache => 'MyExpirePolicy', args...;
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
```
This will invoke `MyExpirePolicy->TIEHASH(args)`. MyExpirePolicy::TIEHASH should do whatever is appropriate to set up the cache, and it should return the cache object to the caller.
For example, MyExpirePolicy::TIEHASH might create an object that contains a regular Perl hash (which it will to store the cached values) and some extra information about the arguments and how old the data is and things like that. Let us call this object `C'.
When Memoize needs to check to see if an entry is in the cache already, it will invoke `C->EXISTS(key)`. `key` is the normalized function argument. MyExpirePolicy::EXISTS should return 0 if the key is not in the cache, or if it has expired, and 1 if an unexpired value is in the cache. It should *not* return `undef`, because there is a bug in some versions of Perl that will cause a spurious FETCH if the EXISTS method returns `undef`.
If your EXISTS function returns true, Memoize will try to fetch the cached value by invoking `C->FETCH(key)`. MyExpirePolicy::FETCH should return the cached value. Otherwise, Memoize will call the memoized function to compute the appropriate value, and will store it into the cache by calling `C->STORE(key, value)`.
Here is a very brief example of a policy module that expires each cache item after ten seconds.
```
package Memoize::TenSecondExpire;
sub TIEHASH {
my ($package, %args) = @_;
my $cache = $args{HASH} || {};
bless $cache => $package;
}
sub EXISTS {
my ($cache, $key) = @_;
if (exists $cache->{$key} &&
$cache->{$key}{EXPIRE_TIME} > time) {
return 1
} else {
return 0; # Do NOT return `undef' here.
}
}
sub FETCH {
my ($cache, $key) = @_;
return $cache->{$key}{VALUE};
}
sub STORE {
my ($cache, $key, $newvalue) = @_;
$cache->{$key}{VALUE} = $newvalue;
$cache->{$key}{EXPIRE_TIME} = time + 10;
}
```
To use this expiration policy, the user would say
```
use Memoize;
tie my %cache10sec => 'Memoize::TenSecondExpire';
memoize 'function', SCALAR_CACHE => [HASH => \%cache10sec];
```
Memoize would then call `function` whenever a cached value was entirely absent or was older than ten seconds.
You should always support a `HASH` argument to `TIEHASH` that ties the underlying cache so that the user can specify that the cache is also persistent or that it has some other interesting semantics. The example above demonstrates how to do this, as does `Memoize::Expire`.
Another sample module, <Memoize::Saves>, is available in a separate distribution on CPAN. It implements a policy that allows you to specify that certain function values would always be looked up afresh. See the documentation for details.
ALTERNATIVES
------------
Brent Powers has a `Memoize::ExpireLRU` module that was designed to work with Memoize and provides expiration of least-recently-used data. The cache is held at a fixed number of entries, and when new data comes in, the least-recently used data is expired. See <http://search.cpan.org/search?mode=module&query=ExpireLRU>.
Joshua Chamas's Tie::Cache module may be useful as an expiration manager. (If you try this, let me know how it works out.)
If you develop any useful expiration managers that you think should be distributed with Memoize, please let me know.
CAVEATS
-------
This module is experimental, and may contain bugs. Please report bugs to the address below.
Number-of-uses is stored as a 16-bit unsigned integer, so can't exceed 65535.
Because of clock granularity, expiration times may occur up to one second sooner than you expect. For example, suppose you store a value with a lifetime of ten seconds, and you store it at 12:00:00.998 on a certain day. Memoize will look at the clock and see 12:00:00. Then 9.01 seconds later, at 12:00:10.008 you try to read it back. Memoize will look at the clock and see 12:00:10 and conclude that the value has expired. This will probably not occur if you have `Time::HiRes` installed.
AUTHOR
------
Mark-Jason Dominus ([email protected])
Mike Cariaso provided valuable insight into the best way to solve this problem.
SEE ALSO
---------
perl(1)
The Memoize man page.
http://www.plover.com/~mjd/perl/Memoize/ (for news and updates)
I maintain a mailing list on which I occasionally announce new versions of Memoize. The list is for announcements only, not discussion. To join, send an empty message to [email protected].
| programming_docs |
perl perlbug perlbug
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [AUTHORS](#AUTHORS)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
NAME
----
perlbug - how to submit bug reports on Perl
SYNOPSIS
--------
**perlbug**
**perlbug** [ **-v** ] [ **-a** *address* ] [ **-s** *subject* ] [ **-b** *body* | **-f** *inputfile* ] [ **-F** *outputfile* ] [ **-r** *returnaddress* ] [ **-e** *editor* ] [ **-c** *adminaddress* | **-C** ] [ **-S** ] [ **-t** ] [ **-d** ] [ **-h** ] [ **-T** ]
**perlbug** [ **-v** ] [ **-r** *returnaddress* ] [ **-ok** | **-okay** | **-nok** | **-nokay** ]
**perlthanks**
DESCRIPTION
-----------
This program is designed to help you generate bug reports (and thank-you notes) about perl5 and the modules which ship with it.
In most cases, you can just run it interactively from a command line without any special arguments and follow the prompts.
If you have found a bug with a non-standard port (one that was not part of the *standard distribution*), a binary distribution, or a non-core module (such as Tk, DBI, etc), then please see the documentation that came with that distribution to determine the correct place to report bugs.
Bug reports should be submitted to the GitHub issue tracker at <https://github.com/Perl/perl5/issues>. The **[email protected]** address no longer automatically opens tickets. You can use this tool to compose your report and save it to a file which you can then submit to the issue tracker.
In extreme cases, **perlbug** may not work well enough on your system to guide you through composing a bug report. In those cases, you may be able to use **perlbug -d** or **perl -V** to get system configuration information to include in your issue report.
When reporting a bug, please run through this checklist:
What version of Perl you are running? Type `perl -v` at the command line to find out.
Are you running the latest released version of perl? Look at <http://www.perl.org/> to find out. If you are not using the latest released version, please try to replicate your bug on the latest stable release.
Note that reports about bugs in old versions of Perl, especially those which indicate you haven't also tested the current stable release of Perl, are likely to receive less attention from the volunteers who build and maintain Perl than reports about bugs in the current release.
Are you sure what you have is a bug? A significant number of the bug reports we get turn out to be documented features in Perl. Make sure the issue you've run into isn't intentional by glancing through the documentation that comes with the Perl distribution.
Given the sheer volume of Perl documentation, this isn't a trivial undertaking, but if you can point to documentation that suggests the behaviour you're seeing is *wrong*, your issue is likely to receive more attention. You may want to start with **perldoc** <perltrap> for pointers to common traps that new (and experienced) Perl programmers run into.
If you're unsure of the meaning of an error message you've run across, **perldoc** <perldiag> for an explanation. If the message isn't in perldiag, it probably isn't generated by Perl. You may have luck consulting your operating system documentation instead.
If you are on a non-UNIX platform **perldoc** <perlport>, as some features may be unimplemented or work differently.
You may be able to figure out what's going wrong using the Perl debugger. For information about how to use the debugger **perldoc** <perldebug>.
Do you have a proper test case? The easier it is to reproduce your bug, the more likely it will be fixed -- if nobody can duplicate your problem, it probably won't be addressed.
A good test case has most of these attributes: short, simple code; few dependencies on external commands, modules, or libraries; no platform-dependent code (unless it's a platform-specific bug); clear, simple documentation.
A good test case is almost always a good candidate to be included in Perl's test suite. If you have the time, consider writing your test case so that it can be easily included into the standard test suite.
Have you included all relevant information? Be sure to include the **exact** error messages, if any. "Perl gave an error" is not an exact error message.
If you get a core dump (or equivalent), you may use a debugger (**dbx**, **gdb**, etc) to produce a stack trace to include in the bug report.
NOTE: unless your Perl has been compiled with debug info (often **-g**), the stack trace is likely to be somewhat hard to use because it will most probably contain only the function names and not their arguments. If possible, recompile your Perl with debug info and reproduce the crash and the stack trace.
Can you describe the bug in plain English? The easier it is to understand a reproducible bug, the more likely it will be fixed. Any insight you can provide into the problem will help a great deal. In other words, try to analyze the problem (to the extent you can) and report your discoveries.
Can you fix the bug yourself? If so, that's great news; bug reports with patches are likely to receive significantly more attention and interest than those without patches. Please submit your patch via the GitHub Pull Request workflow as described in **perldoc** <perlhack>. You may also send patches to **[email protected]**. When sending a patch, create it using `git format-patch` if possible, though a unified diff created with `diff -pu` will do nearly as well.
Your patch may be returned with requests for changes, or requests for more detailed explanations about your fix.
Here are a few hints for creating high-quality patches:
Make sure the patch is not reversed (the first argument to diff is typically the original file, the second argument your changed file). Make sure you test your patch by applying it with `git am` or the `patch` program before you send it on its way. Try to follow the same style as the code you are trying to patch. Make sure your patch really does work (`make test`, if the thing you're patching is covered by Perl's test suite).
Can you use `perlbug` to submit a thank-you note? Yes, you can do this by either using the `-T` option, or by invoking the program as `perlthanks`. Thank-you notes are good. It makes people smile.
Please make your issue title informative. "a bug" is not informative. Neither is "perl crashes" nor is "HELP!!!". These don't help. A compact description of what's wrong is fine.
Having done your bit, please be prepared to wait, to be told the bug is in your code, or possibly to get no reply at all. The volunteers who maintain Perl are busy folks, so if your problem is an obvious bug in your own code, is difficult to understand or is a duplicate of an existing report, you may not receive a personal reply.
If it is important to you that your bug be fixed, do monitor the issue tracker (you will be subscribed to notifications for issues you submit or comment on) and the commit logs to development versions of Perl, and encourage the maintainers with kind words or offers of frosty beverages. (Please do be kind to the maintainers. Harassing or flaming them is likely to have the opposite effect of the one you want.)
Feel free to update the ticket about your bug on <https://github.com/Perl/perl5/issues> if a new version of Perl is released and your bug is still present.
OPTIONS
-------
**-a**
Address to send the report to instead of saving to a file.
**-b**
Body of the report. If not included on the command line, or in a file with **-f**, you will get a chance to edit the report.
**-C**
Don't send copy to administrator when sending report by mail.
**-c**
Address to send copy of report to when sending report by mail. Defaults to the address of the local perl administrator (recorded when perl was built).
**-d**
Data mode (the default if you redirect or pipe output). This prints out your configuration data, without saving or mailing anything. You can use this with **-v** to get more complete data.
**-e**
Editor to use.
**-f**
File containing the body of the report. Use this to quickly send a prepared report.
**-F**
File to output the results to. Defaults to **perlbug.rep**.
**-h**
Prints a brief summary of the options.
**-ok**
Report successful build on this system to perl porters. Forces **-S** and **-C**. Forces and supplies values for **-s** and **-b**. Only prompts for a return address if it cannot guess it (for use with **make**). Honors return address specified with **-r**. You can use this with **-v** to get more complete data. Only makes a report if this system is less than 60 days old.
**-okay**
As **-ok** except it will report on older systems.
**-nok**
Report unsuccessful build on this system. Forces **-C**. Forces and supplies a value for **-s**, then requires you to edit the report and say what went wrong. Alternatively, a prepared report may be supplied using **-f**. Only prompts for a return address if it cannot guess it (for use with **make**). Honors return address specified with **-r**. You can use this with **-v** to get more complete data. Only makes a report if this system is less than 60 days old.
**-nokay**
As **-nok** except it will report on older systems.
**-p**
The names of one or more patch files or other text attachments to be included with the report. Multiple files must be separated with commas.
**-r**
Your return address. The program will ask you to confirm its default if you don't use this option.
**-S**
Save or send the report without asking for confirmation.
**-s**
Subject to include with the report. You will be prompted if you don't supply one on the command line.
**-t**
Test mode. Makes it possible to command perlbug from a pipe or file, for testing purposes.
**-T**
Send a thank-you note instead of a bug report.
**-v**
Include verbose configuration data in the report.
AUTHORS
-------
Kenneth Albanowski (<[email protected]>), subsequently *doc*tored by Gurusamy Sarathy (<[email protected]>), Tom Christiansen (<[email protected]>), Nathan Torkington (<[email protected]>), Charles F. Randall (<[email protected]>), Mike Guy (<[email protected]>), Dominic Dunlop (<[email protected]>), Hugo van der Sanden (<[email protected]>), Jarkko Hietaniemi (<[email protected]>), Chris Nandor (<[email protected]>), Jon Orwant (<[email protected]>, Richard Foley (<[email protected]>), Jesse Vincent (<[email protected]>), and Craig A. Berry (<[email protected]>).
SEE ALSO
---------
perl(1), perldebug(1), perldiag(1), perlport(1), perltrap(1), diff(1), patch(1), dbx(1), gdb(1)
BUGS
----
None known (guess what must have been used to report them?)
perl FileCache FileCache
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CAVEATS](#CAVEATS)
* [BUGS](#BUGS)
NAME
----
FileCache - keep more files open than the system permits
SYNOPSIS
--------
```
no strict 'refs';
use FileCache;
# or
use FileCache maxopen => 16;
cacheout $mode, $path;
# or
cacheout $path;
print $path @data;
$fh = cacheout $mode, $path;
# or
$fh = cacheout $path;
print $fh @data;
```
DESCRIPTION
-----------
The `cacheout` function will make sure that there's a filehandle open for reading or writing available as the pathname you give it. It automatically closes and re-opens files if you exceed your system's maximum number of file descriptors, or the suggested maximum *maxopen*.
cacheout EXPR The 1-argument form of cacheout will open a file for writing (`'>'`) on it's first use, and appending (`'>>'`) thereafter.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
cacheout MODE, EXPR The 2-argument form of cacheout will use the supplied mode for the initial and subsequent openings. Most valid modes for 3-argument `open` are supported namely; `'>'`, `'+>'`, `'<'`, `'<+'`, `'>>'`, `'|-'` and `'-|'`
To pass supplemental arguments to a program opened with `'|-'` or `'-|'` append them to the command string as you would system EXPR.
Returns EXPR on success for convenience. You may neglect the return value and manipulate EXPR as the filehandle directly if you prefer.
CAVEATS
-------
While it is permissible to `close` a FileCache managed file, do not do so if you are calling `FileCache::cacheout` from a package other than which it was imported, or with another module which overrides `close`. If you must, use `FileCache::cacheout_close`.
Although FileCache can be used with piped opens ('-|' or '|-') doing so is strongly discouraged. If FileCache finds it necessary to close and then reopen a pipe, the command at the far end of the pipe will be reexecuted - the results of performing IO on FileCache'd pipes is unlikely to be what you expect. The ability to use FileCache on pipes may be removed in a future release.
FileCache does not store the current file offset if it finds it necessary to close a file. When the file is reopened, the offset will be as specified by the original `open` file mode. This could be construed to be a bug.
The module functionality relies on symbolic references, so things will break under 'use strict' unless 'no strict "refs"' is also specified.
BUGS
----
*sys/param.h* lies with its `NOFILE` define on some systems, so you may have to set *maxopen* yourself.
perl Term::Complete Term::Complete
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
Term::Complete - Perl word completion module
SYNOPSIS
--------
```
$input = Complete('prompt_string', \@completion_list);
$input = Complete('prompt_string', @completion_list);
```
DESCRIPTION
-----------
This routine provides word completion on the list of words in the array (or array ref).
The tty driver is put into raw mode and restored using an operating system specific command, in UNIX-like environments `stty`.
The following command characters are defined:
<tab> Attempts word completion. Cannot be changed.
^D Prints completion list. Defined by *$Term::Complete::complete*.
^U Erases the current input. Defined by *$Term::Complete::kill*.
<del>, <bs> Erases one character. Defined by *$Term::Complete::erase1* and *$Term::Complete::erase2*.
DIAGNOSTICS
-----------
Bell sounds when word completion fails.
BUGS
----
The completion character <tab> cannot be changed.
AUTHOR
------
Wayne Thompson
perl File::Spec::VMS File::Spec::VMS
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
File::Spec::VMS - methods for VMS file specs
SYNOPSIS
--------
```
require File::Spec::VMS; # Done internally by File::Spec if needed
```
DESCRIPTION
-----------
See File::Spec::Unix for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics.
The default behavior is to allow either VMS or Unix syntax on input and to return VMS syntax on output unless Unix syntax has been explicitly requested via the `DECC$FILENAME_UNIX_REPORT` CRTL feature.
canonpath (override) Removes redundant portions of file specifications and returns results in native syntax unless Unix filename reporting has been enabled.
catdir (override) Concatenates a list of file specifications, and returns the result as a native directory specification unless the Unix filename reporting feature has been enabled. No check is made for "impossible" cases (e.g. elements other than the first being absolute filespecs).
catfile (override) Concatenates a list of directory specifications with a filename specification to build a path.
curdir (override) Returns a string representation of the current directory: '[]' or '.'
devnull (override) Returns a string representation of the null device: '\_NLA0:' or '/dev/null'
rootdir (override) Returns a string representation of the root directory: 'SYS$DISK:[000000]' or '/'
tmpdir (override) Returns a string representation of the first writable directory from the following list or '' if none are writable:
```
/tmp if C<DECC$FILENAME_UNIX_REPORT> is enabled.
sys$scratch:
$ENV{TMPDIR}
```
If running under taint mode, and if $ENV{TMPDIR} is tainted, it is not used.
updir (override) Returns a string representation of the parent directory: '[-]' or '..'
case\_tolerant (override) VMS file specification syntax is case-tolerant.
path (override) Translate logical name DCL$PATH as a searchlist, rather than trying to `split` string value of `$ENV{'PATH'}`.
file\_name\_is\_absolute (override) Checks for VMS directory spec as well as Unix separators.
splitpath (override)
```
($volume,$directories,$file) = File::Spec->splitpath( $path );
($volume,$directories,$file) = File::Spec->splitpath( $path,
$no_file );
```
Passing a true value for `$no_file` indicates that the path being split only contains directory components, even on systems where you can usually (when not supporting a foreign syntax) tell the difference between directories and files at a glance.
splitdir (override) Split a directory specification into the components.
catpath (override) Construct a complete filespec.
abs2rel (override) Attempt to convert an absolute file specification to a relative specification.
rel2abs (override) Return an absolute file specification from a relative one.
COPYRIGHT
---------
Copyright (c) 2004-14 by the Perl 5 Porters. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
See <File::Spec> and <File::Spec::Unix>. This package overrides the implementation of these methods, not the semantics.
An explanation of VMS file specs can be found at <http://h71000.www7.hp.com/doc/731FINAL/4506/4506pro_014.html#apps_locating_naming_files>.
perl Net::Netrc Net::Netrc
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The .netrc File](#The-.netrc-File)
+ [Class Methods](#Class-Methods)
+ [Object Methods](#Object-Methods)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::Netrc - OO interface to users netrc file
SYNOPSIS
--------
```
use Net::Netrc;
$mach = Net::Netrc->lookup('some.machine');
$login = $mach->login;
($login, $password, $account) = $mach->lpa;
```
DESCRIPTION
-----------
`Net::Netrc` is a class implementing a simple interface to the .netrc file used as by the ftp program.
`Net::Netrc` also implements security checks just like the ftp program, these checks are, first that the .netrc file must be owned by the user and second the ownership permissions should be such that only the owner has read and write access. If these conditions are not met then a warning is output and the .netrc file is not read.
###
The *.netrc* File
The .netrc file contains login and initialization information used by the auto-login process. It resides in the user's home directory. The following tokens are recognized; they may be separated by spaces, tabs, or new-lines:
machine name Identify a remote machine name. The auto-login process searches the .netrc file for a machine token that matches the remote machine specified. Once a match is made, the subsequent .netrc tokens are processed, stopping when the end of file is reached or an- other machine or a default token is encountered.
default This is the same as machine name except that default matches any name. There can be only one default token, and it must be after all machine tokens. This is normally used as:
```
default login anonymous password user@site
```
thereby giving the user automatic anonymous login to machines not specified in .netrc.
login name Identify a user on the remote machine. If this token is present, the auto-login process will initiate a login using the specified name.
password string Supply a password. If this token is present, the auto-login process will supply the specified string if the remote server requires a password as part of the login process.
account string Supply an additional account password. If this token is present, the auto-login process will supply the specified string if the remote server requires an additional account password.
macdef name Define a macro. `Net::Netrc` only parses this field to be compatible with *ftp*.
###
Class Methods
The constructor for a `Net::Netrc` object is not called new as it does not really create a new object. But instead is called `lookup` as this is essentially what it does.
`lookup($machine[, $login])`
Lookup and return a reference to the entry for `$machine`. If `$login` is given then the entry returned will have the given login. If `$login` is not given then the first entry in the .netrc file for `$machine` will be returned.
If a matching entry cannot be found, and a default entry exists, then a reference to the default entry is returned.
If there is no matching entry found and there is no default defined, or no .netrc file is found, then `undef` is returned.
###
Object Methods
`login()`
Return the login id for the netrc entry
`password()`
Return the password for the netrc entry
`account()`
Return the account information for the netrc entry
`lpa()`
Return a list of login, password and account information for the netrc entry
EXPORTS
-------
*None*.
KNOWN BUGS
-----------
See <https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=libnet>.
SEE ALSO
---------
<Net::Cmd>.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 1995-1998 Graham Barr. All rights reserved.
Copyright (C) 2013-2014, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
| programming_docs |
perl TAP::Parser::SourceHandler::Perl TAP::Parser::SourceHandler::Perl
================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [can\_handle](#can_handle)
- [make\_iterator](#make_iterator)
- [get\_taint](#get_taint)
- [get\_perl](#get_perl)
* [SUBCLASSING](#SUBCLASSING)
+ [Example](#Example)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Parser::SourceHandler::Perl - Stream TAP from a Perl executable
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::Source;
use TAP::Parser::SourceHandler::Perl;
my $source = TAP::Parser::Source->new->raw( \'script.pl' );
$source->assemble_meta;
my $class = 'TAP::Parser::SourceHandler::Perl';
my $vote = $class->can_handle( $source );
my $iter = $class->make_iterator( $source );
```
DESCRIPTION
-----------
This is a *Perl* <TAP::Parser::SourceHandler> - it has 2 jobs:
1. Figure out if the <TAP::Parser::Source> it's given is actually a Perl script (["can\_handle"](#can_handle)).
2. Creates an iterator for Perl sources (["make\_iterator"](#make_iterator)).
Unless you're writing a plugin or subclassing <TAP::Parser>, you probably won't need to use this module directly.
METHODS
-------
###
Class Methods
#### `can_handle`
```
my $vote = $class->can_handle( $source );
```
Only votes if $source looks like a file. Casts the following votes:
```
0.9 if it has a shebang ala "#!...perl"
0.3 if it has any shebang
0.8 if it's a .t file
0.9 if it's a .pl file
0.75 if it's in a 't' directory
0.25 by default (backwards compat)
```
#### `make_iterator`
```
my $iterator = $class->make_iterator( $source );
```
Constructs & returns a new <TAP::Parser::Iterator::Process> for the source. Assumes `$source->raw` contains a reference to the perl script. `croak`s if the file could not be found.
The command to run is built as follows:
```
$perl @switches $perl_script @test_args
```
The perl command to use is determined by ["get\_perl"](#get_perl). The command generated is guaranteed to preserve:
```
PERL5LIB
PERL5OPT
Taint Mode, if set in the script's shebang
```
*Note:* the command generated will *not* respect any shebang line defined in your Perl script. This is only a problem if you have compiled a custom version of Perl or if you want to use a specific version of Perl for one test and a different version for another, for example:
```
#!/path/to/a/custom_perl --some --args
#!/usr/local/perl-5.6/bin/perl -w
```
Currently you need to write a plugin to get around this.
#### `get_taint`
Decode any taint switches from a Perl shebang line.
```
# $taint will be 't'
my $taint = TAP::Parser::SourceHandler::Perl->get_taint( '#!/usr/bin/perl -t' );
# $untaint will be undefined
my $untaint = TAP::Parser::SourceHandler::Perl->get_taint( '#!/usr/bin/perl' );
```
#### `get_perl`
Gets the version of Perl currently running the test suite.
SUBCLASSING
-----------
Please see ["SUBCLASSING" in TAP::Parser](TAP::Parser#SUBCLASSING) for a subclassing overview.
### Example
```
package MyPerlSourceHandler;
use strict;
use TAP::Parser::SourceHandler::Perl;
use base 'TAP::Parser::SourceHandler::Perl';
# use the version of perl from the shebang line in the test file
sub get_perl {
my $self = shift;
if (my $shebang = $self->shebang( $self->{file} )) {
$shebang =~ /^#!(.*\bperl.*?)(?:(?:\s)|(?:$))/;
return $1 if $1;
}
return $self->SUPER::get_perl(@_);
}
```
SEE ALSO
---------
<TAP::Object>, <TAP::Parser>, <TAP::Parser::IteratorFactory>, <TAP::Parser::SourceHandler>, <TAP::Parser::SourceHandler::Executable>, <TAP::Parser::SourceHandler::File>, <TAP::Parser::SourceHandler::Handle>, <TAP::Parser::SourceHandler::RawTAP>
perl IPC::Open3 IPC::Open3
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [See Also](#See-Also)
* [WARNING](#WARNING)
NAME
----
IPC::Open3 - open a process for reading, writing, and error handling using open3()
SYNOPSIS
--------
```
use Symbol 'gensym'; # vivify a separate handle for STDERR
my $pid = open3(my $chld_in, my $chld_out, my $chld_err = gensym,
'some', 'cmd', 'and', 'args');
# or pass the command through the shell
my $pid = open3(my $chld_in, my $chld_out, my $chld_err = gensym,
'some cmd and args');
# read from parent STDIN
# send STDOUT and STDERR to already open handle
open my $outfile, '>>', 'output.txt' or die "open failed: $!";
my $pid = open3('<&STDIN', $outfile, undef,
'some', 'cmd', 'and', 'args');
# write to parent STDOUT and STDERR
my $pid = open3(my $chld_in, '>&STDOUT', '>&STDERR',
'some', 'cmd', 'and', 'args');
# reap zombie and retrieve exit status
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
```
DESCRIPTION
-----------
Extremely similar to open2(), open3() spawns the given command and connects $chld\_out for reading from the child, $chld\_in for writing to the child, and $chld\_err for errors. If $chld\_err is false, or the same file descriptor as $chld\_out, then STDOUT and STDERR of the child are on the same filehandle. This means that an autovivified lexical cannot be used for the STDERR filehandle, but gensym from [Symbol](symbol) can be used to vivify a new glob reference, see ["SYNOPSIS"](#SYNOPSIS). The $chld\_in will have autoflush turned on.
If $chld\_in begins with `<&`, then $chld\_in will be closed in the parent, and the child will read from it directly. If $chld\_out or $chld\_err begins with `>&`, then the child will send output directly to that filehandle. In both cases, there will be a [dup(2)](http://man.he.net/man2/dup) instead of a [pipe(2)](http://man.he.net/man2/pipe) made.
If either reader or writer is the empty string or undefined, this will be replaced by an autogenerated filehandle. If so, you must pass a valid lvalue in the parameter slot so it can be overwritten in the caller, or an exception will be raised.
The filehandles may also be integers, in which case they are understood as file descriptors.
open3() returns the process ID of the child process. It doesn't return on failure: it just raises an exception matching `/^open3:/`. However, `exec` failures in the child (such as no such file or permission denied), are just reported to $chld\_err under Windows and OS/2, as it is not possible to trap them.
If the child process dies for any reason, the next write to $chld\_in is likely to generate a SIGPIPE in the parent, which is fatal by default. So you may wish to handle this signal.
Note if you specify `-` as the command, in an analogous fashion to `open(my $fh, "-|")` the child process will just be the forked Perl process rather than an external command. This feature isn't yet supported on Win32 platforms.
open3() does not wait for and reap the child process after it exits. Except for short programs where it's acceptable to let the operating system take care of this, you need to do this yourself. This is normally as simple as calling `waitpid $pid, 0` when you're done with the process. Failing to do this can result in an accumulation of defunct or "zombie" processes. See ["waitpid" in perlfunc](perlfunc#waitpid) for more information.
If you try to read from the child's stdout writer and their stderr writer, you'll have problems with blocking, which means you'll want to use select() or <IO::Select>, which means you'd best use sysread() instead of readline() for normal stuff.
This is very dangerous, as you may block forever. It assumes it's going to talk to something like [bc(1)](http://man.he.net/man1/bc), both writing to it and reading from it. This is presumably safe because you "know" that commands like [bc(1)](http://man.he.net/man1/bc) will read a line at a time and output a line at a time. Programs like [sort(1)](http://man.he.net/man1/sort) that read their entire input stream first, however, are quite apt to cause deadlock.
The big problem with this approach is that if you don't have control over source code being run in the child process, you can't control what it does with pipe buffering. Thus you can't just open a pipe to `cat -v` and continually read and write a line from it.
See Also
---------
<IPC::Open2>
Like Open3 but without STDERR capture.
<IPC::Run>
This is a CPAN module that has better error handling and more facilities than Open3.
WARNING
-------
The order of arguments differs from that of open2().
perl Text::Wrap Text::Wrap
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDES](#OVERRIDES)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
Text::Wrap - line wrapping to form simple paragraphs
SYNOPSIS
--------
**Example 1**
```
use Text::Wrap;
$initial_tab = "\t"; # Tab before first line
$subsequent_tab = ""; # All other lines flush left
print wrap($initial_tab, $subsequent_tab, @text);
print fill($initial_tab, $subsequent_tab, @text);
$lines = wrap($initial_tab, $subsequent_tab, @text);
@paragraphs = fill($initial_tab, $subsequent_tab, @text);
```
**Example 2**
```
use Text::Wrap qw(wrap $columns $huge);
$columns = 132; # Wrap at 132 characters
$huge = 'die';
$huge = 'wrap';
$huge = 'overflow';
```
**Example 3**
```
use Text::Wrap;
$Text::Wrap::columns = 72;
print wrap('', '', @text);
```
DESCRIPTION
-----------
`Text::Wrap::wrap()` is a very simple paragraph formatter. It formats a single paragraph at a time by breaking lines at word boundaries. Indentation is controlled for the first line (`$initial_tab`) and all subsequent lines (`$subsequent_tab`) independently. Please note: `$initial_tab` and `$subsequent_tab` are the literal strings that will be used: it is unlikely you would want to pass in a number.
`Text::Wrap::fill()` is a simple multi-paragraph formatter. It formats each paragraph separately and then joins them together when it's done. It will destroy any whitespace in the original text. It breaks text into paragraphs by looking for whitespace after a newline. In other respects, it acts like wrap().
`wrap()` compresses trailing whitespace into one newline, and `fill()` deletes all trailing whitespace.
Both `wrap()` and `fill()` return a single string.
Unlike the old Unix fmt(1) utility, this module correctly accounts for any Unicode combining characters (such as diacriticals) that may occur in each line for both expansion and unexpansion. These are overstrike characters that do not increment the logical position. Make sure you have the appropriate Unicode settings enabled.
OVERRIDES
---------
`Text::Wrap::wrap()` has a number of variables that control its behavior. Because other modules might be using `Text::Wrap::wrap()` it is suggested that you leave these variables alone! If you can't do that, then use `local($Text::Wrap::VARIABLE) = YOURVALUE` when you change the values so that the original value is restored. This `local()` trick will not work if you import the variable into your own namespace.
Lines are wrapped at `$Text::Wrap::columns` columns (default value: 76). `$Text::Wrap::columns` should be set to the full width of your output device. In fact, every resulting line will have length of no more than `$columns - 1`.
It is possible to control which characters terminate words by modifying `$Text::Wrap::break`. Set this to a string such as `'[\s:]'` (to break before spaces or colons) or a pre-compiled regexp such as `qr/[\s']/` (to break before spaces or apostrophes). The default is simply `'\s'`; that is, words are terminated by spaces. (This means, among other things, that trailing punctuation such as full stops or commas stay with the word they are "attached" to.) Setting `$Text::Wrap::break` to a regular expression that doesn't eat any characters (perhaps just a forward look-ahead assertion) will cause warnings.
Beginner note: In example 2, above `$columns` is imported into the local namespace, and set locally. In example 3, `$Text::Wrap::columns` is set in its own namespace without importing it.
`Text::Wrap::wrap()` starts its work by expanding all the tabs in its input into spaces. The last thing it does it to turn spaces back into tabs. If you do not want tabs in your results, set `$Text::Wrap::unexpand` to a false value. Likewise if you do not want to use 8-character tabstops, set `$Text::Wrap::tabstop` to the number of characters you do want for your tabstops.
If you want to separate your lines with something other than `\n` then set `$Text::Wrap::separator` to your preference. This replaces all newlines with `$Text::Wrap::separator`. If you just want to preserve existing newlines but add new breaks with something else, set `$Text::Wrap::separator2` instead.
When words that are longer than `$columns` are encountered, they are broken up. `wrap()` adds a `"\n"` at column `$columns`. This behavior can be overridden by setting `$huge` to 'die' or to 'overflow'. When set to 'die', large words will cause `die()` to be called. When set to 'overflow', large words will be left intact.
Historical notes: 'die' used to be the default value of `$huge`. Now, 'wrap' is the default value.
EXAMPLES
--------
Code:
```
print wrap("\t","",<<END);
This is a bit of text that forms
a normal book-style indented paragraph
END
```
Result:
```
" This is a bit of text that forms
a normal book-style indented paragraph
"
```
Code:
```
$Text::Wrap::columns=20;
$Text::Wrap::separator="|";
print wrap("","","This is a bit of text that forms a normal book-style paragraph");
```
Result:
```
"This is a bit of|text that forms a|normal book-style|paragraph"
```
SEE ALSO
---------
For correct handling of East Asian half- and full-width characters, see <Text::WrapI18N>. For more detailed controls: <Text::Format>.
AUTHOR
------
David Muir Sharnoff <[email protected]> with help from Tim Pierce and many many others.
LICENSE
-------
Copyright (C) 1996-2009 David Muir Sharnoff. Copyright (C) 2012-2013 Google, Inc. This module may be modified, used, copied, and redistributed at your own risk. Although allowed by the preceding license, please do not publicly redistribute modified versions of this code with the name "Text::Wrap" unless it passes the unmodified Text::Wrap test suite.
perl Test2::API Test2::API
==========
CONTENTS
--------
* [NAME](#NAME)
* [\*\*\*INTERNALS NOTE\*\*\*](#***INTERNALS-NOTE***)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
+ [WRITING A TOOL](#WRITING-A-TOOL)
+ [TESTING YOUR TOOLS](#TESTING-YOUR-TOOLS)
+ [OTHER API FUNCTIONS](#OTHER-API-FUNCTIONS)
* [MAIN API EXPORTS](#MAIN-API-EXPORTS)
+ [context(...)](#context(...))
- [OPTIONAL PARAMETERS](#OPTIONAL-PARAMETERS)
+ [release($;$)](#release(%24;%24))
+ [context\_do(&;@)](#context_do(&;@))
+ [no\_context(&;$)](#no_context(&;%24))
+ [intercept(&)](#intercept(&))
+ [run\_subtest(...)](#run_subtest(...))
- [ARGUMENTS:](#ARGUMENTS:)
- [BUFFERED VS UNBUFFERED (OR STREAMED)](#BUFFERED-VS-UNBUFFERED-(OR-STREAMED))
* [OTHER API EXPORTS](#OTHER-API-EXPORTS)
+ [STATUS AND INITIALIZATION STATE](#STATUS-AND-INITIALIZATION-STATE)
+ [BEHAVIOR HOOKS](#BEHAVIOR-HOOKS)
+ [IPC AND CONCURRENCY](#IPC-AND-CONCURRENCY)
+ [MANAGING FORMATTERS](#MANAGING-FORMATTERS)
* [OTHER EXAMPLES](#OTHER-EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
* [MAGIC](#MAGIC)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API - Primary interface for writing Test2 based testing tools.
\*\*\*INTERNALS NOTE\*\*\*
---------------------------
**The internals of this package are subject to change at any time!** The public methods provided will not change in backwards-incompatible ways (once there is a stable release), but the underlying implementation details might. **Do not break encapsulation here!**
Currently the implementation is to create a single instance of the <Test2::API::Instance> Object. All class methods defer to the single instance. There is no public access to the singleton, and that is intentional. The class methods provided by this package provide the only functionality publicly exposed.
This is done primarily to avoid the problems Test::Builder had by exposing its singleton. We do not want anyone to replace this singleton, rebless it, or directly muck with its internals. If you need to do something and cannot because of the restrictions placed here, then please report it as an issue. If possible, we will create a way for you to implement your functionality without exposing things that should not be exposed.
DESCRIPTION
-----------
This package exports all the functions necessary to write and/or verify testing tools. Using these building blocks you can begin writing test tools very quickly. You are also provided with tools that help you to test the tools you write.
SYNOPSIS
--------
###
WRITING A TOOL
The `context()` method is your primary interface into the Test2 framework.
```
package My::Ok;
use Test2::API qw/context/;
our @EXPORT = qw/my_ok/;
use base 'Exporter';
# Just like ok() from Test::More
sub my_ok($;$) {
my ($bool, $name) = @_;
my $ctx = context(); # Get a context
$ctx->ok($bool, $name);
$ctx->release; # Release the context
return $bool;
}
```
See <Test2::API::Context> for a list of methods available on the context object.
###
TESTING YOUR TOOLS
The `intercept { ... }` tool lets you temporarily intercept all events generated by the test system:
```
use Test2::API qw/intercept/;
use My::Ok qw/my_ok/;
my $events = intercept {
# These events are not displayed
my_ok(1, "pass");
my_ok(0, "fail");
};
```
As of version 1.302178 this now returns an arrayref that is also an instance of <Test2::API::InterceptResult>. See the <Test2::API::InterceptResult> documentation for details on how to best use it.
###
OTHER API FUNCTIONS
```
use Test2::API qw{
test2_init_done
test2_stack
test2_set_is_end
test2_get_is_end
test2_ipc
test2_formatter_set
test2_formatter
test2_is_testing_done
};
my $init = test2_init_done();
my $stack = test2_stack();
my $ipc = test2_ipc();
test2_formatter_set($FORMATTER)
my $formatter = test2_formatter();
... And others ...
```
MAIN API EXPORTS
-----------------
All exports are optional. You must specify subs to import.
```
use Test2::API qw/context intercept run_subtest/;
```
This is the list of exports that are most commonly needed. If you are simply writing a tool, then this is probably all you need. If you need something and you cannot find it here, then you can also look at ["OTHER API EXPORTS"](#OTHER-API-EXPORTS).
These exports lack the 'test2\_' prefix because of how important/common they are. Exports in the ["OTHER API EXPORTS"](#OTHER-API-EXPORTS) section have the 'test2\_' prefix to ensure they stand out.
###
context(...)
Usage:
$ctx = context()
$ctx = context(%params) The `context()` function will always return the current context. If there is already a context active, it will be returned. If there is not an active context, one will be generated. When a context is generated it will default to using the file and line number where the currently running sub was called from.
Please see ["CRITICAL DETAILS" in Test2::API::Context](Test2::API::Context#CRITICAL-DETAILS) for important rules about what you can and cannot do with a context once it is obtained.
**Note** This function will throw an exception if you ignore the context object it returns.
**Note** On perls 5.14+ a depth check is used to insure there are no context leaks. This cannot be safely done on older perls due to <https://rt.perl.org/Public/Bug/Display.html?id=127774> You can forcefully enable it either by setting `$ENV{T2_CHECK_DEPTH} = 1` or `$Test2::API::DO_DEPTH_CHECK = 1` **BEFORE** loading <Test2::API>.
####
OPTIONAL PARAMETERS
All parameters to `context` are optional.
level => $int If you must obtain a context in a sub deeper than your entry point you can use this to tell it how many EXTRA stack frames to look back. If this option is not provided the default of `0` is used.
```
sub third_party_tool {
my $sub = shift;
... # Does not obtain a context
$sub->();
...
}
third_party_tool(sub {
my $ctx = context(level => 1);
...
$ctx->release;
});
```
wrapped => $int Use this if you need to write your own tool that wraps a call to `context()` with the intent that it should return a context object.
```
sub my_context {
my %params = ( wrapped => 0, @_ );
$params{wrapped}++;
my $ctx = context(%params);
...
return $ctx;
}
sub my_tool {
my $ctx = my_context();
...
$ctx->release;
}
```
If you do not do this, then tools you call that also check for a context will notice that the context they grabbed was created at the same stack depth, which will trigger protective measures that warn you and destroy the existing context.
stack => $stack Normally `context()` looks at the global hub stack. If you are maintaining your own <Test2::API::Stack> instance you may pass it in to be used instead of the global one.
hub => $hub Use this parameter if you want to obtain the context for a specific hub instead of whatever one happens to be at the top of the stack.
on\_init => sub { ... } This lets you provide a callback sub that will be called **ONLY** if your call to `context()` generated a new context. The callback **WILL NOT** be called if `context()` is returning an existing context. The only argument passed into the callback will be the context object itself.
```
sub foo {
my $ctx = context(on_init => sub { 'will run' });
my $inner = sub {
# This callback is not run since we are getting the existing
# context from our parent sub.
my $ctx = context(on_init => sub { 'will NOT run' });
$ctx->release;
}
$inner->();
$ctx->release;
}
```
on\_release => sub { ... } This lets you provide a callback sub that will be called when the context instance is released. This callback will be added to the returned context even if an existing context is returned. If multiple calls to context add callbacks, then all will be called in reverse order when the context is finally released.
```
sub foo {
my $ctx = context(on_release => sub { 'will run second' });
my $inner = sub {
my $ctx = context(on_release => sub { 'will run first' });
# Neither callback runs on this release
$ctx->release;
}
$inner->();
# Both callbacks run here.
$ctx->release;
}
```
###
release($;$)
Usage:
release $ctx;
release $ctx, ...; This is intended as a shortcut that lets you release your context and return a value in one statement. This function will get your context, and an optional return value. It will release your context, then return your value. Scalar context is always assumed.
```
sub tool {
my $ctx = context();
...
return release $ctx, 1;
}
```
This tool is most useful when you want to return the value you get from calling a function that needs to see the current context:
```
my $ctx = context();
my $out = some_tool(...);
$ctx->release;
return $out;
```
We can combine the last 3 lines of the above like so:
```
my $ctx = context();
release $ctx, some_tool(...);
```
###
context\_do(&;@)
Usage:
```
sub my_tool {
context_do {
my $ctx = shift;
my (@args) = @_;
$ctx->ok(1, "pass");
...
# No need to call $ctx->release, done for you on scope exit.
} @_;
}
```
Using this inside your test tool takes care of a lot of boilerplate for you. It will ensure a context is acquired. It will capture and rethrow any exception. It will insure the context is released when you are done. It preserves the subroutine call context (array, scalar, void).
This is the safest way to write a test tool. The only two downsides to this are a slight performance decrease, and some extra indentation in your source. If the indentation is a problem for you then you can take a peek at the next section.
###
no\_context(&;$)
Usage:
no\_context { ... };
no\_context { ... } $hid;
```
sub my_tool(&) {
my $code = shift;
my $ctx = context();
...
no_context {
# Things in here will not see our current context, they get a new
# one.
$code->();
};
...
$ctx->release;
};
```
This tool will hide a context for the provided block of code. This means any tools run inside the block will get a completely new context if they acquire one. The new context will be inherited by tools nested below the one that acquired it.
This will normally hide the current context for the top hub. If you need to hide the context for a different hub you can pass in the optional `$hid` parameter.
###
intercept(&)
Usage:
```
my $events = intercept {
ok(1, "pass");
ok(0, "fail");
...
};
```
This function takes a codeblock as its only argument, and it has a prototype. It will execute the codeblock, intercepting any generated events in the process. It will return an array reference with all the generated event objects. All events should be subclasses of <Test2::Event>.
As of version 1.302178 the events array that is returned is blssed as an <Test2::API::InterceptResult> instance. <Test2::API::InterceptResult> Provides a helpful interface for filtering and/or inspecting the events list overall, or individual events within the list.
This is intended to help you test your test code. This is not intended for people simply writing tests.
###
run\_subtest(...)
Usage:
```
run_subtest($NAME, \&CODE, $BUFFERED, @ARGS)
# or
run_subtest($NAME, \&CODE, \%PARAMS, @ARGS)
```
This will run the provided codeblock with the args in `@args`. This codeblock will be run as a subtest. A subtest is an isolated test state that is condensed into a single <Test2::Event::Subtest> event, which contains all events generated inside the subtest.
####
ARGUMENTS:
$NAME The name of the subtest.
\&CODE The code to run inside the subtest.
$BUFFERED or \%PARAMS If this is a simple scalar then it will be treated as a boolean for the 'buffered' setting. If this is a hash reference then it will be used as a parameters hash. The param hash will be used for hub construction (with the specified keys removed).
Keys that are removed and used by run\_subtest:
'buffered' => $bool Toggle buffered status.
'inherit\_trace' => $bool Normally the subtest hub is pushed and the sub is allowed to generate its own root context for the hub. When this setting is turned on a root context will be created for the hub that shares the same trace as the current context.
Set this to true if your tool is producing subtests without user-specified subs.
'no\_fork' => $bool Defaults to off. Normally forking inside a subtest will actually fork the subtest, resulting in 2 final subtest events. This parameter will turn off that behavior, only the original process/thread will return a final subtest event.
@ARGS Any extra arguments you want passed into the subtest code.
####
BUFFERED VS UNBUFFERED (OR STREAMED)
Normally all events inside and outside a subtest are sent to the formatter immediately by the hub. Sometimes it is desirable to hold off sending events within a subtest until the subtest is complete. This usually depends on the formatter being used.
Things not effected by this flag In both cases events are generated and stored in an array. This array is eventually used to populate the `subevents` attribute on the <Test2::Event::Subtest> event that is generated at the end of the subtest. This flag has no effect on this part, it always happens.
At the end of the subtest, the final <Test2::Event::Subtest> event is sent to the formatter.
Things that are effected by this flag The `buffered` attribute of the <Test2::Event::Subtest> event will be set to the value of this flag. This means any formatter, listener, etc which looks at the event will know if it was buffered.
Things that are formatter dependant Events within a buffered subtest may or may not be sent to the formatter as they happen. If a formatter fails to specify then the default is to **NOT SEND** the events as they are generated, instead the formatter can pull them from the `subevents` attribute.
A formatter can specify by implementing the `hide_buffered()` method. If this method returns true then events generated inside a buffered subtest will not be sent independently of the final subtest event.
An example of how this is used is the <Test2::Formatter::TAP> formatter. For unbuffered subtests the events are rendered as they are generated. At the end of the subtest, the final subtest event is rendered, but the `subevents` attribute is ignored. For buffered subtests the opposite occurs, the events are NOT rendered as they are generated, instead the `subevents` attribute is used to render them all at once. This is useful when running subtests tests in parallel, since without it the output from subtests would be interleaved together.
OTHER API EXPORTS
------------------
Exports in this section are not commonly needed. These all have the 'test2\_' prefix to help ensure they stand out. You should look at the ["MAIN API EXPORTS"](#MAIN-API-EXPORTS) section before looking here. This section is one where "Great power comes with great responsibility". It is possible to break things badly if you are not careful with these.
All exports are optional. You need to list which ones you want at import time:
```
use Test2::API qw/test2_init_done .../;
```
###
STATUS AND INITIALIZATION STATE
These provide access to internal state and object instances.
$bool = test2\_init\_done() This will return true if the stack and IPC instances have already been initialized. It will return false if they have not. Init happens as late as possible. It happens as soon as a tool requests the IPC instance, the formatter, or the stack.
$bool = test2\_load\_done() This will simply return the boolean value of the loaded flag. If Test2 has finished loading this will be true, otherwise false. Loading is considered complete the first time a tool requests a context.
test2\_set\_is\_end()
test2\_set\_is\_end($bool) This is used to toggle Test2's belief that the END phase has already started. With no arguments this will set it to true. With arguments it will set it to the first argument's value.
This is used to prevent the use of `caller()` in END blocks which can cause segfaults. This is only necessary in some persistent environments that may have multiple END phases.
$bool = test2\_get\_is\_end() Check if Test2 believes it is the END phase.
$stack = test2\_stack() This will return the global <Test2::API::Stack> instance. If this has not yet been initialized it will be initialized now.
$bool = test2\_is\_testing\_done() This will return true if testing is complete and no other events should be sent. This is useful in things like warning handlers where you might want to turn warnings into events, but need them to start acting like normal warnings when testing is done.
```
$SIG{__WARN__} = sub {
my ($warning) = @_;
if (test2_is_testing_done()) {
warn @_;
}
else {
my $ctx = context();
...
$ctx->release
}
}
```
test2\_ipc\_disable Disable IPC.
$bool = test2\_ipc\_diabled Check if IPC is disabled.
test2\_ipc\_wait\_enable()
test2\_ipc\_wait\_disable()
$bool = test2\_ipc\_wait\_enabled() These can be used to turn IPC waiting on and off, or check the current value of the flag.
Waiting is turned on by default. Waiting will cause the parent process/thread to wait until all child processes and threads are finished before exiting. You will almost never want to turn this off.
$bool = test2\_no\_wait()
test2\_no\_wait($bool) **DISCOURAGED**: This is a confusing interface, it is better to use `test2_ipc_wait_enable()`, `test2_ipc_wait_disable()` and `test2_ipc_wait_enabled()`.
This can be used to get/set the no\_wait status. Waiting is turned on by default. Waiting will cause the parent process/thread to wait until all child processes and threads are finished before exiting. You will almost never want to turn this off.
$fh = test2\_stdout()
$fh = test2\_stderr() These functions return the filehandles that test output should be written to. They are primarily useful when writing a custom formatter and code that turns events into actual output (TAP, etc.). They will return a dupe of the original filehandles that formatted output can be sent to regardless of whatever state the currently running test may have left STDOUT and STDERR in.
test2\_reset\_io() Re-dupe the internal filehandles returned by `test2_stdout()` and `test2_stderr()` from the current STDOUT and STDERR. You shouldn't need to do this except in very peculiar situations (for example, you're testing a new formatter and you need control over where the formatter is sending its output.)
###
BEHAVIOR HOOKS
These are hooks that allow you to add custom behavior to actions taken by Test2 and tools built on top of it.
test2\_add\_callback\_exit(sub { ... }) This can be used to add a callback that is called after all testing is done. This is too late to add additional results, the main use of this callback is to set the exit code.
```
test2_add_callback_exit(
sub {
my ($context, $exit, \$new_exit) = @_;
...
}
);
```
The `$context` passed in will be an instance of <Test2::API::Context>. The `$exit` argument will be the original exit code before anything modified it. `$$new_exit` is a reference to the new exit code. You may modify this to change the exit code. Please note that `$$new_exit` may already be different from `$exit`
test2\_add\_callback\_post\_load(sub { ... }) Add a callback that will be called when Test2 is finished loading. This means the callback will be run once, the first time a context is obtained. If Test2 has already finished loading then the callback will be run immediately.
test2\_add\_callback\_testing\_done(sub { ... }) This adds your coderef as a follow-up to the root hub after Test2 is finished loading.
This is essentially a helper to do the following:
```
test2_add_callback_post_load(sub {
my $stack = test2_stack();
$stack->top; # Insure we have a hub
my ($hub) = Test2::API::test2_stack->all;
$hub->set_active(1);
$hub->follow_up(sub { ... }); # <-- Your coderef here
});
```
test2\_add\_callback\_context\_acquire(sub { ... }) Add a callback that will be called every time someone tries to acquire a context. This will be called on EVERY call to `context()`. It gets a single argument, a reference to the hash of parameters being used the construct the context. This is your chance to change the parameters by directly altering the hash.
```
test2_add_callback_context_acquire(sub {
my $params = shift;
$params->{level}++;
});
```
This is a very scary API function. Please do not use this unless you need to. This is here for <Test::Builder> and backwards compatibility. This has you directly manipulate the hash instead of returning a new one for performance reasons.
test2\_add\_callback\_context\_init(sub { ... }) Add a callback that will be called every time a new context is created. The callback will receive the newly created context as its only argument.
test2\_add\_callback\_context\_release(sub { ... }) Add a callback that will be called every time a context is released. The callback will receive the released context as its only argument.
test2\_add\_callback\_pre\_subtest(sub { ... }) Add a callback that will be called every time a subtest is going to be run. The callback will receive the subtest name, coderef, and any arguments.
@list = test2\_list\_context\_acquire\_callbacks() Return all the context acquire callback references.
@list = test2\_list\_context\_init\_callbacks() Returns all the context init callback references.
@list = test2\_list\_context\_release\_callbacks() Returns all the context release callback references.
@list = test2\_list\_exit\_callbacks() Returns all the exit callback references.
@list = test2\_list\_post\_load\_callbacks() Returns all the post load callback references.
@list = test2\_list\_pre\_subtest\_callbacks() Returns all the pre-subtest callback references.
test2\_add\_uuid\_via(sub { ... })
$sub = test2\_add\_uuid\_via() This allows you to provide a UUID generator. If provided UUIDs will be attached to all events, hubs, and contexts. This is useful for storing, tracking, and linking these objects.
The sub you provide should always return a unique identifier. Most things will expect a proper UUID string, however nothing in Test2::API enforces this.
The sub will receive exactly 1 argument, the type of thing being tagged 'context', 'hub', or 'event'. In the future additional things may be tagged, in which case new strings will be passed in. These are purely informative, you can (and usually should) ignore them.
###
IPC AND CONCURRENCY
These let you access, or specify, the IPC system internals.
$bool = test2\_has\_ipc() Check if IPC is enabled.
$ipc = test2\_ipc() This will return the global <Test2::IPC::Driver> instance. If this has not yet been initialized it will be initialized now.
test2\_ipc\_add\_driver($DRIVER) Add an IPC driver to the list. This will add the driver to the start of the list.
@drivers = test2\_ipc\_drivers() Get the list of IPC drivers.
$bool = test2\_ipc\_polling() Check if polling is enabled.
test2\_ipc\_enable\_polling() Turn on polling. This will cull events from other processes and threads every time a context is created.
test2\_ipc\_disable\_polling() Turn off IPC polling.
test2\_ipc\_enable\_shm() Legacy, this is currently a no-op that returns 0;
test2\_ipc\_set\_pending($uniq\_val) Tell other processes and events that an event is pending. `$uniq_val` should be a unique value no other thread/process will generate.
**Note:** After calling this `test2_ipc_get_pending()` will return 1. This is intentional, and not avoidable.
$pending = test2\_ipc\_get\_pending() This returns -1 if there is no way to check (assume yes)
This returns 0 if there are (most likely) no pending events.
This returns 1 if there are (likely) pending events. Upon return it will reset, nothing else will be able to see that there were pending events.
$timeout = test2\_ipc\_get\_timeout()
test2\_ipc\_set\_timeout($timeout) Get/Set the timeout value for the IPC system. This timeout is how long the IPC system will wait for child processes and threads to finish before aborting.
The default value is `30` seconds.
###
MANAGING FORMATTERS
These let you access, or specify, the formatters that can/should be used.
$formatter = test2\_formatter This will return the global formatter class. This is not an instance. By default the formatter is set to <Test2::Formatter::TAP>.
You can override this default using the `T2_FORMATTER` environment variable.
Normally 'Test2::Formatter::' is prefixed to the value in the environment variable:
```
$ T2_FORMATTER='TAP' perl test.t # Use the Test2::Formatter::TAP formatter
$ T2_FORMATTER='Foo' perl test.t # Use the Test2::Formatter::Foo formatter
```
If you want to specify a full module name you use the '+' prefix:
```
$ T2_FORMATTER='+Foo::Bar' perl test.t # Use the Foo::Bar formatter
```
test2\_formatter\_set($class\_or\_instance) Set the global formatter class. This can only be set once. **Note:** This will override anything specified in the 'T2\_FORMATTER' environment variable.
@formatters = test2\_formatters() Get a list of all loaded formatters.
test2\_formatter\_add($class\_or\_instance) Add a formatter to the list. Last formatter added is used at initialization. If this is called after initialization a warning will be issued.
OTHER EXAMPLES
---------------
See the `/Examples/` directory included in this distribution.
SEE ALSO
---------
<Test2::API::Context> - Detailed documentation of the context object.
<Test2::IPC> - The IPC system used for threading/fork support.
<Test2::Formatter> - Formatters such as TAP live here.
<Test2::Event> - Events live in this namespace.
<Test2::Hub> - All events eventually funnel through a hub. Custom hubs are how `intercept()` and `run_subtest()` are implemented.
MAGIC
-----
This package has an END block. This END block is responsible for setting the exit code based on the test results. This end block also calls the callbacks that can be added to this package.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
| programming_docs |
perl TAP::Formatter::Console::Session TAP::Formatter::Console::Session
================================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [clear\_for\_close](#clear_for_close)
+ [close\_test](#close_test)
+ [header](#header)
+ [result](#result)
NAME
----
TAP::Formatter::Console::Session - Harness output delegate for default console output
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides console orientated output formatting for TAP::Harness.
### `clear_for_close`
### `close_test`
### `header`
### `result`
perl ExtUtils::MM_VOS ExtUtils::MM\_VOS
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overridden methods](#Overridden-methods)
- [extra\_clean\_files](#extra_clean_files)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::MM\_VOS - VOS specific subclass of ExtUtils::MM\_Unix
SYNOPSIS
--------
```
Don't use this module directly.
Use ExtUtils::MM and let it choose.
```
DESCRIPTION
-----------
This is a subclass of <ExtUtils::MM_Unix> which contains functionality for VOS.
Unless otherwise stated it works just like ExtUtils::MM\_Unix.
###
Overridden methods
#### extra\_clean\_files
Cleanup VOS core files
AUTHOR
------
Michael G Schwern <[email protected]> with code from ExtUtils::MM\_Unix
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl Internals Internals
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [FUNCTIONS](#FUNCTIONS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Internals - Reserved special namespace for internals related functions
SYNOPSIS
--------
```
$is_ro= Internals::SvREADONLY($x)
$refcnt= Internals::SvREFCNT($x)
hv_clear_placeholders(%hash);
```
DESCRIPTION
-----------
The Internals namespace is used by the core Perl development team to expose certain low level internals routines for testing and other purposes.
In theory these routines were not and are not intended to be used outside of the perl core, and are subject to change and removal at any time.
In practice people have come to depend on these over the years, despite being historically undocumented, so we will provide some level of forward compatibility for some time. Nevertheless you can assume that any routine documented here is experimental or deprecated and you should find alternatives to their use.
### FUNCTIONS
SvREFCNT(THING [, $value]) Historically Perl has been a refcounted language. This means that each variable tracks how many things reference it, and when the variable is no longer referenced it will automatically free itself. In theory Perl code should not have to care about this, and in a future version Perl might change to some other strategy, although in practice this is unlikely.
This function allows one to violate the abstraction of variables and get or set the refcount of a variable, and in generally is really only useful in code that is testing refcount behavior.
\*NOTE\* You are strongly discouraged from using this function in non-test code and especially discouraged from using the set form of this function. The results of doing so may result in segmentation faults or other undefined behavior.
SvREADONLY(THING, [, $value]) Set or get whether a variable is readonly or not. Exactly what the readonly flag means depend on the type of the variable affected and the version of perl used.
You are strongly discouraged from using this function directly. It is used by various core modules, like `Hash::Util`, and the `constant` pragma to implement higher-level behavior which should be used instead.
See the core implementation for the exact meaning of the readonly flag for each internal variable type.
hv\_clear\_placeholders(%hash) Clear any placeholders from a locked hash. Should not be used directly. You should use the wrapper functions provided by Hash::Util instead. As of 5.25 also available as `Hash::Util::_clear_placeholders(%hash)`
AUTHOR
------
Perl core development team.
SEE ALSO
---------
<perlguts> <Hash::Util> <constant> universal.c
perl perlhack perlhack
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SUPER QUICK PATCH GUIDE](#SUPER-QUICK-PATCH-GUIDE)
* [BUG REPORTING](#BUG-REPORTING)
* [PERL 5 PORTERS](#PERL-5-PORTERS)
+ [perl-changes mailing list](#perl-changes-mailing-list)
+ [#p5p on IRC](#%23p5p-on-IRC)
* [GETTING THE PERL SOURCE](#GETTING-THE-PERL-SOURCE)
+ [Read access via Git](#Read-access-via-Git)
+ [Read access via the web](#Read-access-via-the-web)
+ [Write access via git](#Write-access-via-git)
* [PATCHING PERL](#PATCHING-PERL)
+ [Submitting patches](#Submitting-patches)
+ [Getting your patch accepted](#Getting-your-patch-accepted)
- [Patch style](#Patch-style)
- [Commit message](#Commit-message)
- [Comments, Comments, Comments](#Comments,-Comments,-Comments)
- [Style](#Style)
- [Test suite](#Test-suite)
+ [Patching a core module](#Patching-a-core-module)
+ [Updating perldelta](#Updating-perldelta)
+ [What makes for a good patch?](#What-makes-for-a-good-patch?)
- [Does the concept match the general goals of Perl?](#Does-the-concept-match-the-general-goals-of-Perl?)
- [Where is the implementation?](#Where-is-the-implementation?)
- [Backwards compatibility](#Backwards-compatibility)
- [Could it be a module instead?](#Could-it-be-a-module-instead?)
- [Is the feature generic enough?](#Is-the-feature-generic-enough?)
- [Does it potentially introduce new bugs?](#Does-it-potentially-introduce-new-bugs?)
- [How big is it?](#How-big-is-it?)
- [Does it preclude other desirable features?](#Does-it-preclude-other-desirable-features?)
- [Is the implementation robust?](#Is-the-implementation-robust?)
- [Is the implementation generic enough to be portable?](#Is-the-implementation-generic-enough-to-be-portable?)
- [Is the implementation tested?](#Is-the-implementation-tested?)
- [Is there enough documentation?](#Is-there-enough-documentation?)
- [Is there another way to do it?](#Is-there-another-way-to-do-it?)
- [Does it create too much work?](#Does-it-create-too-much-work?)
- [Patches speak louder than words](#Patches-speak-louder-than-words)
* [TESTING](#TESTING)
+ [Special make test targets](#Special-make-test-targets)
+ [Parallel tests](#Parallel-tests)
+ [Running tests by hand](#Running-tests-by-hand)
+ [Using t/harness for testing](#Using-t/harness-for-testing)
- [Other environment variables that may influence tests](#Other-environment-variables-that-may-influence-tests)
+ [Performance testing](#Performance-testing)
+ [Building perl at older commits](#Building-perl-at-older-commits)
* [MORE READING FOR GUTS HACKERS](#MORE-READING-FOR-GUTS-HACKERS)
* [CPAN TESTERS AND PERL SMOKERS](#CPAN-TESTERS-AND-PERL-SMOKERS)
* [WHAT NEXT?](#WHAT-NEXT?)
+ ["The Road goes ever on and on, down from the door where it began."](#%22The-Road-goes-ever-on-and-on,-down-from-the-door-where-it-began.%22)
+ [Metaphoric Quotations](#Metaphoric-Quotations)
* [AUTHOR](#AUTHOR)
NAME
----
perlhack - How to hack on Perl
DESCRIPTION
-----------
This document explains how Perl development works. It includes details about the Perl 5 Porters email list, the Perl repository, the Perl bug tracker, patch guidelines, and commentary on Perl development philosophy.
SUPER QUICK PATCH GUIDE
------------------------
If you just want to submit a single small patch like a pod fix, a test for a bug, comment fixes, etc., it's easy! Here's how:
* Check out the source repository
The perl source is in a git repository. You can clone the repository with the following command:
```
% git clone https://github.com/Perl/perl5.git perl
```
* Ensure you're following the latest advice
In case the advice in this guide has been updated recently, read the latest version directly from the perl source:
```
% perldoc pod/perlhack.pod
```
* Create a branch for your change
Create a branch based on blead to commit your change to, which will later be used to send it to the Perl issue tracker.
```
% git checkout -b mychange
```
* Make your change
Hack, hack, hack. Keep in mind that Perl runs on many different platforms, with different operating systems that have different capabilities, different filesystem organizations, and even different character sets. <perlhacktips> gives advice on this.
* Test your change
You can run all the tests with the following commands:
```
% ./Configure -des -Dusedevel
% make test
```
Keep hacking until the tests pass.
* Commit your change
Committing your work will save the change *on your local system*:
```
% git commit -a -m 'Commit message goes here'
```
Make sure the commit message describes your change in a single sentence. For example, "Fixed spelling errors in perlhack.pod".
* Send your change to the Perl issue tracker
The next step is to submit your patch to the Perl core ticket system.
Create a GitHub fork of the perl5 repository and add it as a remote, if you haven't already, as described in the GitHub documentation at <https://help.github.com/en/articles/working-with-forks>.
```
% git remote add fork [email protected]:MyUser/perl5.git
```
For more information, see ["Connecting to GitHub with SSH"](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/connecting-to-github-with-ssh).
If you'd rather use an HTTPS URL for your `git push` see ["Cloning with HTTPS URLs"](https://docs.github.com/en/free-pro-team@latest/github/using-git/which-remote-url-should-i-use#cloning-with-https-urls).
```
% git remote add fork https://github.com/MyUser/perl5.git
```
Then, push your new branch to your fork.
```
% git push -u fork mychange
```
Finally, create a Pull Request on GitHub from your branch to blead as described in the GitHub documentation at <https://help.github.com/en/articles/creating-a-pull-request-from-a-fork>.
* Thank you
The porters appreciate the time you spent helping to make Perl better. Thank you!
* Acknowledgement
All contributors are credited (by name and email address) in the AUTHORS file, which is part of the perl distribution, as well as the Git commit history.
If you don’t want to be included in the AUTHORS file, just let us know. Otherwise we will take your submission of a patch as permission to credit you in the AUTHORS file.
* Next time
The next time you wish to make a patch, you need to start from the latest perl in a pristine state. Check you don't have any local changes or added files in your perl check-out which you wish to keep, then run these commands:
```
% git checkout blead
% git pull
% git reset --hard origin/blead
% git clean -dxf
```
BUG REPORTING
--------------
If you want to report a bug in Perl, or browse existing Perl bugs and patches, use the GitHub issue tracker at <https://github.com/perl/perl5/issues>.
Please check the archive of the perl5-porters list (see below) and/or the bug tracking system before submitting a bug report. Often, you'll find that the bug has been reported already.
You can log in to the bug tracking system and comment on existing bug reports. If you have additional information regarding an existing bug, please add it. This will help the porters fix the bug.
PERL 5 PORTERS
---------------
The perl5-porters (p5p) mailing list is where the Perl standard distribution is maintained and developed. The people who maintain Perl are also referred to as the "Perl 5 Porters", "p5p" or just the "porters".
A searchable archive of the list is available at <https://markmail.org/search/?q=perl5-porters>. There is also an archive at <https://archive.develooper.com/[email protected]/>.
###
perl-changes mailing list
The perl5-changes mailing list receives a copy of each patch that gets submitted to the maintenance and development branches of the perl repository. See <https://lists.perl.org/list/perl5-changes.html> for subscription and archive information.
###
#p5p on IRC
Many porters are also active on the <irc://irc.perl.org/#p5p> channel. Feel free to join the channel and ask questions about hacking on the Perl core.
GETTING THE PERL SOURCE
------------------------
All of Perl's source code is kept centrally in a Git repository at *github.com*. The repository contains many Perl revisions from Perl 1 onwards and all the revisions from Perforce, the previous version control system.
For much more detail on using git with the Perl repository, please see <perlgit>.
###
Read access via Git
You will need a copy of Git for your computer. You can fetch a copy of the repository using the git protocol:
```
% git clone [email protected]:Perl/perl5.git perl
```
This clones the repository and makes a local copy in the *perl* directory.
If you cannot use the git protocol for firewall reasons, you can also clone via http:
```
% git clone https://github.com/Perl/perl5.git perl
```
###
Read access via the web
You may access the repository over the web. This allows you to browse the tree, see recent commits, subscribe to repository notifications, search for particular commits and more. You may access it at <https://github.com/Perl/perl5>.
###
Write access via git
If you have a commit bit, please see <perlgit> for more details on using git.
PATCHING PERL
--------------
If you're planning to do more extensive work than a single small fix, we encourage you to read the documentation below. This will help you focus your work and make your patches easier to incorporate into the Perl source.
###
Submitting patches
If you have a small patch to submit, please submit it via the GitHub Pull Request workflow. You may also send patches to the p5p list.
Patches are reviewed and discussed on GitHub or the p5p list. Simple, uncontroversial patches will usually be applied without any discussion. When the patch is applied, the ticket will be updated and you will receive email.
In other cases, the patch will need more work or discussion. You are encouraged to participate in the discussion and advocate for your patch. Sometimes your patch may get lost in the shuffle. It's appropriate to send a reminder email to p5p if no action has been taken in a month. Please remember that the Perl 5 developers are all volunteers, and be polite.
Changes are always applied directly to the main development branch, called "blead". Some patches may be backported to a maintenance branch. If you think your patch is appropriate for the maintenance branch (see ["MAINTENANCE BRANCHES" in perlpolicy](perlpolicy#MAINTENANCE-BRANCHES)), please explain why when you submit it.
###
Getting your patch accepted
If you are submitting a code patch there are several things that you can do to help the Perl 5 Porters accept your patch.
####
Patch style
Using the GitHub Pull Request workflow, your patch will automatically be available in a suitable format. If you wish to submit a patch to the p5p list for review, make sure to create it appropriately.
If you used git to check out the Perl source, then using `git format-patch` will produce a patch in a style suitable for Perl. The `format-patch` command produces one patch file for each commit you made. If you prefer to send a single patch for all commits, you can use `git diff`.
```
% git checkout blead
% git pull
% git diff blead my-branch-name
```
This produces a patch based on the difference between blead and your current branch. It's important to make sure that blead is up to date before producing the diff, that's why we call `git pull` first.
We strongly recommend that you use git if possible. It will make your life easier, and ours as well.
However, if you're not using git, you can still produce a suitable patch. You'll need a pristine copy of the Perl source to diff against. The porters prefer unified diffs. Using GNU `diff`, you can produce a diff like this:
```
% diff -Npurd perl.pristine perl.mine
```
Make sure that you `make realclean` in your copy of Perl to remove any build artifacts, or you may get a confusing result.
####
Commit message
As you craft each patch you intend to submit to the Perl core, it's important to write a good commit message. This is especially important if your submission will consist of a series of commits.
The first line of the commit message should be a short description without a period. It should be no longer than the subject line of an email, 50 characters being a good rule of thumb.
A lot of Git tools (Gitweb, GitHub, git log --pretty=oneline, ...) will only display the first line (cut off at 50 characters) when presenting commit summaries.
The commit message should include a description of the problem that the patch corrects or new functionality that the patch adds.
As a general rule of thumb, your commit message should help a programmer who knows the Perl core quickly understand what you were trying to do, how you were trying to do it, and why the change matters to Perl.
* Why
Your commit message should describe why the change you are making is important. When someone looks at your change in six months or six years, your intent should be clear.
If you're deprecating a feature with the intent of later simplifying another bit of code, say so. If you're fixing a performance problem or adding a new feature to support some other bit of the core, mention that.
* What
Your commit message should describe what part of the Perl core you're changing and what you expect your patch to do.
* How
While it's not necessary for documentation changes, new tests or trivial patches, it's often worth explaining how your change works. Even if it's clear to you today, it may not be clear to a porter next month or next year.
A commit message isn't intended to take the place of comments in your code. Commit messages should describe the change you made, while code comments should describe the current state of the code.
If you've just implemented a new feature, complete with doc, tests and well-commented code, a brief commit message will often suffice. If, however, you've just changed a single character deep in the parser or lexer, you might need to write a small novel to ensure that future readers understand what you did and why you did it.
####
Comments, Comments, Comments
Be sure to adequately comment your code. While commenting every line is unnecessary, anything that takes advantage of side effects of operators, that creates changes that will be felt outside of the function being patched, or that others may find confusing should be documented. If you are going to err, it is better to err on the side of adding too many comments than too few.
The best comments explain *why* the code does what it does, not *what it does*.
#### Style
In general, please follow the particular style of the code you are patching.
In particular, follow these general guidelines for patching Perl sources:
* 4-wide indents for code, 2-wide indents for nested CPP `#define`s, with 8-wide tabstops.
* Use spaces for indentation, not tab characters.
The codebase is a mixture of tabs and spaces for indentation, and we are moving to spaces only. Converting lines you're patching from 8-wide tabs to spaces will help this migration.
* Try not to exceed 79 columns
In general, we target 80 column lines. When sticking to 80 columns would lead to torturous code or rework, it's fine to go longer. Try to keep your excess past 80 to a minimum.
* ANSI C prototypes
* Uncuddled elses and "K&R" style for indenting control constructs
* No C++ style (//) comments
* Mark places that need to be revisited with XXX (and revisit often!)
* Opening brace lines up with "if" when conditional spans multiple lines; should be at end-of-line otherwise
* In function definitions, name starts in column 0 (return value-type is on previous line)
* Single space after keywords that are followed by parens, no space between function name and following paren
* Avoid assignments in conditionals, but if they're unavoidable, use extra paren, e.g. "if (a && (b = c)) ..."
* "return foo;" rather than "return(foo);"
* "if (!foo) ..." rather than "if (foo == FALSE) ..." etc.
* Do not declare variables using "register". It may be counterproductive with modern compilers, and is deprecated in C++, under which the Perl source is regularly compiled.
* In-line functions that are in headers that are accessible to XS code need to be able to compile without warnings with commonly used extra compilation flags, such as gcc's `-Wswitch-default` which warns whenever a switch statement does not have a "default" case. The use of these extra flags is to catch potential problems in legal C code, and is often used by Perl aggregators, such as Linux distributors.
####
Test suite
If your patch changes code (rather than just changing documentation), you should also include one or more test cases which illustrate the bug you're fixing or validate the new functionality you're adding. In general, you should update an existing test file rather than create a new one.
Your test suite additions should generally follow these guidelines (courtesy of Gurusamy Sarathy <[email protected]>):
* Know what you're testing. Read the docs, and the source.
* Tend to fail, not succeed.
* Interpret results strictly.
* Use unrelated features (this will flush out bizarre interactions).
* Use non-standard idioms (otherwise you are not testing TIMTOWTDI).
* Avoid using hardcoded test numbers whenever possible (the EXPECTED/GOT found in t/op/tie.t is much more maintainable, and gives better failure reports).
* Give meaningful error messages when a test fails.
* Avoid using qx// and system() unless you are testing for them. If you do use them, make sure that you cover \_all\_ perl platforms.
* Unlink any temporary files you create.
* Promote unforeseen warnings to errors with $SIG{\_\_WARN\_\_}.
* Be sure to use the libraries and modules shipped with the version being tested, not those that were already installed.
* Add comments to the code explaining what you are testing for.
* Make updating the '1..42' string unnecessary. Or make sure that you update it.
* Test \_all\_ behaviors of a given operator, library, or function.
Test all optional arguments.
Test return values in various contexts (boolean, scalar, list, lvalue).
Use both global and lexical variables.
Don't forget the exceptional, pathological cases.
###
Patching a core module
This works just like patching anything else, with one extra consideration.
Modules in the *cpan/* directory of the source tree are maintained outside of the Perl core. When the author updates the module, the updates are simply copied into the core. See that module's documentation or its listing on <https://metacpan.org/> for more information on reporting bugs and submitting patches.
In most cases, patches to modules in *cpan/* should be sent upstream and should not be applied to the Perl core individually. If a patch to a file in *cpan/* absolutely cannot wait for the fix to be made upstream, released to CPAN and copied to blead, you must add (or update) a `CUSTOMIZED` entry in the *Porting/Maintainers.pl* file to flag that a local modification has been made. See *Porting/Maintainers.pl* for more details.
In contrast, modules in the *dist/* directory are maintained in the core.
###
Updating perldelta
For changes significant enough to warrant a *pod/perldelta.pod* entry, the porters will greatly appreciate it if you submit a delta entry along with your actual change. Significant changes include, but are not limited to:
* Adding, deprecating, or removing core features
* Adding, deprecating, removing, or upgrading core or dual-life modules
* Adding new core tests
* Fixing security issues and user-visible bugs in the core
* Changes that might break existing code, either on the perl or C level
* Significant performance improvements
* Adding, removing, or significantly changing documentation in the *pod/* directory
* Important platform-specific changes
Please make sure you add the perldelta entry to the right section within *pod/perldelta.pod*. More information on how to write good perldelta entries is available in the `Style` section of *Porting/how\_to\_write\_a\_perldelta.pod*.
###
What makes for a good patch?
New features and extensions to the language can be contentious. There is no specific set of criteria which determine what features get added, but here are some questions to consider when developing a patch:
####
Does the concept match the general goals of Perl?
Our goals include, but are not limited to:
1. Keep it fast, simple, and useful.
2. Keep features/concepts as orthogonal as possible.
3. No arbitrary limits (platforms, data sizes, cultures).
4. Keep it open and exciting to use/patch/advocate Perl everywhere.
5. Either assimilate new technologies, or build bridges to them.
####
Where is the implementation?
All the talk in the world is useless without an implementation. In almost every case, the person or people who argue for a new feature will be expected to be the ones who implement it. Porters capable of coding new features have their own agendas, and are not available to implement your (possibly good) idea.
####
Backwards compatibility
It's a cardinal sin to break existing Perl programs. New warnings can be contentious--some say that a program that emits warnings is not broken, while others say it is. Adding keywords has the potential to break programs, changing the meaning of existing token sequences or functions might break programs.
The Perl 5 core includes mechanisms to help porters make backwards incompatible changes more compatible such as the <feature> and <deprecate> modules. Please use them when appropriate.
####
Could it be a module instead?
Perl 5 has extension mechanisms, modules and XS, specifically to avoid the need to keep changing the Perl interpreter. You can write modules that export functions, you can give those functions prototypes so they can be called like built-in functions, you can even write XS code to mess with the runtime data structures of the Perl interpreter if you want to implement really complicated things.
Whenever possible, new features should be prototyped in a CPAN module before they will be considered for the core.
####
Is the feature generic enough?
Is this something that only the submitter wants added to the language, or is it broadly useful? Sometimes, instead of adding a feature with a tight focus, the porters might decide to wait until someone implements the more generalized feature.
####
Does it potentially introduce new bugs?
Radical rewrites of large chunks of the Perl interpreter have the potential to introduce new bugs.
####
How big is it?
The smaller and more localized the change, the better. Similarly, a series of small patches is greatly preferred over a single large patch.
####
Does it preclude other desirable features?
A patch is likely to be rejected if it closes off future avenues of development. For instance, a patch that placed a true and final interpretation on prototypes is likely to be rejected because there are still options for the future of prototypes that haven't been addressed.
####
Is the implementation robust?
Good patches (tight code, complete, correct) stand more chance of going in. Sloppy or incorrect patches might be placed on the back burner until fixes can be made, or they might be discarded altogether without further notice.
####
Is the implementation generic enough to be portable?
The worst patches make use of system-specific features. It's highly unlikely that non-portable additions to the Perl language will be accepted.
####
Is the implementation tested?
Patches which change behaviour (fixing bugs or introducing new features) must include regression tests to verify that everything works as expected.
Without tests provided by the original author, how can anyone else changing perl in the future be sure that they haven't unwittingly broken the behaviour the patch implements? And without tests, how can the patch's author be confident that his/her hard work put into the patch won't be accidentally thrown away by someone in the future?
####
Is there enough documentation?
Patches without documentation are probably ill-thought out or incomplete. No features can be added or changed without documentation, so submitting a patch for the appropriate pod docs as well as the source code is important.
####
Is there another way to do it?
Larry said "Although the Perl Slogan is *There's More Than One Way to Do It*, I hesitate to make 10 ways to do something". This is a tricky heuristic to navigate, though--one man's essential addition is another man's pointless cruft.
####
Does it create too much work?
Work for the committers, work for Perl programmers, work for module authors, ... Perl is supposed to be easy.
####
Patches speak louder than words
Working code is always preferred to pie-in-the-sky ideas. A patch to add a feature stands a much higher chance of making it to the language than does a random feature request, no matter how fervently argued the request might be. This ties into "Will it be useful?", as the fact that someone took the time to make the patch demonstrates a strong desire for the feature.
TESTING
-------
The core uses the same testing style as the rest of Perl, a simple "ok/not ok" run through Test::Harness, but there are a few special considerations.
There are three ways to write a test in the core: <Test::More>, *t/test.pl* and ad hoc `print $test ? "ok 42\n" : "not ok 42\n"`. The decision of which to use depends on what part of the test suite you're working on. This is a measure to prevent a high-level failure (such as Config.pm breaking) from causing basic functionality tests to fail.
The *t/test.pl* library provides some of the features of <Test::More>, but avoids loading most modules and uses as few core features as possible.
If you write your own test, use the [Test Anything Protocol](https://testanything.org).
* *t/base*, *t/comp* and *t/opbasic*
Since we don't know if `require` works, or even subroutines, use ad hoc tests for these three. Step carefully to avoid using the feature being tested. Tests in *t/opbasic*, for instance, have been placed there rather than in *t/op* because they test functionality which *t/test.pl* presumes has already been demonstrated to work.
* All other subdirectories of *t/*
Now that basic require() and subroutines are tested, you can use the *t/test.pl* library.
You can also use certain libraries like [Config](config) conditionally, but be sure to skip the test gracefully if it's not there.
* Test files not found under *t/*
This category includes *.t* files underneath directories such as *dist*, *ext* and *lib*. Since the core of Perl has now been tested, <Test::More> can and now should be used. You can also use the full suite of core modules in the tests. (As noted in ["Patching a core module"](#Patching-a-core-module) above, changes to *.t* files found under *cpan/* should be submitted to the upstream maintainers of those modules.)
When you say "make test", Perl uses the *t/TEST* program to run the test suite (except under Win32 where it uses *t/harness* instead). All tests are run from the *t/* directory, **not** the directory which contains the test. This causes some problems with the tests in *lib/*, so here's some opportunity for some patching.
You must be triply conscious of cross-platform concerns. This usually boils down to using <File::Spec>, avoiding things like `fork()` and `system()` unless absolutely necessary, and not assuming that a given character has a particular ordinal value (code point) or that its UTF-8 representation is composed of particular bytes.
There are several functions available to specify characters and code points portably in tests. The always-preloaded functions `utf8::unicode_to_native()` and its inverse `utf8::native_to_unicode()` take code points and translate appropriately. The file *t/charset\_tools.pl* has several functions that can be useful. It has versions of the previous two functions that take strings as inputs -- not single numeric code points: `uni_to_native()` and `native_to_uni()`. If you must look at the individual bytes comprising a UTF-8 encoded string, `byte_utf8a_to_utf8n()` takes as input a string of those bytes encoded for an ASCII platform, and returns the equivalent string in the native platform. For example, `byte_utf8a_to_utf8n("\xC2\xA0")` returns the byte sequence on the current platform that form the UTF-8 for `U+00A0`, since `"\xC2\xA0"` are the UTF-8 bytes on an ASCII platform for that code point. This function returns `"\xC2\xA0"` on an ASCII platform, and `"\x80\x41"` on an EBCDIC 1047 one.
But easiest is, if the character is specifiable as a literal, like `"A"` or `"%"`, to use that; if not so specificable, you can use `\N{}` , if the side effects aren't troublesome. Simply specify all your characters in hex, using `\N{U+ZZ}` instead of `\xZZ`. `\N{}` is the Unicode name, and so it always gives you the Unicode character. `\N{U+41}` is the character whose Unicode code point is `0x41`, hence is `'A'` on all platforms. The side effects are:
* These select Unicode rules. That means that in double-quotish strings, the string is always converted to UTF-8 to force a Unicode interpretation (you can `utf8::downgrade()` afterwards to convert back to non-UTF8, if possible). In regular expression patterns, the conversion isn't done, but if the character set modifier would otherwise be `/d`, it is changed to `/u`.
* If you use the form `\N{*character name*}`, the <charnames> module gets automatically loaded. This may not be suitable for the test level you are doing.
If you are testing locales (see <perllocale>), there are helper functions in *t/loc\_tools.pl* to enable you to see what locales there are on the current platform.
###
Special `make test` targets
There are various special make targets that can be used to test Perl slightly differently than the standard "test" target. Not all them are expected to give a 100% success rate. Many of them have several aliases, and many of them are not available on certain operating systems.
* test\_porting
This runs some basic sanity tests on the source tree and helps catch basic errors before you submit a patch.
* minitest
Run *miniperl* on *t/base*, *t/comp*, *t/cmd*, *t/run*, *t/io*, *t/op*, *t/uni* and *t/mro* tests.
*miniperl* is a minimalistic perl built to bootstrap building extensions, utilties, documentation etc. It doesn't support dynamic loading and depending on the point in the build process will only have access to a limited set of core modules. *miniperl* is not intended for day to day use.
* test.valgrind check.valgrind
(Only in Linux) Run all the tests using the memory leak + naughty memory access tool "valgrind". The log files will be named *testname.valgrind*.
* test\_harness
Run the test suite with the *t/harness* controlling program, instead of *t/TEST*. *t/harness* is more sophisticated, and uses the <Test::Harness> module, thus using this test target supposes that perl mostly works. The main advantage for our purposes is that it prints a detailed summary of failed tests at the end. Also, unlike *t/TEST*, it doesn't redirect stderr to stdout.
Note that under Win32 *t/harness* is always used instead of *t/TEST*, so there is no special "test\_harness" target.
Under Win32's "test" target you may use the TEST\_SWITCHES and TEST\_FILES environment variables to control the behaviour of *t/harness*. This means you can say
```
nmake test TEST_FILES="op/*.t"
nmake test TEST_SWITCHES="-torture" TEST_FILES="op/*.t"
```
* test-notty test\_notty
Sets PERL\_SKIP\_TTY\_TEST to true before running normal test.
###
Parallel tests
The core distribution can now run its regression tests in parallel on Unix-like and Windows platforms. On Unix, instead of running `make test`, set `TEST_JOBS` in your environment to the number of tests to run in parallel, and run `make test_harness`. On a Bourne-like shell, this can be done as
```
TEST_JOBS=3 make test_harness # Run 3 tests in parallel
```
An environment variable is used, rather than parallel make itself, because <TAP::Harness> needs to be able to schedule individual non-conflicting test scripts itself, and there is no standard interface to `make` utilities to interact with their job schedulers.
Tests are normally run in a logical order, with the sanity tests first, then the main tests of the Perl core functionality, then the tests for the non-core modules. On many-core systems, this may not use the hardware as effectively as possible. By also specifying
```
TEST_JOBS=19 PERL_TEST_HARNESS_ASAP=1 make -j19 test_harness
```
you signal that you want the tests to finish in wall-clock time as short as possible. After the sanity tests are completed, this causes the remaining ones to be packed into the available cores as tightly as we know how. This has its greatest effect on slower, many-core systems. Throughput was sped up by 20% on an outmoded 24-core system; less on more recent faster ones with fewer cores.
Note that the command line above added a `-j` parameter to make, so as to cause parallel compilation. This may or may not work on your platform.
###
Running tests by hand
You can run part of the test suite by hand by using one of the following commands from the *t/* directory:
```
./perl -I../lib TEST list-of-.t-files
```
or
```
./perl -I../lib harness list-of-.t-files
```
(If you don't specify test scripts, the whole test suite will be run.)
###
Using *t/harness* for testing
If you use `harness` for testing, you have several command line options available to you. The arguments are as follows, and are in the order that they must appear if used together.
```
harness -v -torture -re=pattern LIST OF FILES TO TEST
harness -v -torture -re LIST OF PATTERNS TO MATCH
```
If `LIST OF FILES TO TEST` is omitted, the file list is obtained from the manifest. The file list may include shell wildcards which will be expanded out.
* -v
Run the tests under verbose mode so you can see what tests were run, and debug output.
* -torture
Run the torture tests as well as the normal set.
* -re=PATTERN
Filter the file list so that all the test files run match PATTERN. Note that this form is distinct from the **-re LIST OF PATTERNS** form below in that it allows the file list to be provided as well.
* -re LIST OF PATTERNS
Filter the file list so that all the test files run match /(LIST|OF|PATTERNS)/. Note that with this form the patterns are joined by '|' and you cannot supply a list of files, instead the test files are obtained from the MANIFEST.
You can run an individual test by a command similar to
```
./perl -I../lib path/to/foo.t
```
except that the harnesses set up some environment variables that may affect the execution of the test:
* PERL\_CORE=1
indicates that we're running this test as part of the perl core test suite. This is useful for modules that have a dual life on CPAN.
* PERL\_DESTRUCT\_LEVEL=2
is set to 2 if it isn't set already (see ["PERL\_DESTRUCT\_LEVEL" in perlhacktips](perlhacktips#PERL_DESTRUCT_LEVEL)).
* PERL
(used only by *t/TEST*) if set, overrides the path to the perl executable that should be used to run the tests (the default being *./perl*).
* PERL\_SKIP\_TTY\_TEST
if set, tells to skip the tests that need a terminal. It's actually set automatically by the Makefile, but can also be forced artificially by running 'make test\_notty'.
####
Other environment variables that may influence tests
* PERL\_TEST\_Net\_Ping
Setting this variable runs all the Net::Ping modules tests, otherwise some tests that interact with the outside world are skipped. See [perl58delta](https://perldoc.perl.org/5.36.0/perl58delta).
* PERL\_TEST\_NOVREXX
Setting this variable skips the vrexx.t tests for OS2::REXX.
* PERL\_TEST\_NUMCONVERTS
This sets a variable in op/numconvert.t.
* PERL\_TEST\_MEMORY
Setting this variable includes the tests in *t/bigmem/*. This should be set to the number of gigabytes of memory available for testing, eg. `PERL_TEST_MEMORY=4` indicates that tests that require 4GiB of available memory can be run safely.
See also the documentation for the Test and Test::Harness modules, for more environment variables that affect testing.
###
Performance testing
The file *t/perf/benchmarks* contains snippets of perl code which are intended to be benchmarked across a range of perls by the *Porting/bench.pl* tool. If you fix or enhance a performance issue, you may want to add a representative code sample to the file, then run *bench.pl* against the previous and current perls to see what difference it has made, and whether anything else has slowed down as a consequence.
The file *t/perf/opcount.t* is designed to test whether a particular code snippet has been compiled into an optree containing specified numbers of particular op types. This is good for testing whether optimisations which alter ops, such as converting an `aelem` op into an `aelemfast` op, are really doing that.
The files *t/perf/speed.t* and *t/re/speed.t* are designed to test things that run thousands of times slower if a particular optimisation is broken (for example, the utf8 length cache on long utf8 strings). Add a test that will take a fraction of a second normally, and minutes otherwise, causing the test file to time out on failure.
###
Building perl at older commits
In the course of hacking on the Perl core distribution, you may have occasion to configure, build and test perl at an old commit. Sometimes `make` will fail during this process. If that happens, you may be able to salvage the situation by using the Devel::PatchPerl library from CPAN (not included in the core) to bring the source code at that commit to a buildable state.
Here's a real world example, taken from work done to resolve [perl #10118](https://github.com/Perl/perl5/issues/10118). Use of *Porting/bisect.pl* had identified commit `ba77e4cc9d1ceebf472c9c5c18b2377ee47062e6` as the commit in which a bug was corrected. To confirm, a P5P developer wanted to configure and build perl at commit `ba77e4c^` (presumably "bad") and then at `ba77e4c` (presumably "good"). Normal configuration and build was attempted:
```
$ sh ./Configure -des -Dusedevel
$ make test_prep
```
`make`, however, failed with output (excerpted) like this:
```
cc -fstack-protector -L/usr/local/lib -o miniperl \
gv.o toke.o perly.o pad.o regcomp.o dump.o util.o \
mg.o reentr.o mro.o hv.o av.o run.o pp_hot.o sv.o \
pp.o scope.o pp_ctl.o pp_sys.o doop.o doio.o regexec.o \
utf8.o taint.o deb.o universal.o globals.o perlio.o \
numeric.o mathoms.o locale.o pp_pack.o pp_sort.o \
miniperlmain.o opmini.o perlmini.o
pp.o: In function `Perl_pp_pow':
pp.c:(.text+0x2db9): undefined reference to `pow'
...
collect2: error: ld returned 1 exit status
makefile:348: recipe for target 'miniperl' failed
make: *** [miniperl] Error 1
```
Another P5P contributor recommended installation and use of Devel::PatchPerl for this situation, first to determine the version of perl at the commit in question, then to patch the source code at that point to facilitate a build.
```
$ perl -MDevel::PatchPerl -e \
'print Devel::PatchPerl->determine_version("/path/to/sourcecode"),
"\n";'
5.11.1
$ perl -MDevel::PatchPerl -e \
'Devel::PatchPerl->patch_source("5.11.1", "/path/to/sourcecode");'
```
Once the source was patched, `./Configure` and `make test_prep` were called and completed successfully, enabling confirmation of the findings in RT #72414.
MORE READING FOR GUTS HACKERS
------------------------------
To hack on the Perl guts, you'll need to read the following things:
* <perlsource>
An overview of the Perl source tree. This will help you find the files you're looking for.
* <perlinterp>
An overview of the Perl interpreter source code and some details on how Perl does what it does.
* <perlhacktut>
This document walks through the creation of a small patch to Perl's C code. If you're just getting started with Perl core hacking, this will help you understand how it works.
* <perlhacktips>
More details on hacking the Perl core. This document focuses on lower level details such as how to write tests, compilation issues, portability, debugging, etc.
If you plan on doing serious C hacking, make sure to read this.
* <perlguts>
This is of paramount importance, since it's the documentation of what goes where in the Perl source. Read it over a couple of times and it might start to make sense - don't worry if it doesn't yet, because the best way to study it is to read it in conjunction with poking at Perl source, and we'll do that later on.
Gisle Aas's "illustrated perlguts", also known as *illguts*, has very helpful pictures:
<https://metacpan.org/release/RURBAN/illguts-0.49>
* <perlxstut> and <perlxs>
A working knowledge of XSUB programming is incredibly useful for core hacking; XSUBs use techniques drawn from the PP code, the portion of the guts that actually executes a Perl program. It's a lot gentler to learn those techniques from simple examples and explanation than from the core itself.
* <perlapi>
The documentation for the Perl API explains what some of the internal functions do, as well as the many macros used in the source.
* *Porting/pumpkin.pod*
This is a collection of words of wisdom for a Perl porter; some of it is only useful to the pumpkin holders, but most of it applies to anyone wanting to go about Perl development.
CPAN TESTERS AND PERL SMOKERS
------------------------------
The CPAN testers ( <http://cpantesters.org/> ) are a group of volunteers who test CPAN modules on a variety of platforms.
Perl Smokers ( <https://www.nntp.perl.org/group/perl.daily-build/> and <https://www.nntp.perl.org/group/perl.daily-build.reports/> ) automatically test Perl source releases on platforms with various configurations.
Both efforts welcome volunteers. In order to get involved in smoke testing of the perl itself visit <https://metacpan.org/release/Test-Smoke>. In order to start smoke testing CPAN modules visit <https://metacpan.org/release/CPANPLUS-YACSmoke> or <https://metacpan.org/release/minismokebox> or <https://metacpan.org/release/CPAN-Reporter>.
WHAT NEXT?
-----------
If you've read all the documentation in the document and the ones listed above, you're more than ready to hack on Perl.
Here's some more recommendations
* Subscribe to perl5-porters, follow the patches and try and understand them; don't be afraid to ask if there's a portion you're not clear on - who knows, you may unearth a bug in the patch...
* Do read the README associated with your operating system, e.g. README.aix on the IBM AIX OS. Don't hesitate to supply patches to that README if you find anything missing or changed over a new OS release.
* Find an area of Perl that seems interesting to you, and see if you can work out how it works. Scan through the source, and step over it in the debugger. Play, poke, investigate, fiddle! You'll probably get to understand not just your chosen area but a much wider range of *perl*'s activity as well, and probably sooner than you'd think.
###
"The Road goes ever on and on, down from the door where it began."
If you can do these things, you've started on the long road to Perl porting. Thanks for wanting to help make Perl better - and happy hacking!
###
Metaphoric Quotations
If you recognized the quote about the Road above, you're in luck.
Most software projects begin each file with a literal description of each file's purpose. Perl instead begins each with a literary allusion to that file's purpose.
Like chapters in many books, all top-level Perl source files (along with a few others here and there) begin with an epigrammatic inscription that alludes, indirectly and metaphorically, to the material you're about to read.
Quotations are taken from writings of J.R.R. Tolkien pertaining to his Legendarium, almost always from *The Lord of the Rings*. Chapters and page numbers are given using the following editions:
* *The Hobbit*, by J.R.R. Tolkien. The hardcover, 70th-anniversary edition of 2007 was used, published in the UK by Harper Collins Publishers and in the US by the Houghton Mifflin Company.
* *The Lord of the Rings*, by J.R.R. Tolkien. The hardcover, 50th-anniversary edition of 2004 was used, published in the UK by Harper Collins Publishers and in the US by the Houghton Mifflin Company.
* *The Lays of Beleriand*, by J.R.R. Tolkien and published posthumously by his son and literary executor, C.J.R. Tolkien, being the 3rd of the 12 volumes in Christopher's mammoth *History of Middle Earth*. Page numbers derive from the hardcover edition, first published in 1983 by George Allen & Unwin; no page numbers changed for the special 3-volume omnibus edition of 2002 or the various trade-paper editions, all again now by Harper Collins or Houghton Mifflin.
Other JRRT books fair game for quotes would thus include *The Adventures of Tom Bombadil*, *The Silmarillion*, *Unfinished Tales*, and *The Tale of the Children of Hurin*, all but the first posthumously assembled by CJRT. But *The Lord of the Rings* itself is perfectly fine and probably best to quote from, provided you can find a suitable quote there.
So if you were to supply a new, complete, top-level source file to add to Perl, you should conform to this peculiar practice by yourself selecting an appropriate quotation from Tolkien, retaining the original spelling and punctuation and using the same format the rest of the quotes are in. Indirect and oblique is just fine; remember, it's a metaphor, so being meta is, after all, what it's for.
AUTHOR
------
This document was originally written by Nathan Torkington, and is maintained by the perl5-porters mailing list.
| programming_docs |
perl VMS::Filespec VMS::Filespec
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [rmsexpand](#rmsexpand)
+ [vmsify](#vmsify)
+ [unixify](#unixify)
+ [pathify](#pathify)
+ [fileify](#fileify)
+ [vmspath](#vmspath)
+ [unixpath](#unixpath)
+ [candelete](#candelete)
+ [case\_tolerant\_process](#case_tolerant_process)
+ [unixrealpath](#unixrealpath)
+ [vmsrealpath](#vmsrealpath)
* [REVISION](#REVISION)
NAME
----
VMS::Filespec - convert between VMS and Unix file specification syntax
SYNOPSIS
--------
```
use VMS::Filespec;
$fullspec = rmsexpand('[.VMS]file.specification'[, 'default:[file.spec]']);
$vmsspec = vmsify('/my/Unix/file/specification');
$unixspec = unixify('my:[VMS]file.specification');
$path = pathify('my:[VMS.or.Unix.directory]specification.dir');
$dirfile = fileify('my:[VMS.or.Unix.directory.specification]');
$vmsdir = vmspath('my/VMS/or/Unix/directory/specification.dir');
$unixdir = unixpath('my:[VMS.or.Unix.directory]specification.dir');
candelete('my:[VMS.or.Unix]file.specification');
$case_tolerant = case_tolerant_process;
$unixspec = unixrealpath('file_specification');
$vmsspec = vmsrealpath('file_specification');
```
DESCRIPTION
-----------
This package provides routines to simplify conversion between VMS and Unix syntax when processing file specifications. This is useful when porting scripts designed to run under either OS, and also allows you to take advantage of conveniences provided by either syntax (*e.g.* ability to easily concatenate Unix-style specifications). In addition, it provides an additional file test routine, `candelete`, which determines whether you have delete access to a file.
If you're running under VMS, the routines in this package are special, in that they're automatically made available to any Perl script, whether you're running *miniperl* or the full *perl*. The `use VMS::Filespec` or `require VMS::Filespec; import VMS::Filespec ...` statement can be used to import the function names into the current package, but they're always available if you use the fully qualified name, whether or not you've mentioned the *.pm* file in your script. If you're running under another OS and have installed this package, it behaves like a normal Perl extension (in fact, you're using Perl substitutes to emulate the necessary VMS system calls).
Each of these routines accepts a file specification in either VMS or Unix syntax, and returns the converted file specification, or `undef` if an error occurs. The conversions are, for the most part, simply string manipulations; the routines do not check the details of syntax (e.g. that only legal characters are used). There is one exception: when running under VMS, conversions from VMS syntax use the $PARSE service to expand specifications, so illegal syntax, or a relative directory specification which extends above the tope of the current directory path (e.g [---.foo] when in dev:[dir.sub]) will cause errors. In general, any legal file specification will be converted properly, but garbage input tends to produce garbage output.
Each of these routines is prototyped as taking a single scalar argument, so you can use them as unary operators in complex expressions (as long as you don't use the `&` form of subroutine call, which bypasses prototype checking).
The routines provided are:
### rmsexpand
Uses the RMS $PARSE and $SEARCH services to expand the input specification to its fully qualified form, except that a null type or version is not added unless it was present in either the original file specification or the default specification passed to `rmsexpand`. (If the file does not exist, the input specification is expanded as much as possible.) If an error occurs, returns `undef` and sets `$!` and `$^E`.
`rmsexpand` on success will produce a name that fits in a 255 byte buffer, which is required for parameters passed to the DCL interpreter.
### vmsify
Converts a file specification to VMS syntax. If the file specification cannot be converted to or is already in VMS syntax, it will be passed through unchanged.
The file specifications of `.` and `..` will be converted to `[]` and `[-]`.
If the file specification is already in a valid VMS syntax, it will be passed through unchanged, except that the UTF-8 flag will be cleared since VMS format file specifications are never in UTF-8.
When Perl is running on an OpenVMS system, if the `DECC$EFS_CHARSET` feature is not enabled, extra dots in the file specification will be converted to underscore characters, and the `?` character will be converted to a `%` character, if a conversion is done.
When Perl is running on an OpenVMS system, if the `DECC$EFS_CHARSET` feature is enabled, this implies that the Unix pathname cannot have a version, and that a path consisting of three dots, `./.../`, will be converted to `[.^.^.^.]`.
Unix style shell macros like `$(abcd)` are passed through instead of being converted to `$^(abcd^)` independent of the `DECC$EFS_CHARSET` feature setting. Unix style shell macros should not use characters that are not in the ASCII character set, as the resulting specification may or may not be still in UTF8 format.
The feature logical name `PERL_VMS_VTF7_FILENAMES` controls if UNICODE characters in Unix filenames are encoded in VTF-7 notation in the resulting OpenVMS file specification. [Currently under development]
`unixify` on the resulting file specification may not result in the original Unix file specification, so programs should not plan to convert a file specification from Unix to VMS and then back to Unix again after modification of the components.
### unixify
Converts a file specification to Unix syntax. If the file specification cannot be converted to or is already in Unix syntax, it will be passed through unchanged.
When Perl is running on an OpenVMS system, the following `DECC$` feature settings will control how the filename is converted:
```
C<decc$disable_to_vms_logname_translation:> default = C<ENABLE>
C<decc$disable_posix_root:> default = C<ENABLE>
C<decc$efs_charset:> default = C<DISABLE>
C<decc$filename_unix_no_version:> default = C<DISABLE>
C<decc$readdir_dropdotnotype:> default = C<ENABLE>
```
When Perl is being run under a Unix shell on OpenVMS, the defaults at a future time may be more appropriate for it.
When Perl is running on an OpenVMS system with `DECC$EFS_CHARSET` enabled, a wild card directory name of `[...]` cannot be translated to a valid Unix file specification. Also, directory file specifications will have their implied ".dir;1" removed, and a trailing `.` character indicating a null extension will be removed.
Note that `DECC$EFS_CHARSET` requires `DECC$FILENAME_UNIX_NO_VERSION` because the conversion routine cannot differentiate whether the last `.` of a Unix specification is delimiting a version, or is just part of a file specification.
`vmsify` on the resulting file specification may not result in the original VMS file specification, so programs should not plan to convert a file specification from VMS to Unix and then back to VMS again after modification.
### pathify
Converts a directory specification to a path - that is, a string you can prepend to a file name to form a valid file specification. If the input file specification uses VMS syntax, the returned path does, too; likewise for Unix syntax (Unix paths are guaranteed to end with '/'). Note that this routine will insist that the input be a legal directory file specification; the file type and version, if specified, must be *.DIR;1*. For compatibility with Unix usage, the type and version may also be omitted.
### fileify
Converts a directory specification to the file specification of the directory file - that is, a string you can pass to functions like `stat` or `rmdir` to manipulate the directory file. If the input directory specification uses VMS syntax, the returned file specification does, too; likewise for Unix syntax. As with `pathify`, the input file specification must have a type and version of *.DIR;1*, or the type and version must be omitted.
### vmspath
Acts like `pathify`, but insures the returned path uses VMS syntax.
### unixpath
Acts like `pathify`, but insures the returned path uses Unix syntax.
### candelete
Determines whether you have delete access to a file. If you do, `candelete` returns true. If you don't, or its argument isn't a legal file specification, `candelete` returns FALSE. Unlike other file tests, the argument to `candelete` must be a file name (not a FileHandle), and, since it's an XSUB, it's a list operator, so you need to be careful about parentheses. Both of these restrictions may be removed in the future if the functionality of `candelete` becomes part of the Perl core.
### case\_tolerant\_process
This reports whether the VMS process has been set to a case tolerant state, and returns true when the process is in the traditional case tolerant mode and false when case sensitivity has been enabled for the process. It is intended for use by the File::Spec::VMS->case\_tolerant method only, and it is recommended that you only use File::Spec->case\_tolerant.
### unixrealpath
This exposes the VMS C library `realpath` function where available. It will always return a Unix format specification.
If the `realpath` function is not available, or is unable to return the real path of the file, `unixrealpath` will use the same internal procedure as the `vmsrealpath` function and convert the output to a Unix format specification. It is not available on non-VMS systems.
### vmsrealpath
This uses the `LIB$FID_TO_NAME` run-time library call to find the name of the primary link to a file, and returns the filename in VMS format. This function is not available on non-VMS systems.
REVISION
--------
This document was last revised 8-DEC-2007, for Perl 5.10.0
perl CPAN::Meta::History::Meta_1_3 CPAN::Meta::History::Meta\_1\_3
===============================
CONTENTS
--------
* [NAME](#NAME)
* [PREFACE](#PREFACE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FORMAT](#FORMAT)
* [TERMINOLOGY](#TERMINOLOGY)
* [HEADER](#HEADER)
* [FIELDS](#FIELDS)
+ [meta-spec](#meta-spec)
+ [name](#name)
+ [version](#version)
+ [abstract](#abstract)
+ [author](#author)
+ [license](#license)
+ [distribution\_type](#distribution_type)
+ [requires](#requires)
+ [recommends](#recommends)
+ [build\_requires](#build_requires)
+ [conflicts](#conflicts)
+ [dynamic\_config](#dynamic_config)
+ [private](#private)
+ [provides](#provides)
+ [no\_index](#no_index)
- [file](#file)
- [directory](#directory)
- [package](#package)
- [namespace](#namespace)
+ [keywords](#keywords)
+ [resources](#resources)
+ [generated\_by](#generated_by)
* [VERSION SPECIFICATIONS](#VERSION-SPECIFICATIONS)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
CPAN::Meta::History::Meta\_1\_3 - Version 1.3 metadata specification for META.yml
PREFACE
-------
This is a historical copy of the version 1.3 specification for *META.yml* files, copyright by Ken Williams and licensed under the same terms as Perl itself.
Modifications from the original:
* Various spelling corrections
* Include list of valid licenses from <Module::Build> 0.2805 rather than linking to the module, with minor updates to text and links to reflect versions at the time of publication.
* Fixed some dead links to point to active resources.
SYNOPSIS
--------
```
--- #YAML:1.0
name: Module-Build
abstract: Build and install Perl modules
version: 0.20
author:
- Ken Williams <[email protected]>
license: perl
distribution_type: module
requires:
Config: 0
Cwd: 0
Data::Dumper: 0
ExtUtils::Install: 0
File::Basename: 0
File::Compare: 0
File::Copy: 0
File::Find: 0
File::Path: 0
File::Spec: 0
IO::File: 0
perl: 5.005_03
recommends:
Archive::Tar: 1.00
ExtUtils::Install: 0.3
ExtUtils::ParseXS: 2.02
Pod::Text: 0
YAML: 0.35
build_requires:
Test: 0
urls:
license: http://dev.perl.org/licenses/
meta-spec:
version: 1.3
url: http://module-build.sourceforge.net/META-spec-v1.3.html
generated_by: Module::Build version 0.20
```
DESCRIPTION
-----------
This document describes version 1.3 of the *META.yml* specification.
The *META.yml* file describes important properties of contributed Perl distributions such as the ones found on CPAN. It is typically created by tools like Module::Build, Module::Install, and ExtUtils::MakeMaker.
The fields in the *META.yml* file are meant to be helpful for people maintaining module collections (like CPAN), for people writing installation tools (like CPAN.pm or CPANPLUS), or just for people who want to know some stuff about a distribution before downloading it and starting to install it.
*Note: The latest stable version of this specification can always be found at <http://module-build.sourceforge.net/META-spec-current.html>, and the latest development version (which may include things that won't make it into the stable version) can always be found at <http://module-build.sourceforge.net/META-spec-blead.html>.*
FORMAT
------
*META.yml* files are written in the YAML format (see <http://www.yaml.org/>).
See the following links to learn why we chose YAML instead of, say, XML or Data::Dumper:
* [Module::Build design plans](http://www.nntp.perl.org/group/perl.makemaker/2002/04/msg407.html)
* [Not keen on YAML](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1353.html)
* [META Concerns](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1385.html)
TERMINOLOGY
-----------
distribution This is the primary object described by the *META.yml* specification. In the context of this document it usually refers to a collection of modules, scripts, and/or documents that are distributed together for other developers to use. Examples of distributions are `Class-Container`, `libwww-perl`, or `DBI`.
module This refers to a reusable library of code typically contained in a single file. Currently, we primarily talk of perl modules, but this specification should be open enough to apply to other languages as well (ex. python, ruby). Examples of modules are `Class::Container`, `LWP::Simple`, or `DBD::File`.
HEADER
------
The first line of a *META.yml* file should be a valid YAML document header like `"--- #YAML:1.0"`.
FIELDS
------
The rest of the *META.yml* file is one big YAML mapping whose keys are described here.
###
meta-spec
Example:
```
meta-spec:
version: 1.3
url: http://module-build.sourceforge.net/META-spec-v1.3.html
```
(Spec 1.1) [required] {URL} This field indicates the location of the version of the META.yml specification used.
### name
Example:
```
name: Module-Build
```
(Spec 1.0) [required] {string} The name of the distribution which is often created by taking the "main module" in the distribution and changing "::" to "-". Sometimes it's completely different, however, as in the case of the libwww-perl distribution (see <http://search.cpan.org/dist/libwww-perl/>).
### version
Example:
```
version: 0.20
```
(Spec 1.0) [required] {version} The version of the distribution to which the *META.yml* file refers.
### abstract
Example:
```
abstract: Build and install Perl modules.
```
(Spec 1.1) [required] {string} A short description of the purpose of the distribution.
### author
Example:
```
author:
- Ken Williams <[email protected]>
```
(Spec 1.1) [required] {list of strings} A YAML sequence indicating the author(s) of the distribution. The preferred form is author-name <email-address>.
### license
Example:
```
license: perl
```
(Spec 1.0) [required] {string} The license under which this distribution may be used and redistributed.
Must be one of the following licenses:
apache The distribution is licensed under the Apache Software License version 1.1 (<http://opensource.org/licenses/Apache-1.1>).
artistic The distribution is licensed under the Artistic License version 1, as specified by the Artistic file in the standard perl distribution (<http://opensource.org/licenses/Artistic-Perl-1.0>).
bsd The distribution is licensed under the BSD 3-Clause License (<http://opensource.org/licenses/BSD-3-Clause>).
gpl The distribution is distributed under the terms of the GNU General Public License version 2 (<http://opensource.org/licenses/GPL-2.0>).
lgpl The distribution is distributed under the terms of the GNU Lesser General Public License version 2 (<http://opensource.org/licenses/LGPL-2.1>).
mit The distribution is licensed under the MIT License (<http://opensource.org/licenses/MIT>).
mozilla The distribution is licensed under the Mozilla Public License. (<http://opensource.org/licenses/MPL-1.0> or <http://opensource.org/licenses/MPL-1.1>)
open\_source The distribution is licensed under some other Open Source Initiative-approved license listed at <http://www.opensource.org/licenses/>.
perl The distribution may be copied and redistributed under the same terms as perl itself (this is by far the most common licensing option for modules on CPAN). This is a dual license, in which the user may choose between either the GPL version 1 or the Artistic version 1 license.
restrictive The distribution may not be redistributed without special permission from the author and/or copyright holder.
unrestricted The distribution is licensed under a license that is not approved by [www.opensource.org](http://www.opensource.org/) but that allows distribution without restrictions.
### distribution\_type
Example:
```
distribution_type: module
```
(Spec 1.0) [optional] {string} What kind of stuff is contained in this distribution. Most things on CPAN are `module`s (which can also mean a collection of modules), but some things are `script`s.
Unfortunately this field is basically meaningless, since many distributions are hybrids of several kinds of things, or some new thing, or subjectively different in focus depending on who's using them. Tools like Module::Build and MakeMaker will likely stop generating this field.
### requires
Example:
```
requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules this distribution requires for proper operation. The keys are the module names, and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
### recommends
Example:
```
recommends:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules this distribution recommends for enhanced operation. The keys are the module names, and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
*ALTERNATIVE: It may be desirable to present to the user which features depend on which modules so they can make an informed decision about which recommended modules to install.*
Example:
```
optional_features:
- foo:
description: Provides the ability to blah.
requires:
Data::Dumper: 0
File::Find: 1.03
- bar:
description: This feature is not available on this platform.
excludes_os: MSWin32
```
*(Spec 1.1) [optional] {map} A YAML sequence of names for optional features which are made available when its requirements are met. For each feature a description is provided along with any of ["requires"](#requires), ["build\_requires"](#build_requires), ["conflicts"](#conflicts), `requires_packages`, `requires_os`, and `excludes_os` which have the same meaning in this subcontext as described elsewhere in this document.*
### build\_requires
Example:
```
build_requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules required for building and/or testing of this distribution. The keys are the module names, and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS). These dependencies are not required after the module is installed.
### conflicts
Example:
```
conflicts:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules that cannot be installed while this distribution is installed. This is a pretty uncommon situation. The keys for `conflicts` are the module names, and the values are version specifications as described in ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
### dynamic\_config
Example:
```
dynamic_config: 0
```
(Spec 1.0) [optional] {boolean} A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed when building this distribution, or whether it can be built, tested and installed solely from consulting its metadata file. The main reason to set this to a true value is that your module performs some dynamic configuration (asking questions, sensing the environment, etc.) as part of its build/install process.
Currently Module::Build doesn't actually do anything with this flag - it's probably going to be up to higher-level tools like CPAN to do something useful with it. It can potentially bring lots of security, packaging, and convenience improvements.
If this field is omitted, it defaults to 1 (true).
### private
*(Deprecated)* (Spec 1.0) [optional] {map} This field has been renamed to ["no\_index"](#no_index). See below.
### provides
Example:
```
provides:
Foo::Bar:
file: lib/Foo/Bar.pm
version: 0.27_02
Foo::Bar::Blah:
file: lib/Foo/Bar/Blah.pm
Foo::Bar::Baz:
file: lib/Foo/Bar/Baz.pm
version: 0.3
```
(Spec 1.1) [optional] {map} A YAML mapping that describes all packages provided by this distribution. This information can be (and, in some cases, is) used by distribution and automation mechanisms like PAUSE, CPAN, and search.cpan.org to build indexes saying in which distribution various packages can be found.
When using tools like <Module::Build> that can generate the `provides` mapping for your distribution automatically, make sure you examine what it generates to make sure it makes sense - indexers will usually trust the `provides` field if it's present, rather than scanning through the distribution files themselves to figure out packages and versions. This is a good thing, because it means you can use the `provides` field to tell the indexers precisely what you want indexed about your distribution, rather than relying on them to essentially guess what you want indexed.
### no\_index
Example:
```
no_index:
file:
- My/Module.pm
directory:
- My/Private
package:
- My::Module::Stuff
namespace:
- My::Module::Stuff
```
(Spec 1.1) [optional] {map} A YAML mapping that describes any files, directories, packages, and namespaces that are private (i.e. implementation artifacts) that are not of interest to searching and indexing tools. This is useful when no `provides` field is present.
For example, <http://search.cpan.org/> excludes items listed in `no_index` when searching for POD, meaning files in these directories will not converted to HTML and made public - which is useful if you have example or test PODs that you don't want the search engine to go through.
#### file
(Spec 1.1) [optional] Exclude any listed file(s).
#### directory
(Spec 1.1) [optional] Exclude anything below the listed directory(ies).
[Note: previous editions of the spec had `dir` instead of `directory`, but I think MakeMaker and various users started using `directory`, so in deference we switched to that.]
#### package
(Spec 1.1) [optional] Exclude the listed package(s).
#### namespace
(Spec 1.1) [optional] Excludes anything below the listed namespace(s), but *not* the listed namespace(s) its self.
### keywords
Example:
```
keywords:
- make
- build
- install
```
(Spec 1.1) [optional] {list} A sequence of keywords/phrases that describe this distribution.
### resources
Example:
```
resources:
license: http://dev.perl.org/licenses/
homepage: http://sourceforge.net/projects/module-build
bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=Module-Build
repository: http://sourceforge.net/cvs/?group_id=45731
MailingList: http://lists.sourceforge.net/lists/listinfo/module-build-general
```
(Spec 1.1) [optional] {map} A mapping of any URL resources related to this distribution. All-lower-case keys, such as `homepage`, `license`, and `bugtracker`, are reserved by this specification, as they have "official" meanings defined here in this specification. If you'd like to add your own "special" entries (like the "MailingList" entry above), use at least one upper-case letter.
The current set of official keys is:
homepage The official home of this project on the web.
license An URL for an official statement of this distribution's license.
bugtracker An URL for a bug tracker (e.g. Bugzilla or RT queue) for this project.
### generated\_by
Example:
```
generated_by: Module::Build version 0.20
```
(Spec 1.0) [required] {string} Indicates the tool that was used to create this *META.yml* file. It's good form to include both the name of the tool and its version, but this field is essentially opaque, at least for the moment. If *META.yml* was generated by hand, it is suggested that the author be specified here.
[Note: My *meta\_stats.pl* script which I use to gather statistics regarding *META.yml* usage prefers the form listed above, i.e. it splits on /\s+version\s+/ taking the first field as the name of the tool that generated the file and the second field as version of that tool. RWS]
VERSION SPECIFICATIONS
-----------------------
Some fields require a version specification (ex. ["requires"](#requires), ["recommends"](#recommends), ["build\_requires"](#build_requires), etc.) to indicate the particular version(s) of some other module that may be required as a prerequisite. This section details the version specification formats that are currently supported.
The simplest format for a version specification is just the version number itself, e.g. `2.4`. This means that **at least** version 2.4 must be present. To indicate that **any** version of a prerequisite is okay, even if the prerequisite doesn't define a version at all, use the version `0`.
You may also use the operators < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and != (not equal). For example, the specification `< 2.0` means that any version of the prerequisite less than 2.0 is suitable.
For more complicated situations, version specifications may be AND-ed together using commas. The specification `>= 1.2, != 1.5, < 2.0` indicates a version that must be **at least** 1.2, **less than** 2.0, and **not equal to** 1.5.
SEE ALSO
---------
[CPAN](http://www.cpan.org/)
[CPAN.pm](cpan)
[CPANPLUS](cpanplus)
<Data::Dumper>
<ExtUtils::MakeMaker>
<Module::Build>
<Module::Install>
[XML](http://www.w3.org/XML/)
[YAML](http://www.yaml.org/)
HISTORY
-------
March 14, 2003 (Pi day) * Created version 1.0 of this document.
May 8, 2003 * Added the ["dynamic\_config"](#dynamic_config) field, which was missing from the initial version.
November 13, 2003 * Added more YAML rationale articles.
* Fixed existing link to YAML discussion thread to point to new <http://nntp.x.perl.org/group/> site.
* Added and deprecated the ["private"](#private) field.
* Added ["abstract"](#abstract), `configure`, `requires_packages`, `requires_os`, `excludes_os`, and ["no\_index"](#no_index) fields.
* Bumped version.
November 16, 2003 * Added `generation`, `authored_by` fields.
* Add alternative proposal to the ["recommends"](#recommends) field.
* Add proposal for a `requires_build_tools` field.
December 9, 2003 * Added link to latest version of this specification on CPAN.
* Added section ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
* Chang name from Module::Build::META-spec to CPAN::META::Specification.
* Add proposal for `auto_regenerate` field.
December 15, 2003 * Add `index` field as a compliment to ["no\_index"](#no_index)
* Add ["keywords"](#keywords) field as a means to aid searching distributions.
* Add ["TERMINOLOGY"](#TERMINOLOGY) section to explain certain terms that may be ambiguous.
July 26, 2005 * Removed a bunch of items (generation, requires\_build\_tools, requires\_packages, configure, requires\_os, excludes\_os, auto\_regenerate) that have never actually been supported, but were more like records of brainstorming.
* Changed `authored_by` to ["author"](#author), since that's always been what it's actually called in actual *META.yml* files.
* Added the "==" operator to the list of supported version-checking operators.
* Noted that the ["distribution\_type"](#distribution_type) field is basically meaningless, and shouldn't really be used.
* Clarified ["dynamic\_config"](#dynamic_config) a bit.
August 23, 2005 * Removed the name `CPAN::META::Specification`, since that implies a module that doesn't actually exist.
| programming_docs |
perl perlmod perlmod
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Is this the document you were after?](#Is-this-the-document-you-were-after?)
+ [Packages](#Packages)
+ [Symbol Tables](#Symbol-Tables)
+ [BEGIN, UNITCHECK, CHECK, INIT and END](#BEGIN,-UNITCHECK,-CHECK,-INIT-and-END)
+ [Perl Classes](#Perl-Classes)
+ [Perl Modules](#Perl-Modules)
+ [Making your module threadsafe](#Making-your-module-threadsafe)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlmod - Perl modules (packages and symbol tables)
DESCRIPTION
-----------
###
Is this the document you were after?
There are other documents which might contain the information that you're looking for:
This doc Perl's packages, namespaces, and some info on classes.
<perlnewmod> Tutorial on making a new module.
<perlmodstyle> Best practices for making a new module.
### Packages
Unlike Perl 4, in which all the variables were dynamic and shared one global name space, causing maintainability problems, Perl 5 provides two mechanisms for protecting code from having its variables stomped on by other code: lexically scoped variables created with `my` or `state` and namespaced global variables, which are exposed via the `vars` pragma, or the `our` keyword. Any global variable is considered to be part of a namespace and can be accessed via a "fully qualified form". Conversely, any lexically scoped variable is considered to be part of that lexical-scope, and does not have a "fully qualified form".
In perl namespaces are called "packages" and the `package` declaration tells the compiler which namespace to prefix to `our` variables and unqualified dynamic names. This both protects against accidental stomping and provides an interface for deliberately clobbering global dynamic variables declared and used in other scopes or packages, when that is what you want to do.
The scope of the `package` declaration is from the declaration itself through the end of the enclosing block, `eval`, or file, whichever comes first (the same scope as the my(), our(), state(), and local() operators, and also the effect of the experimental "reference aliasing," which may change), or until the next `package` declaration. Unqualified dynamic identifiers will be in this namespace, except for those few identifiers that, if unqualified, default to the main package instead of the current one as described below. A `package` statement affects only dynamic global symbols, including subroutine names, and variables you've used local() on, but *not* lexical variables created with my(), our() or state().
Typically, a `package` statement is the first declaration in a file included in a program by one of the `do`, `require`, or `use` operators. You can switch into a package in more than one place: `package` has no effect beyond specifying which symbol table the compiler will use for dynamic symbols for the rest of that block or until the next `package` statement. You can refer to variables and filehandles in other packages by prefixing the identifier with the package name and a double colon: `$Package::Variable`. If the package name is null, the `main` package is assumed. That is, `$::sail` is equivalent to `$main::sail`.
The old package delimiter was a single quote, but double colon is now the preferred delimiter, in part because it's more readable to humans, and in part because it's more readable to **emacs** macros. It also makes C++ programmers feel like they know what's going on--as opposed to using the single quote as separator, which was there to make Ada programmers feel like they knew what was going on. Because the old-fashioned syntax is still supported for backwards compatibility, if you try to use a string like `"This is $owner's house"`, you'll be accessing `$owner::s`; that is, the $s variable in package `owner`, which is probably not what you meant. Use braces to disambiguate, as in `"This is ${owner}'s house"`.
Packages may themselves contain package separators, as in `$OUTER::INNER::var`. This implies nothing about the order of name lookups, however. There are no relative packages: all symbols are either local to the current package, or must be fully qualified from the outer package name down. For instance, there is nowhere within package `OUTER` that `$INNER::var` refers to `$OUTER::INNER::var`. `INNER` refers to a totally separate global package. The custom of treating package names as a hierarchy is very strong, but the language in no way enforces it.
Only identifiers starting with letters (or underscore) are stored in a package's symbol table. All other symbols are kept in package `main`, including all punctuation variables, like $\_. In addition, when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are forced to be in package `main`, even when used for other purposes than their built-in ones. If you have a package called `m`, `s`, or `y`, then you can't use the qualified form of an identifier because it would be instead interpreted as a pattern match, a substitution, or a transliteration.
Variables beginning with underscore used to be forced into package main, but we decided it was more useful for package writers to be able to use leading underscore to indicate private variables and method names. However, variables and functions named with a single `_`, such as $\_ and `sub _`, are still forced into the package `main`. See also ["The Syntax of Variable Names" in perlvar](perlvar#The-Syntax-of-Variable-Names).
`eval`ed strings are compiled in the package in which the eval() was compiled. (Assignments to `$SIG{}`, however, assume the signal handler specified is in the `main` package. Qualify the signal handler name if you wish to have a signal handler in a package.) For an example, examine *perldb.pl* in the Perl library. It initially switches to the `DB` package so that the debugger doesn't interfere with variables in the program you are trying to debug. At various points, however, it temporarily switches back to the `main` package to evaluate various expressions in the context of the `main` package (or wherever you came from). See <perldebug>.
The special symbol `__PACKAGE__` contains the current package, but cannot (easily) be used to construct variable names. After `my($foo)` has hidden package variable `$foo`, it can still be accessed, without knowing what package you are in, as `${__PACKAGE__.'::foo'}`.
See <perlsub> for other scoping issues related to my() and local(), and <perlref> regarding closures.
###
Symbol Tables
The symbol table for a package happens to be stored in the hash of that name with two colons appended. The main symbol table's name is thus `%main::`, or `%::` for short. Likewise the symbol table for the nested package mentioned earlier is named `%OUTER::INNER::`.
The value in each entry of the hash is what you are referring to when you use the `*name` typeglob notation.
```
local *main::foo = *main::bar;
```
You can use this to print out all the variables in a package, for instance. The standard but antiquated *dumpvar.pl* library and the CPAN module Devel::Symdump make use of this.
The results of creating new symbol table entries directly or modifying any entries that are not already typeglobs are undefined and subject to change between releases of perl.
Assignment to a typeglob performs an aliasing operation, i.e.,
```
*dick = *richard;
```
causes variables, subroutines, formats, and file and directory handles accessible via the identifier `richard` also to be accessible via the identifier `dick`. If you want to alias only a particular variable or subroutine, assign a reference instead:
```
*dick = \$richard;
```
Which makes $richard and $dick the same variable, but leaves @richard and @dick as separate arrays. Tricky, eh?
There is one subtle difference between the following statements:
```
*foo = *bar;
*foo = \$bar;
```
`*foo = *bar` makes the typeglobs themselves synonymous while `*foo = \$bar` makes the SCALAR portions of two distinct typeglobs refer to the same scalar value. This means that the following code:
```
$bar = 1;
*foo = \$bar; # Make $foo an alias for $bar
{
local $bar = 2; # Restrict changes to block
print $foo; # Prints '1'!
}
```
Would print '1', because `$foo` holds a reference to the *original* `$bar`. The one that was stuffed away by `local()` and which will be restored when the block ends. Because variables are accessed through the typeglob, you can use `*foo = *bar` to create an alias which can be localized. (But be aware that this means you can't have a separate `@foo` and `@bar`, etc.)
What makes all of this important is that the Exporter module uses glob aliasing as the import/export mechanism. Whether or not you can properly localize a variable that has been exported from a module depends on how it was exported:
```
@EXPORT = qw($FOO); # Usual form, can't be localized
@EXPORT = qw(*FOO); # Can be localized
```
You can work around the first case by using the fully qualified name (`$Package::FOO`) where you need a local value, or by overriding it by saying `*FOO = *Package::FOO` in your script.
The `*x = \$y` mechanism may be used to pass and return cheap references into or from subroutines if you don't want to copy the whole thing. It only works when assigning to dynamic variables, not lexicals.
```
%some_hash = (); # can't be my()
*some_hash = fn( \%another_hash );
sub fn {
local *hashsym = shift;
# now use %hashsym normally, and you
# will affect the caller's %another_hash
my %nhash = (); # do what you want
return \%nhash;
}
```
On return, the reference will overwrite the hash slot in the symbol table specified by the \*some\_hash typeglob. This is a somewhat tricky way of passing around references cheaply when you don't want to have to remember to dereference variables explicitly.
Another use of symbol tables is for making "constant" scalars.
```
*PI = \3.14159265358979;
```
Now you cannot alter `$PI`, which is probably a good thing all in all. This isn't the same as a constant subroutine, which is subject to optimization at compile-time. A constant subroutine is one prototyped to take no arguments and to return a constant expression. See <perlsub> for details on these. The `use constant` pragma is a convenient shorthand for these.
You can say `*foo{PACKAGE}` and `*foo{NAME}` to find out what name and package the \*foo symbol table entry comes from. This may be useful in a subroutine that gets passed typeglobs as arguments:
```
sub identify_typeglob {
my $glob = shift;
print 'You gave me ', *{$glob}{PACKAGE},
'::', *{$glob}{NAME}, "\n";
}
identify_typeglob *foo;
identify_typeglob *bar::baz;
```
This prints
```
You gave me main::foo
You gave me bar::baz
```
The `*foo{THING}` notation can also be used to obtain references to the individual elements of \*foo. See <perlref>.
Subroutine definitions (and declarations, for that matter) need not necessarily be situated in the package whose symbol table they occupy. You can define a subroutine outside its package by explicitly qualifying the name of the subroutine:
```
package main;
sub Some_package::foo { ... } # &foo defined in Some_package
```
This is just a shorthand for a typeglob assignment at compile time:
```
BEGIN { *Some_package::foo = sub { ... } }
```
and is *not* the same as writing:
```
{
package Some_package;
sub foo { ... }
}
```
In the first two versions, the body of the subroutine is lexically in the main package, *not* in Some\_package. So something like this:
```
package main;
$Some_package::name = "fred";
$main::name = "barney";
sub Some_package::foo {
print "in ", __PACKAGE__, ": \$name is '$name'\n";
}
Some_package::foo();
```
prints:
```
in main: $name is 'barney'
```
rather than:
```
in Some_package: $name is 'fred'
```
This also has implications for the use of the SUPER:: qualifier (see <perlobj>).
###
BEGIN, UNITCHECK, CHECK, INIT and END
Five specially named code blocks are executed at the beginning and at the end of a running Perl program. These are the `BEGIN`, `UNITCHECK`, `CHECK`, `INIT`, and `END` blocks.
These code blocks can be prefixed with `sub` to give the appearance of a subroutine (although this is not considered good style). One should note that these code blocks don't really exist as named subroutines (despite their appearance). The thing that gives this away is the fact that you can have **more than one** of these code blocks in a program, and they will get **all** executed at the appropriate moment. So you can't execute any of these code blocks by name.
A `BEGIN` code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed. You may have multiple `BEGIN` blocks within a file (or eval'ed string); they will execute in order of definition. Because a `BEGIN` code block executes immediately, it can pull in definitions of subroutines and such from other files in time to be visible to the rest of the compile and run time. Once a `BEGIN` has run, it is immediately undefined and any code it used is returned to Perl's memory pool.
An `END` code block is executed as late as possible, that is, after perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. (But not if it's morphing into another program via `exec`, or being blown out of the water by a signal--you have to trap that yourself (if you can).) You may have multiple `END` blocks within a file--they will execute in reverse order of definition; that is: last in, first out (LIFO). `END` blocks are not executed when you run perl with the `-c` switch, or if compilation fails.
Note that `END` code blocks are **not** executed at the end of a string `eval()`: if any `END` code blocks are created in a string `eval()`, they will be executed just as any other `END` code block of that package in LIFO order just before the interpreter is being exited.
Inside an `END` code block, `$?` contains the value that the program is going to pass to `exit()`. You can modify `$?` to change the exit value of the program. Beware of changing `$?` by accident (e.g. by running something via `system`).
Inside of a `END` block, the value of `${^GLOBAL_PHASE}` will be `"END"`.
Similar to an `END` block are `defer` blocks, though they operate on the lifetime of individual block scopes, rather than the program as a whole. They are documented in ["defer" in perlsyn](perlsyn#defer).
`UNITCHECK`, `CHECK` and `INIT` code blocks are useful to catch the transition between the compilation phase and the execution phase of the main program.
`UNITCHECK` blocks are run just after the unit which defined them has been compiled. The main program file and each module it loads are compilation units, as are string `eval`s, run-time code compiled using the `(?{ })` construct in a regex, calls to `do FILE`, `require FILE`, and code after the `-e` switch on the command line.
`BEGIN` and `UNITCHECK` blocks are not directly related to the phase of the interpreter. They can be created and executed during any phase.
`CHECK` code blocks are run just after the **initial** Perl compile phase ends and before the run time begins, in LIFO order. `CHECK` code blocks are used in the Perl compiler suite to save the compiled state of the program.
Inside of a `CHECK` block, the value of `${^GLOBAL_PHASE}` will be `"CHECK"`.
`INIT` blocks are run just before the Perl runtime begins execution, in "first in, first out" (FIFO) order.
Inside of an `INIT` block, the value of `${^GLOBAL_PHASE}` will be `"INIT"`.
The `CHECK` and `INIT` blocks in code compiled by `require`, string `do`, or string `eval` will not be executed if they occur after the end of the main compilation phase; that can be a problem in mod\_perl and other persistent environments which use those functions to load code at runtime.
When you use the **-n** and **-p** switches to Perl, `BEGIN` and `END` work just as they do in **awk**, as a degenerate case. Both `BEGIN` and `CHECK` blocks are run when you use the **-c** switch for a compile-only syntax check, although your main code is not.
The **begincheck** program makes it all clear, eventually:
```
#!/usr/bin/perl
# begincheck
print "10. Ordinary code runs at runtime.\n";
END { print "16. So this is the end of the tale.\n" }
INIT { print " 7. INIT blocks run FIFO just before runtime.\n" }
UNITCHECK {
print " 4. And therefore before any CHECK blocks.\n"
}
CHECK { print " 6. So this is the sixth line.\n" }
print "11. It runs in order, of course.\n";
BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
END { print "15. Read perlmod for the rest of the story.\n" }
CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" }
INIT { print " 8. Run this again, using Perl's -c switch.\n" }
print "12. This is anti-obfuscated code.\n";
END { print "14. END blocks run LIFO at quitting time.\n" }
BEGIN { print " 2. So this line comes out second.\n" }
UNITCHECK {
print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n"
}
INIT { print " 9. You'll see the difference right away.\n" }
print "13. It only _looks_ like it should be confusing.\n";
__END__
```
###
Perl Classes
There is no special class syntax in Perl, but a package may act as a class if it provides subroutines to act as methods. Such a package may also derive some of its methods from another class (package) by listing the other package name(s) in its global @ISA array (which must be a package global, not a lexical).
For more on this, see <perlootut> and <perlobj>.
###
Perl Modules
A module is just a set of related functions in a library file, i.e., a Perl package with the same name as the file. It is specifically designed to be reusable by other modules or programs. It may do this by providing a mechanism for exporting some of its symbols into the symbol table of any package using it, or it may function as a class definition and make its semantics available implicitly through method calls on the class and its objects, without explicitly exporting anything. Or it can do a little of both.
For example, to start a traditional, non-OO module called Some::Module, create a file called *Some/Module.pm* and start with this template:
```
package Some::Module; # assumes Some/Module.pm
use v5.36;
# Get the import method from Exporter to export functions and
# variables
use Exporter 5.57 'import';
# set the version for version checking
our $VERSION = '1.00';
# Functions and variables which are exported by default
our @EXPORT = qw(func1 func2);
# Functions and variables which can be optionally exported
our @EXPORT_OK = qw($Var1 %Hashit func3);
# exported package globals go here
our $Var1 = '';
our %Hashit = ();
# non-exported package globals go here
# (they are still accessible as $Some::Module::stuff)
our @more = ();
our $stuff = '';
# file-private lexicals go here, before any functions which use them
my $priv_var = '';
my %secret_hash = ();
# here's a file-private function as a closure,
# callable as $priv_func->();
my $priv_func = sub {
...
};
# make all your functions, whether exported or not;
# remember to put something interesting in the {} stubs
sub func1 { ... }
sub func2 { ... }
# this one isn't always exported, but could be called directly
# as Some::Module::func3()
sub func3 { ... }
END { ... } # module clean-up code here (global destructor)
1; # don't forget to return a true value from the file
```
Then go on to declare and use your variables in functions without any qualifications. See [Exporter](exporter) and the <perlmodlib> for details on mechanics and style issues in module creation.
Perl modules are included into your program by saying
```
use Module;
```
or
```
use Module LIST;
```
This is exactly equivalent to
```
BEGIN { require 'Module.pm'; 'Module'->import; }
```
or
```
BEGIN { require 'Module.pm'; 'Module'->import( LIST ); }
```
As a special case
```
use Module ();
```
is exactly equivalent to
```
BEGIN { require 'Module.pm'; }
```
All Perl module files have the extension *.pm*. The `use` operator assumes this so you don't have to spell out "*Module.pm*" in quotes. This also helps to differentiate new modules from old *.pl* and *.ph* files. Module names are also capitalized unless they're functioning as pragmas; pragmas are in effect compiler directives, and are sometimes called "pragmatic modules" (or even "pragmata" if you're a classicist).
The two statements:
```
require SomeModule;
require "SomeModule.pm";
```
differ from each other in two ways. In the first case, any double colons in the module name, such as `Some::Module`, are translated into your system's directory separator, usually "/". The second case does not, and would have to be specified literally. The other difference is that seeing the first `require` clues in the compiler that uses of indirect object notation involving "SomeModule", as in `$ob = purge SomeModule`, are method calls, not function calls. (Yes, this really can make a difference.)
Because the `use` statement implies a `BEGIN` block, the importing of semantics happens as soon as the `use` statement is compiled, before the rest of the file is compiled. This is how it is able to function as a pragma mechanism, and also how modules are able to declare subroutines that are then visible as list or unary operators for the rest of the current file. This will not work if you use `require` instead of `use`. With `require` you can get into this problem:
```
require Cwd; # make Cwd:: accessible
$here = Cwd::getcwd();
use Cwd; # import names from Cwd::
$here = getcwd();
require Cwd; # make Cwd:: accessible
$here = getcwd(); # oops! no main::getcwd()
```
In general, `use Module ()` is recommended over `require Module`, because it determines module availability at compile time, not in the middle of your program's execution. An exception would be if two modules each tried to `use` each other, and each also called a function from that other module. In that case, it's easy to use `require` instead.
Perl packages may be nested inside other package names, so we can have package names containing `::`. But if we used that package name directly as a filename it would make for unwieldy or impossible filenames on some systems. Therefore, if a module's name is, say, `Text::Soundex`, then its definition is actually found in the library file *Text/Soundex.pm*.
Perl modules always have a *.pm* file, but there may also be dynamically linked executables (often ending in *.so*) or autoloaded subroutine definitions (often ending in *.al*) associated with the module. If so, these will be entirely transparent to the user of the module. It is the responsibility of the *.pm* file to load (or arrange to autoload) any additional functionality. For example, although the POSIX module happens to do both dynamic loading and autoloading, the user can say just `use POSIX` to get it all.
###
Making your module threadsafe
Perl supports a type of threads called interpreter threads (ithreads). These threads can be used explicitly and implicitly.
Ithreads work by cloning the data tree so that no data is shared between different threads. These threads can be used by using the `threads` module or by doing fork() on win32 (fake fork() support). When a thread is cloned all Perl data is cloned, however non-Perl data cannot be cloned automatically. Perl after 5.8.0 has support for the `CLONE` special subroutine. In `CLONE` you can do whatever you need to do, like for example handle the cloning of non-Perl data, if necessary. `CLONE` will be called once as a class method for every package that has it defined (or inherits it). It will be called in the context of the new thread, so all modifications are made in the new area. Currently CLONE is called with no parameters other than the invocant package name, but code should not assume that this will remain unchanged, as it is likely that in future extra parameters will be passed in to give more information about the state of cloning.
If you want to CLONE all objects you will need to keep track of them per package. This is simply done using a hash and Scalar::Util::weaken().
Perl after 5.8.7 has support for the `CLONE_SKIP` special subroutine. Like `CLONE`, `CLONE_SKIP` is called once per package; however, it is called just before cloning starts, and in the context of the parent thread. If it returns a true value, then no objects of that class will be cloned; or rather, they will be copied as unblessed, undef values. For example: if in the parent there are two references to a single blessed hash, then in the child there will be two references to a single undefined scalar value instead. This provides a simple mechanism for making a module threadsafe; just add `sub CLONE_SKIP { 1 }` at the top of the class, and `DESTROY()` will now only be called once per object. Of course, if the child thread needs to make use of the objects, then a more sophisticated approach is needed.
Like `CLONE`, `CLONE_SKIP` is currently called with no parameters other than the invocant package name, although that may change. Similarly, to allow for future expansion, the return value should be a single `0` or `1` value.
SEE ALSO
---------
See <perlmodlib> for general style issues related to building Perl modules and classes, as well as descriptions of the standard library and CPAN, [Exporter](exporter) for how Perl's standard import/export mechanism works, <perlootut> and <perlobj> for in-depth information on creating classes, <perlobj> for a hard-core reference document on objects, <perlsub> for an explanation of functions and scoping, and <perlxstut> and <perlguts> for more information on writing extension modules.
| programming_docs |
perl perlfreebsd perlfreebsd
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [FreeBSD core dumps from readdir\_r with ithreads](#FreeBSD-core-dumps-from-readdir_r-with-ithreads)
+ [$^X doesn't always contain a full path in FreeBSD](#%24%5EX-doesn't-always-contain-a-full-path-in-FreeBSD)
* [AUTHOR](#AUTHOR)
NAME
----
perlfreebsd - Perl version 5 on FreeBSD systems
DESCRIPTION
-----------
This document describes various features of FreeBSD that will affect how Perl version 5 (hereafter just Perl) is compiled and/or runs.
###
FreeBSD core dumps from readdir\_r with ithreads
When perl is configured to use ithreads, it will use re-entrant library calls in preference to non-re-entrant versions. There is a bug in FreeBSD's `readdir_r` function in versions 4.5 and earlier that can cause a SEGV when reading large directories. A patch for FreeBSD libc is available (see <http://www.freebsd.org/cgi/query-pr.cgi?pr=misc/30631> ) which has been integrated into FreeBSD 4.6.
###
`$^X` doesn't always contain a full path in FreeBSD
perl sets `$^X` where possible to a full path by asking the operating system. On FreeBSD the full path of the perl interpreter is found by using `sysctl` with `KERN_PROC_PATHNAME` if that is supported, else by reading the symlink */proc/curproc/file*. FreeBSD 7 and earlier has a bug where either approach sometimes returns an incorrect value (see <http://www.freebsd.org/cgi/query-pr.cgi?pr=35703> ). In these cases perl will fall back to the old behaviour of using C's `argv[0]` value for `$^X`.
AUTHOR
------
Nicholas Clark <[email protected]>, collating wisdom supplied by Slaven Rezic and Tim Bunce.
Please report any errors, updates, or suggestions to <https://github.com/Perl/perl5/issues>.
perl CPAN::Meta::YAML CPAN::Meta::YAML
================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::YAML - Read and write a subset of YAML for CPAN Meta files
VERSION
-------
version 0.018
SYNOPSIS
--------
```
use CPAN::Meta::YAML;
# reading a META file
open $fh, "<:utf8", "META.yml";
$yaml_text = do { local $/; <$fh> };
$yaml = CPAN::Meta::YAML->read_string($yaml_text)
or die CPAN::Meta::YAML->errstr;
# finding the metadata
$meta = $yaml->[0];
# writing a META file
$yaml_text = $yaml->write_string
or die CPAN::Meta::YAML->errstr;
open $fh, ">:utf8", "META.yml";
print $fh $yaml_text;
```
DESCRIPTION
-----------
This module implements a subset of the YAML specification for use in reading and writing CPAN metadata files like *META.yml* and *MYMETA.yml*. It should not be used for any other general YAML parsing or generation task.
NOTE: *META.yml* (and *MYMETA.yml*) files should be UTF-8 encoded. Users are responsible for proper encoding and decoding. In particular, the `read` and `write` methods do **not** support UTF-8 and should not be used.
SUPPORT
-------
This module is currently derived from <YAML::Tiny> by Adam Kennedy. If there are bugs in how it parses a particular META.yml file, please file a bug report in the YAML::Tiny bugtracker: <https://github.com/Perl-Toolchain-Gang/YAML-Tiny/issues>
SEE ALSO
---------
<YAML::Tiny>, [YAML](yaml), <YAML::XS>
AUTHORS
-------
* Adam Kennedy <[email protected]>
* David Golden <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by Adam Kennedy.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl XS::Typemap XS::Typemap
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
* [AUTHOR](#AUTHOR)
NAME
----
XS::Typemap - module to test the XS typemaps distributed with perl
SYNOPSIS
--------
```
use XS::Typemap;
$output = T_IV( $input );
$output = T_PV( $input );
@output = T_ARRAY( @input );
```
DESCRIPTION
-----------
This module is used to test that the XS typemaps distributed with perl are working as advertised. A function is available for each typemap definition (eventually). In general each function takes a variable, processes it through the OUTPUT typemap and then returns it using the INPUT typemap.
A test script can then compare the input and output to make sure they are the expected values. When only an input or output function is provided the function will be named after the typemap entry and have either '\_IN' or '\_OUT' appended.
All the functions are exported. There is no reason not to do this since the entire purpose is for testing Perl. Namespace pollution will be limited to the test script.
NOTES
-----
This module is for testing only and should not normally be installed.
AUTHOR
------
Tim Jenness <[email protected]>
Copyright (C) 2001 Tim Jenness All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Net::Config Net::Config
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Class Methods](#Class-Methods)
+ [NetConfig Values](#NetConfig-Values)
* [EXPORTS](#EXPORTS)
* [KNOWN BUGS](#KNOWN-BUGS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
* [LICENCE](#LICENCE)
* [VERSION](#VERSION)
* [DATE](#DATE)
* [HISTORY](#HISTORY)
NAME
----
Net::Config - Local configuration data for libnet
SYNOPSIS
--------
```
use Net::Config qw(%NetConfig);
```
DESCRIPTION
-----------
`Net::Config` holds configuration data for the modules in the libnet distribution. During installation you will be asked for these values.
The configuration data is held globally in a file in the perl installation tree, but a user may override any of these values by providing their own. This can be done by having a `.libnetrc` file in their home directory. This file should return a reference to a HASH containing the keys described below. For example
```
# .libnetrc
{
nntp_hosts => [ "my_preferred_host" ],
ph_hosts => [ "my_ph_server" ],
}
__END__
```
###
Class Methods
`Net::Config` defines the following methods. They are methods as they are invoked as class methods. This is because `Net::Config` inherits from `Net::LocalCfg` so you can override these methods if you want.
`requires_firewall($host)`
Attempts to determine if a given host is outside your firewall. Possible return values are.
```
-1 Cannot lookup hostname
0 Host is inside firewall (or there is no ftp_firewall entry)
1 Host is outside the firewall
```
This is done by using hostname lookup and the `local_netmask` entry in the configuration data.
###
NetConfig Values
nntp\_hosts snpp\_hosts pop3\_hosts smtp\_hosts ph\_hosts daytime\_hosts time\_hosts Each is a reference to an array of hostnames (in order of preference), which should be used for the given protocol
inet\_domain Your internet domain name
ftp\_firewall If you have an FTP proxy firewall (**NOT** an HTTP or SOCKS firewall) then this value should be set to the firewall hostname. If your firewall does not listen to port 21, then this value should be set to `"hostname:port"` (eg `"hostname:99"`)
ftp\_firewall\_type There are many different ftp firewall products available. But unfortunately there is no standard for how to traverse a firewall. The list below shows the sequence of commands that Net::FTP will use
```
user Username for remote host
pass Password for remote host
fwuser Username for firewall
fwpass Password for firewall
remote.host The hostname of the remote ftp server
```
0 There is no firewall
1
```
USER [email protected]
PASS pass
```
2
```
USER fwuser
PASS fwpass
USER [email protected]
PASS pass
```
3
```
USER fwuser
PASS fwpass
SITE remote.site
USER user
PASS pass
```
4
```
USER fwuser
PASS fwpass
OPEN remote.site
USER user
PASS pass
```
5
```
USER user@[email protected]
PASS pass@fwpass
```
6
```
USER [email protected]
PASS fwpass
USER user
PASS pass
```
7
```
USER [email protected]
PASS pass
AUTH fwuser
RESP fwpass
```
ftp\_ext\_passive ftp\_int\_passive FTP servers can work in passive or active mode. Active mode is when you want to transfer data you have to tell the server the address and port to connect to. Passive mode is when the server provide the address and port and you establish the connection.
With some firewalls active mode does not work as the server cannot connect to your machine (because you are behind a firewall) and the firewall does not re-write the command. In this case you should set `ftp_ext_passive` to a *true* value.
Some servers are configured to only work in passive mode. If you have one of these you can force `Net::FTP` to always transfer in passive mode; when not going via a firewall, by setting `ftp_int_passive` to a *true* value.
local\_netmask A reference to a list of netmask strings in the form `"134.99.4.0/24"`. These are used by the `requires_firewall` function to determine if a given host is inside or outside your firewall.
The following entries are used during installation & testing on the libnet package
test\_hosts If true then `make test` may attempt to connect to hosts given in the configuration.
test\_exists If true then `Configure` will check each hostname given that it exists
EXPORTS
-------
The following symbols are, or can be, exported by this module:
Default Exports `%NetConfig`.
Optional Exports *None*.
Export Tags *None*.
KNOWN BUGS
-----------
*None*.
AUTHOR
------
Graham Barr <[[email protected]](mailto:[email protected])>.
Steve Hay <[[email protected]](mailto:[email protected])> is now maintaining libnet as of version 1.22\_02.
COPYRIGHT
---------
Copyright (C) 2000 Graham Barr. All rights reserved.
Copyright (C) 2013-2014, 2016, 2020 Steve Hay. All rights reserved.
LICENCE
-------
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the *LICENCE* file.
VERSION
-------
Version 3.14
DATE
----
23 Dec 2020
HISTORY
-------
See the *Changes* file.
perl Test::Builder::Module Test::Builder::Module
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Importing](#Importing)
- [import](#import)
- [import\_extra](#import_extra)
+ [Builder](#Builder)
- [builder](#builder)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Test::Builder::Module - Base class for test modules
SYNOPSIS
--------
```
# Emulates Test::Simple
package Your::Module;
my $CLASS = __PACKAGE__;
use parent 'Test::Builder::Module';
@EXPORT = qw(ok);
sub ok ($;$) {
my $tb = $CLASS->builder;
return $tb->ok(@_);
}
1;
```
DESCRIPTION
-----------
This is a superclass for <Test::Builder>-based modules. It provides a handful of common functionality and a method of getting at the underlying <Test::Builder> object.
### Importing
Test::Builder::Module is a subclass of [Exporter](exporter) which means your module is also a subclass of Exporter. @EXPORT, @EXPORT\_OK, etc... all act normally.
A few methods are provided to do the `use Your::Module tests => 23` part for you.
#### import
Test::Builder::Module provides an `import()` method which acts in the same basic way as <Test::More>'s, setting the plan and controlling exporting of functions and variables. This allows your module to set the plan independent of <Test::More>.
All arguments passed to `import()` are passed onto `Your::Module->builder->plan()` with the exception of `import =>[qw(things to import)]`.
```
use Your::Module import => [qw(this that)], tests => 23;
```
says to import the functions `this()` and `that()` as well as set the plan to be 23 tests.
`import()` also sets the `exported_to()` attribute of your builder to be the caller of the `import()` function.
Additional behaviors can be added to your `import()` method by overriding `import_extra()`.
#### import\_extra
```
Your::Module->import_extra(\@import_args);
```
`import_extra()` is called by `import()`. It provides an opportunity for you to add behaviors to your module based on its import list.
Any extra arguments which shouldn't be passed on to `plan()` should be stripped off by this method.
See <Test::More> for an example of its use.
**NOTE** This mechanism is *VERY ALPHA AND LIKELY TO CHANGE* as it feels like a bit of an ugly hack in its current form.
### Builder
Test::Builder::Module provides some methods of getting at the underlying Test::Builder object.
#### builder
```
my $builder = Your::Class->builder;
```
This method returns the <Test::Builder> object associated with Your::Class. It is not a constructor so you can call it as often as you like.
This is the preferred way to get the <Test::Builder> object. You should *not* get it via `Test::Builder->new` as was previously recommended.
The object returned by `builder()` may change at runtime so you should call `builder()` inside each function rather than store it in a global.
```
sub ok {
my $builder = Your::Class->builder;
return $builder->ok(@_);
}
```
SEE ALSO
---------
<Test2::Manual::Tooling::TestBuilder> describes the improved options for writing testing modules provided by [Test2](test2).
perl perlmodinstall perlmodinstall
==============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [PREAMBLE](#PREAMBLE)
* [PORTABILITY](#PORTABILITY)
* [HEY](#HEY)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
perlmodinstall - Installing CPAN Modules
DESCRIPTION
-----------
You can think of a module as the fundamental unit of reusable Perl code; see <perlmod> for details. Whenever anyone creates a chunk of Perl code that they think will be useful to the world, they register as a Perl developer at <https://www.cpan.org/modules/04pause.html> so that they can then upload their code to the CPAN. The CPAN is the Comprehensive Perl Archive Network and can be accessed at <https://www.cpan.org/> , and searched at <https://metacpan.org/> .
This documentation is for people who want to download CPAN modules and install them on their own computer.
### PREAMBLE
First, are you sure that the module isn't already on your system? Try `perl -MFoo -e 1`. (Replace "Foo" with the name of the module; for instance, `perl -MCGI::Carp -e 1`.)
If you don't see an error message, you have the module. (If you do see an error message, it's still possible you have the module, but that it's not in your path, which you can display with `perl -e "print qq(@INC)"`.) For the remainder of this document, we'll assume that you really honestly truly lack an installed module, but have found it on the CPAN.
So now you have a file ending in .tar.gz (or, less often, .zip). You know there's a tasty module inside. There are four steps you must now take:
**DECOMPRESS** the file
**UNPACK** the file into a directory
**BUILD** the module (sometimes unnecessary)
**INSTALL** the module. Here's how to perform each step for each operating system. This is <not> a substitute for reading the README and INSTALL files that might have come with your module!
Also note that these instructions are tailored for installing the module into your system's repository of Perl modules, but you can install modules into any directory you wish. For instance, where I say `perl Makefile.PL`, you can substitute `perl Makefile.PL PREFIX=/my/perl_directory` to install the modules into */my/perl\_directory*. Then you can use the modules from your Perl programs with `use lib "/my/perl_directory/lib/site_perl";` or sometimes just `use "/my/perl_directory";`. If you're on a system that requires superuser/root access to install modules into the directories you see when you type `perl -e "print qq(@INC)"`, you'll want to install them into a local directory (such as your home directory) and use this approach.
* **If you're on a Unix or Unix-like system,**
You can use Andreas Koenig's CPAN module ( <https://metacpan.org/release/CPAN> ) to automate the following steps, from DECOMPRESS through INSTALL.
A. DECOMPRESS
Decompress the file with `gzip -d yourmodule.tar.gz`
You can get gzip from <ftp://prep.ai.mit.edu/pub/gnu/>
Or, you can combine this step with the next to save disk space:
```
gzip -dc yourmodule.tar.gz | tar -xof -
```
B. UNPACK
Unpack the result with `tar -xof yourmodule.tar`
C. BUILD
Go into the newly-created directory and type:
```
perl Makefile.PL
make test
```
or
```
perl Makefile.PL PREFIX=/my/perl_directory
```
to install it locally. (Remember that if you do this, you'll have to put `use lib "/my/perl_directory";` near the top of the program that is to use this module.
D. INSTALL
While still in that directory, type:
```
make install
```
Make sure you have the appropriate permissions to install the module in your Perl 5 library directory. Often, you'll need to be root.
That's all you need to do on Unix systems with dynamic linking. Most Unix systems have dynamic linking. If yours doesn't, or if for another reason you have a statically-linked perl, **and** the module requires compilation, you'll need to build a new Perl binary that includes the module. Again, you'll probably need to be root.
* **If you're running ActivePerl (Win95/98/2K/NT/XP, Linux, Solaris),**
First, type `ppm` from a shell and see whether ActiveState's PPM repository has your module. If so, you can install it with `ppm` and you won't have to bother with any of the other steps here. You might be able to use the CPAN instructions from the "Unix or Linux" section above as well; give it a try. Otherwise, you'll have to follow the steps below.
```
A. DECOMPRESS
```
You can use the open source 7-zip ( <https://www.7-zip.org/> ) or the shareware Winzip ( <https://www.winzip.com> ) to decompress and unpack modules.
```
B. UNPACK
```
If you used WinZip, this was already done for you.
```
C. BUILD
```
You'll need either `nmake` or `gmake`.
Does the module require compilation (i.e. does it have files that end in .xs, .c, .h, .y, .cc, .cxx, or .C)? If it does, life is now officially tough for you, because you have to compile the module yourself (no easy feat on Windows). You'll need a compiler such as Visual C++. Alternatively, you can download a pre-built PPM package from ActiveState. <http://aspn.activestate.com/ASPN/Downloads/ActivePerl/PPM/>
Go into the newly-created directory and type:
```
perl Makefile.PL
nmake test
D. INSTALL
```
While still in that directory, type:
```
nmake install
```
* **If you're on OS/2,**
Get the EMX development suite and gzip/tar from Hobbes ( <http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2/dev/emx/v0.9d> ), and then follow the instructions for Unix.
* **If you're on VMS,**
When downloading from CPAN, save your file with a `.tgz` extension instead of `.tar.gz`. All other periods in the filename should be replaced with underscores. For example, `Your-Module-1.33.tar.gz` should be downloaded as `Your-Module-1_33.tgz`.
A. DECOMPRESS
Type
```
gzip -d Your-Module.tgz
```
or, for zipped modules, type
```
unzip Your-Module.zip
```
Executables for gzip, zip, and VMStar:
```
http://www.hp.com/go/openvms/freeware/
```
and their source code:
```
http://www.fsf.org/order/ftp.html
```
Note that GNU's gzip/gunzip is not the same as Info-ZIP's zip/unzip package. The former is a simple compression tool; the latter permits creation of multi-file archives.
B. UNPACK
If you're using VMStar:
```
VMStar xf Your-Module.tar
```
Or, if you're fond of VMS command syntax:
```
tar/extract/verbose Your_Module.tar
```
C. BUILD
Make sure you have MMS (from Digital) or the freeware MMK ( available from MadGoat at <http://www.madgoat.com> ). Then type this to create the DESCRIP.MMS for the module:
```
perl Makefile.PL
```
Now you're ready to build:
```
mms test
```
Substitute `mmk` for `mms` above if you're using MMK.
D. INSTALL
Type
```
mms install
```
Substitute `mmk` for `mms` above if you're using MMK.
* **If you're on MVS**,
Introduce the *.tar.gz* file into an HFS as binary; don't translate from ASCII to EBCDIC.
A. DECOMPRESS
Decompress the file with `gzip -d yourmodule.tar.gz`
You can get gzip from <http://www.s390.ibm.com/products/oe/bpxqp1.html>
B. UNPACK
Unpack the result with
```
pax -o to=IBM-1047,from=ISO8859-1 -r < yourmodule.tar
```
The BUILD and INSTALL steps are identical to those for Unix. Some modules generate Makefiles that work better with GNU make, which is available from <http://www.mks.com/s390/gnu/>
PORTABILITY
-----------
Note that not all modules will work with on all platforms. See <perlport> for more information on portability issues. Read the documentation to see if the module will work on your system. There are basically three categories of modules that will not work "out of the box" with all platforms (with some possibility of overlap):
* **Those that should, but don't.** These need to be fixed; consider contacting the author and possibly writing a patch.
* **Those that need to be compiled, where the target platform doesn't have compilers readily available.** (These modules contain *.xs* or *.c* files, usually.) You might be able to find existing binaries on the CPAN or elsewhere, or you might want to try getting compilers and building it yourself, and then release the binary for other poor souls to use.
* **Those that are targeted at a specific platform.** (Such as the Win32:: modules.) If the module is targeted specifically at a platform other than yours, you're out of luck, most likely.
Check the CPAN Testers if a module should work with your platform but it doesn't behave as you'd expect, or you aren't sure whether or not a module will work under your platform. If the module you want isn't listed there, you can test it yourself and let CPAN Testers know, you can join CPAN Testers, or you can request it be tested.
```
https://cpantesters.org/
```
HEY
---
If you have any suggested changes for this page, let me know. Please don't send me mail asking for help on how to install your modules. There are too many modules, and too few Orwants, for me to be able to answer or even acknowledge all your questions. Contact the module author instead, ask someone familiar with Perl on your operating system, or if all else fails, file a ticket at <https://rt.cpan.org/>.
AUTHOR
------
Jon Orwant
[email protected]
with invaluable help from Chris Nandor, and valuable help from Brandon Allbery, Charles Bailey, Graham Barr, Dominic Dunlop, Jarkko Hietaniemi, Ben Holzman, Tom Horsley, Nick Ing-Simmons, Tuomas J. Lukka, Laszlo Molnar, Alan Olsen, Peter Prymmer, Gurusamy Sarathy, Christoph Spalinger, Dan Sugalski, Larry Virden, and Ilya Zakharevich.
First version July 22, 1998; last revised November 21, 2001.
COPYRIGHT
---------
Copyright (C) 1998, 2002, 2003 Jon Orwant. All Rights Reserved.
This document may be distributed under the same terms as Perl itself.
| programming_docs |
perl encoding::warnings encoding::warnings
==================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [NOTICE](#NOTICE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overview of the problem](#Overview-of-the-problem)
+ [Detecting the problem](#Detecting-the-problem)
+ [Solving the problem](#Solving-the-problem)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
encoding::warnings - Warn on implicit encoding conversions
VERSION
-------
This document describes version 0.13 of encoding::warnings, released June 20, 2016.
NOTICE
------
As of Perl 5.26.0, this module has no effect. The internal Perl feature that was used to implement this module has been removed. In recent years, much work has been done on the Perl core to eliminate discrepancies in the treatment of upgraded versus downgraded strings. In addition, the <encoding> pragma, which caused many of the problems, is no longer supported. Thus, the warnings this module produced are no longer necessary.
Hence, if you load this module on Perl 5.26.0, you will get one warning that the module is no longer supported; and the module will do nothing thereafter.
SYNOPSIS
--------
```
use encoding::warnings; # or 'FATAL' to raise fatal exceptions
utf8::encode($a = chr(20000)); # a byte-string (raw bytes)
$b = chr(20000); # a unicode-string (wide characters)
# "Bytes implicitly upgraded into wide characters as iso-8859-1"
$c = $a . $b;
```
DESCRIPTION
-----------
###
Overview of the problem
By default, there is a fundamental asymmetry in Perl's unicode model: implicit upgrading from byte-strings to unicode-strings assumes that they were encoded in *ISO 8859-1 (Latin-1)*, but unicode-strings are downgraded with UTF-8 encoding. This happens because the first 256 codepoints in Unicode happens to agree with Latin-1.
However, this silent upgrading can easily cause problems, if you happen to mix unicode strings with non-Latin1 data -- i.e. byte-strings encoded in UTF-8 or other encodings. The error will not manifest until the combined string is written to output, at which time it would be impossible to see where did the silent upgrading occur.
###
Detecting the problem
This module simplifies the process of diagnosing such problems. Just put this line on top of your main program:
```
use encoding::warnings;
```
Afterwards, implicit upgrading of high-bit bytes will raise a warning. Ex.: `Bytes implicitly upgraded into wide characters as iso-8859-1 at - line 7`.
However, strings composed purely of ASCII code points (`0x00`..`0x7F`) will *not* trigger this warning.
You can also make the warnings fatal by importing this module as:
```
use encoding::warnings 'FATAL';
```
###
Solving the problem
Most of the time, this warning occurs when a byte-string is concatenated with a unicode-string. There are a number of ways to solve it:
* Upgrade both sides to unicode-strings
If your program does not need compatibility for Perl 5.6 and earlier, the recommended approach is to apply appropriate IO disciplines, so all data in your program become unicode-strings. See <encoding>, <open> and ["binmode" in perlfunc](perlfunc#binmode) for how.
* Downgrade both sides to byte-strings
The other way works too, especially if you are sure that all your data are under the same encoding, or if compatibility with older versions of Perl is desired.
You may downgrade strings with `Encode::encode` and `utf8::encode`. See [Encode](encode) and <utf8> for details.
* Specify the encoding for implicit byte-string upgrading
If you are confident that all byte-strings will be in a specific encoding like UTF-8, *and* need not support older versions of Perl, use the `encoding` pragma:
```
use encoding 'utf8';
```
Similarly, this will silence warnings from this module, and preserve the default behaviour:
```
use encoding 'iso-8859-1';
```
However, note that `use encoding` actually had three distinct effects:
+ PerlIO layers for **STDIN** and **STDOUT**
This is similar to what <open> pragma does.
+ Literal conversions
This turns *all* literal string in your program into unicode-strings (equivalent to a `use utf8`), by decoding them using the specified encoding.
+ Implicit upgrading for byte-strings
This will silence warnings from this module, as shown above.Because literal conversions also work on empty strings, it may surprise some people:
```
use encoding 'big5';
my $byte_string = pack("C*", 0xA4, 0x40);
print length $a; # 2 here.
$a .= ""; # concatenating with a unicode string...
print length $a; # 1 here!
```
In other words, do not `use encoding` unless you are certain that the program will not deal with any raw, 8-bit binary data at all.
However, the `Filter => 1` flavor of `use encoding` will *not* affect implicit upgrading for byte-strings, and is thus incapable of silencing warnings from this module. See <encoding> for more details.
CAVEATS
-------
For Perl 5.9.4 or later, this module's effect is lexical.
For Perl versions prior to 5.9.4, this module affects the whole script, instead of inside its lexical block.
SEE ALSO
---------
<perlunicode>, <perluniintro>
<open>, <utf8>, <encoding>, [Encode](encode)
AUTHORS
-------
Audrey Tang
COPYRIGHT
---------
Copyright 2004, 2005, 2006, 2007 by Audrey Tang <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See <http://www.perl.com/perl/misc/Artistic.html>
perl ExtUtils::MM_Darwin ExtUtils::MM\_Darwin
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Overridden Methods](#Overridden-Methods)
- [init\_dist](#init_dist)
- [cflags](#cflags)
NAME
----
ExtUtils::MM\_Darwin - special behaviors for OS X
SYNOPSIS
--------
```
For internal MakeMaker use only
```
DESCRIPTION
-----------
See <ExtUtils::MM_Unix> or <ExtUtils::MM_Any> for documentation on the methods overridden here.
###
Overridden Methods
#### init\_dist
Turn off Apple tar's tendency to copy resource forks as ".\_foo" files.
#### cflags
Over-ride Apple's automatic setting of -Werror
perl Tie::StdHandle Tie::StdHandle
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
Tie::StdHandle - base class definitions for tied handles
SYNOPSIS
--------
```
package NewHandle;
require Tie::Handle;
@ISA = qw(Tie::Handle);
sub READ { ... } # Provide a needed method
sub TIEHANDLE { ... } # Overrides inherited method
package main;
tie *FH, 'NewHandle';
```
DESCRIPTION
-----------
The **Tie::StdHandle** package provide most methods for file handles described in <perltie> (the exceptions are `UNTIE` and `DESTROY`). It causes tied file handles to behave exactly like standard file handles and allow for selective overwriting of methods.
perl IO::Dir IO::Dir
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Dir - supply object methods for directory handles
SYNOPSIS
--------
```
use IO::Dir;
$d = IO::Dir->new(".");
if (defined $d) {
while (defined($_ = $d->read)) { something($_); }
$d->rewind;
while (defined($_ = $d->read)) { something_else($_); }
undef $d;
}
tie %dir, 'IO::Dir', ".";
foreach (keys %dir) {
print $_, " " , $dir{$_}->size,"\n";
}
```
DESCRIPTION
-----------
The `IO::Dir` package provides two interfaces to perl's directory reading routines.
The first interface is an object approach. `IO::Dir` provides an object constructor and methods, which are just wrappers around perl's built in directory reading routines.
new ( [ DIRNAME ] ) `new` is the constructor for `IO::Dir` objects. It accepts one optional argument which, if given, `new` will pass to `open`
The following methods are wrappers for the directory related functions built into perl (the trailing 'dir' has been removed from the names). See <perlfunc> for details of these functions.
open ( DIRNAME )
read ()
seek ( POS )
tell ()
rewind ()
close () `IO::Dir` also provides an interface to reading directories via a tied hash. The tied hash extends the interface beyond just the directory reading routines by the use of `lstat`, from the `File::stat` package, `unlink`, `rmdir` and `utime`.
tie %hash, 'IO::Dir', DIRNAME [, OPTIONS ] The keys of the hash will be the names of the entries in the directory. Reading a value from the hash will be the result of calling `File::stat::lstat`. Deleting an element from the hash will delete the corresponding file or subdirectory, provided that `DIR_UNLINK` is included in the `OPTIONS`.
Assigning to an entry in the hash will cause the time stamps of the file to be modified. If the file does not exist then it will be created. Assigning a single integer to a hash element will cause both the access and modification times to be changed to that value. Alternatively a reference to an array of two values can be passed. The first array element will be used to set the access time and the second element will be used to set the modification time.
SEE ALSO
---------
<File::stat>
AUTHOR
------
Graham Barr. Currently maintained by the Perl Porters. Please report all bugs at <https://github.com/Perl/perl5/issues>.
COPYRIGHT
---------
Copyright (c) 1997-2003 Graham Barr <[email protected]>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Test2::API::Context Test2::API::Context
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [CRITICAL DETAILS](#CRITICAL-DETAILS)
* [METHODS](#METHODS)
+ [EVENT PRODUCTION METHODS](#EVENT-PRODUCTION-METHODS)
* [HOOKS](#HOOKS)
+ [INIT HOOKS](#INIT-HOOKS)
- [GLOBAL](#GLOBAL)
- [PER HUB](#PER-HUB)
- [PER CONTEXT](#PER-CONTEXT)
+ [RELEASE HOOKS](#RELEASE-HOOKS)
- [GLOBAL](#GLOBAL1)
- [PER HUB](#PER-HUB1)
- [PER CONTEXT](#PER-CONTEXT1)
* [THIRD PARTY META-DATA](#THIRD-PARTY-META-DATA)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::API::Context - Object to represent a testing context.
DESCRIPTION
-----------
The context object is the primary interface for authors of testing tools written with [Test2](test2). The context object represents the context in which a test takes place (File and Line Number), and provides a quick way to generate events from that context. The context object also takes care of sending events to the correct <Test2::Hub> instance.
SYNOPSIS
--------
In general you will not be creating contexts directly. To obtain a context you should always use `context()` which is exported by the <Test2::API> module.
```
use Test2::API qw/context/;
sub my_ok {
my ($bool, $name) = @_;
my $ctx = context();
if ($bool) {
$ctx->pass($name);
}
else {
$ctx->fail($name);
}
$ctx->release; # You MUST do this!
return $bool;
}
```
Context objects make it easy to wrap other tools that also use context. Once you grab a context, any tool you call before releasing your context will inherit it:
```
sub wrapper {
my ($bool, $name) = @_;
my $ctx = context();
$ctx->diag("wrapping my_ok");
my $out = my_ok($bool, $name);
$ctx->release; # You MUST do this!
return $out;
}
```
CRITICAL DETAILS
-----------------
you MUST always use the context() sub from Test2::API Creating your own context via `Test2::API::Context->new()` will almost never produce a desirable result. Use `context()` which is exported by <Test2::API>.
There are a handful of cases where a tool author may want to create a new context by hand, which is why the `new` method exists. Unless you really know what you are doing you should avoid this.
You MUST always release the context when done with it Releasing the context tells the system you are done with it. This gives it a chance to run any necessary callbacks or cleanup tasks. If you forget to release the context it will try to detect the problem and warn you about it.
You MUST NOT pass context objects around When you obtain a context object it is made specifically for your tool and any tools nested within. If you pass a context around you run the risk of polluting other tools with incorrect context information.
If you are certain that you want a different tool to use the same context you may pass it a snapshot. `$ctx->snapshot` will give you a shallow clone of the context that is safe to pass around or store.
You MUST NOT store or cache a context for later As long as a context exists for a given hub, all tools that try to get a context will get the existing instance. If you try to store the context you will pollute other tools with incorrect context information.
If you are certain that you want to save the context for later, you can use a snapshot. `$ctx->snapshot` will give you a shallow clone of the context that is safe to pass around or store.
`context()` has some mechanisms to protect you if you do cause a context to persist beyond the scope in which it was obtained. In practice you should not rely on these protections, and they are fairly noisy with warnings.
You SHOULD obtain your context as soon as possible in a given tool You never know what tools you call from within your own tool will need a context. Obtaining the context early ensures that nested tools can find the context you want them to find.
METHODS
-------
$ctx->done\_testing; Note that testing is finished. If no plan has been set this will generate a Plan event.
$clone = $ctx->snapshot() This will return a shallow clone of the context. The shallow clone is safe to store for later.
$ctx->release() This will release the context. This runs cleanup tasks, and several important hooks. It will also restore `$!`, `$?`, and `$@` to what they were when the context was created.
**Note:** If a context is acquired more than once an internal refcount is kept. `release()` decrements the ref count, none of the other actions of `release()` will occur unless the refcount hits 0. This means only the last call to `release()` will reset `$?`, `$!`, `$@`,and run the cleanup tasks.
$ctx->throw($message) This will throw an exception reporting to the file and line number of the context. This will also release the context for you.
$ctx->alert($message) This will issue a warning from the file and line number of the context.
$stack = $ctx->stack() This will return the <Test2::API::Stack> instance the context used to find the current hub.
$hub = $ctx->hub() This will return the <Test2::Hub> instance the context recognizes as the current one to which all events should be sent.
$dbg = $ctx->trace() This will return the <Test2::EventFacet::Trace> instance used by the context.
$ctx->do\_in\_context(\&code, @args); Sometimes you have a context that is not current, and you want things to use it as the current one. In these cases you can call `$ctx->do_in_context(sub { ... })`. The codeblock will be run, and anything inside of it that looks for a context will find the one on which the method was called.
This **DOES NOT** affect context on other hubs, only the hub used by the context will be affected.
```
my $ctx = ...;
$ctx->do_in_context(sub {
my $ctx = context(); # returns the $ctx the sub is called on
});
```
**Note:** The context will actually be cloned, the clone will be used instead of the original. This allows the thread id, process id, and error variables to be correct without modifying the original context.
$ctx->restore\_error\_vars() This will set `$!`, `$?`, and `$@` to what they were when the context was created. There is no localization or anything done here, calling this method will actually set these vars.
$! = $ctx->errno() The (numeric) value of `$!` when the context was created.
$? = $ctx->child\_error() The value of `$?` when the context was created.
$@ = $ctx->eval\_error() The value of `$@` when the context was created.
###
EVENT PRODUCTION METHODS
**Which one do I use?**
The `pass*` and `fail*` are optimal if they meet your situation, using one of them will always be the most optimal. That said they are optimal by eliminating many features.
Method such as `ok`, and `note` are shortcuts for generating common 1-task events based on the old API, however they are forward compatible, and easy to use. If these meet your needs then go ahead and use them, but please check back often for alternatives that may be added.
If you want to generate new style events, events that do many things at once, then you want the `*ev2*` methods. These let you directly specify which facets you wish to use.
$event = $ctx->pass()
$event = $ctx->pass($name) This will send and return an <Test2::Event::Pass> event. You may optionally provide a `$name` for the assertion.
The <Test2::Event::Pass> is a specially crafted and optimized event, using this will help the performance of passing tests.
$true = $ctx->pass\_and\_release()
$true = $ctx->pass\_and\_release($name) This is a combination of `pass()` and `release()`. You can use this if you do not plan to do anything with the context after sending the event. This helps write more clear and compact code.
```
sub shorthand {
my ($bool, $name) = @_;
my $ctx = context();
return $ctx->pass_and_release($name) if $bool;
... Handle a failure ...
}
sub longform {
my ($bool, $name) = @_;
my $ctx = context();
if ($bool) {
$ctx->pass($name);
$ctx->release;
return 1;
}
... Handle a failure ...
}
```
my $event = $ctx->fail()
my $event = $ctx->fail($name)
my $event = $ctx->fail($name, @diagnostics) This lets you send an <Test2::Event::Fail> event. You may optionally provide a `$name` and `@diagnostics` messages.
Diagnostics messages can be simple strings, data structures, or instances of <Test2::EventFacet::Info::Table> (which are converted inline into the <Test2::EventFacet::Info> structure).
my $false = $ctx->fail\_and\_release()
my $false = $ctx->fail\_and\_release($name)
my $false = $ctx->fail\_and\_release($name, @diagnostics) This is a combination of `fail()` and `release()`. This can be used to write clearer and shorter code.
```
sub shorthand {
my ($bool, $name) = @_;
my $ctx = context();
return $ctx->fail_and_release($name) unless $bool;
... Handle a success ...
}
sub longform {
my ($bool, $name) = @_;
my $ctx = context();
unless ($bool) {
$ctx->pass($name);
$ctx->release;
return 1;
}
... Handle a success ...
}
```
$event = $ctx->ok($bool, $name)
$event = $ctx->ok($bool, $name, \@on\_fail) **NOTE:** Use of this method is discouraged in favor of `pass()` and `fail()` which produce <Test2::Event::Pass> and <Test2::Event::Fail> events. These newer event types are faster and less crufty.
This will create an <Test2::Event::Ok> object for you. If `$bool` is false then an <Test2::Event::Diag> event will be sent as well with details about the failure. If you do not want automatic diagnostics you should use the `send_event()` method directly.
The third argument `\@on_fail`) is an optional set of diagnostics to be sent in the event of a test failure. Unlike with `fail()` these diagnostics must be plain strings, data structures are not supported.
$event = $ctx->note($message) Send an <Test2::Event::Note>. This event prints a message to STDOUT.
$event = $ctx->diag($message) Send an <Test2::Event::Diag>. This event prints a message to STDERR.
$event = $ctx->plan($max)
$event = $ctx->plan(0, 'SKIP', $reason) This can be used to send an <Test2::Event::Plan> event. This event usually takes either a number of tests you expect to run. Optionally you can set the expected count to 0 and give the 'SKIP' directive with a reason to cause all tests to be skipped.
$event = $ctx->skip($name, $reason); Send an <Test2::Event::Skip> event.
$event = $ctx->bail($reason) This sends an <Test2::Event::Bail> event. This event will completely terminate all testing.
$event = $ctx->send\_ev2(%facets) This lets you build and send a V2 event directly from facets. The event is returned after it is sent.
This example sends a single assertion, a note (comment for stdout in Test::Builder talk) and sets the plan to 1.
```
my $event = $ctx->send_event(
plan => {count => 1},
assert => {pass => 1, details => "A passing assert"},
info => [{tag => 'NOTE', details => "This is a note"}],
);
```
$event = $ctx->build\_e2(%facets) This is the same as `send_ev2()`, except it builds and returns the event without sending it.
$event = $ctx->send\_ev2\_and\_release($Type, %parameters) This is a combination of `send_ev2()` and `release()`.
```
sub shorthand {
my $ctx = context();
return $ctx->send_ev2_and_release(assert => {pass => 1, details => 'foo'});
}
sub longform {
my $ctx = context();
my $event = $ctx->send_ev2(assert => {pass => 1, details => 'foo'});
$ctx->release;
return $event;
}
```
$event = $ctx->send\_event($Type, %parameters) **It is better to use send\_ev2() in new code.**
This lets you build and send an event of any type. The `$Type` argument should be the event package name with `Test2::Event::` left off, or a fully qualified package name prefixed with a '+'. The event is returned after it is sent.
```
my $event = $ctx->send_event('Ok', ...);
```
or
```
my $event = $ctx->send_event('+Test2::Event::Ok', ...);
```
$event = $ctx->build\_event($Type, %parameters) **It is better to use build\_ev2() in new code.**
This is the same as `send_event()`, except it builds and returns the event without sending it.
$event = $ctx->send\_event\_and\_release($Type, %parameters) **It is better to use send\_ev2\_and\_release() in new code.**
This is a combination of `send_event()` and `release()`.
```
sub shorthand {
my $ctx = context();
return $ctx->send_event_and_release(Pass => { name => 'foo' });
}
sub longform {
my $ctx = context();
my $event = $ctx->send_event(Pass => { name => 'foo' });
$ctx->release;
return $event;
}
```
HOOKS
-----
There are 2 types of hooks, init hooks, and release hooks. As the names suggest, these hooks are triggered when contexts are created or released.
###
INIT HOOKS
These are called whenever a context is initialized. That means when a new instance is created. These hooks are **NOT** called every time something requests a context, just when a new one is created.
#### GLOBAL
This is how you add a global init callback. Global callbacks happen for every context for any hub or stack.
```
Test2::API::test2_add_callback_context_init(sub {
my $ctx = shift;
...
});
```
####
PER HUB
This is how you add an init callback for all contexts created for a given hub. These callbacks will not run for other hubs.
```
$hub->add_context_init(sub {
my $ctx = shift;
...
});
```
####
PER CONTEXT
This is how you specify an init hook that will only run if your call to `context()` generates a new context. The callback will be ignored if `context()` is returning an existing context.
```
my $ctx = context(on_init => sub {
my $ctx = shift;
...
});
```
###
RELEASE HOOKS
These are called whenever a context is released. That means when the last reference to the instance is about to be destroyed. These hooks are **NOT** called every time `$ctx->release` is called.
#### GLOBAL
This is how you add a global release callback. Global callbacks happen for every context for any hub or stack.
```
Test2::API::test2_add_callback_context_release(sub {
my $ctx = shift;
...
});
```
####
PER HUB
This is how you add a release callback for all contexts created for a given hub. These callbacks will not run for other hubs.
```
$hub->add_context_release(sub {
my $ctx = shift;
...
});
```
####
PER CONTEXT
This is how you add release callbacks directly to a context. The callback will **ALWAYS** be added to the context that gets returned, it does not matter if a new one is generated, or if an existing one is returned.
```
my $ctx = context(on_release => sub {
my $ctx = shift;
...
});
```
THIRD PARTY META-DATA
----------------------
This object consumes <Test2::Util::ExternalMeta> which provides a consistent way for you to attach meta-data to instances of this class. This is useful for tools, plugins, and other extensions.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]>
Kent Fredric <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
| programming_docs |
perl IO::Socket IO::Socket
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CONSTRUCTOR ARGUMENTS](#CONSTRUCTOR-ARGUMENTS)
+ [Blocking](#Blocking)
+ [Domain](#Domain)
+ [Listen](#Listen)
+ [Timeout](#Timeout)
+ [Type](#Type)
* [CONSTRUCTORS](#CONSTRUCTORS)
+ [new](#new)
* [METHODS](#METHODS)
+ [accept](#accept)
+ [atmark](#atmark)
+ [autoflush](#autoflush)
+ [bind](#bind)
+ [connected](#connected)
+ [getsockopt](#getsockopt)
+ [listen](#listen)
+ [peername](#peername)
+ [protocol](#protocol)
+ [recv](#recv)
+ [send](#send)
+ [setsockopt](#setsockopt)
+ [shutdown](#shutdown)
+ [sockdomain](#sockdomain)
+ [socket](#socket)
+ [socketpair](#socketpair)
+ [sockname](#sockname)
+ [sockopt](#sockopt)
+ [socktype](#socktype)
+ [timeout](#timeout)
* [EXAMPLES](#EXAMPLES)
* [LIMITATIONS](#LIMITATIONS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IO::Socket - Object interface to socket communications
SYNOPSIS
--------
```
use strict;
use warnings;
use IO::Socket qw(AF_INET AF_UNIX);
# create a new AF_INET socket
my $sock = IO::Socket->new(Domain => AF_INET);
# which is the same as
$sock = IO::Socket::INET->new();
# create a new AF_UNIX socket
$sock = IO::Socket->new(Domain => AF_UNIX);
# which is the same as
$sock = IO::Socket::UNIX->new();
```
DESCRIPTION
-----------
`IO::Socket` provides an object-oriented, <IO::Handle>-based interface to creating and using sockets via [Socket](socket), which provides a near one-to-one interface to the C socket library.
`IO::Socket` is a base class that really only defines methods for those operations which are common to all types of sockets. Operations which are specific to a particular socket domain have methods defined in subclasses of `IO::Socket`. See <IO::Socket::INET>, <IO::Socket::UNIX>, and <IO::Socket::IP> for examples of such a subclass.
`IO::Socket` will export all functions (and constants) defined by [Socket](socket).
CONSTRUCTOR ARGUMENTS
----------------------
Given that `IO::Socket` doesn't have attributes in the traditional sense, the following arguments, rather than attributes, can be passed into the constructor.
Constructor arguments should be passed in `Key => 'Value'` pairs.
The only required argument is ["Domain" in IO::Socket](IO::Socket#Domain).
### Blocking
```
my $sock = IO::Socket->new(..., Blocking => 1);
$sock = IO::Socket->new(..., Blocking => 0);
```
If defined but false, the socket will be set to non-blocking mode. If not specified it defaults to `1` (blocking mode).
### Domain
```
my $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
$sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
```
The socket domain will define which subclass of `IO::Socket` to use. The two options available along with this distribution are `AF_INET` and `AF_UNIX`.
`AF_INET` is for the internet address family of sockets and is handled via <IO::Socket::INET>. `AF_INET` sockets are bound to an internet address and port.
`AF_UNIX` is for the unix domain socket and is handled via <IO::Socket::UNIX>. `AF_UNIX` sockets are bound to the file system as their address name space.
This argument is **required**. All other arguments are optional.
### Listen
```
my $sock = IO::Socket->new(..., Listen => 5);
```
Listen should be an integer value or left unset.
If provided, this argument will place the socket into listening mode. New connections can then be accepted using the ["accept" in IO::Socket](IO::Socket#accept) method. The value given is used as the `listen(2)` queue size.
If the `Listen` argument is given, but false, the queue size will be set to 5.
### Timeout
```
my $sock = IO::Socket->new(..., Timeout => 5);
```
The timeout value, in seconds, for this socket connection. How exactly this value is utilized is defined in the socket domain subclasses that make use of the value.
### Type
```
my $sock = IO::Socket->new(..., Type => IO::Socket::SOCK_STREAM);
```
The socket type that will be used. These are usually `SOCK_STREAM`, `SOCK_DGRAM`, or `SOCK_RAW`. If this argument is left undefined an attempt will be made to infer the type from the service name.
For example, you'll usually use `SOCK_STREAM` with a `tcp` connection and `SOCK_DGRAM` with a `udp` connection.
CONSTRUCTORS
------------
`IO::Socket` extends the <IO::Handle> constructor.
### new
```
my $sock = IO::Socket->new();
# get a new IO::Socket::INET instance
$sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
# get a new IO::Socket::UNIX instance
$sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
# Domain is the only required argument
$sock = IO::Socket->new(
Domain => IO::Socket::AF_INET, # AF_INET, AF_UNIX
Type => IO::Socket::SOCK_STREAM, # SOCK_STREAM, SOCK_DGRAM, ...
Proto => 'tcp', # 'tcp', 'udp', IPPROTO_TCP, IPPROTO_UDP
# and so on...
);
```
Creates an `IO::Socket`, which is a reference to a newly created symbol (see the [Symbol](symbol) package). `new` optionally takes arguments, these arguments are defined in ["CONSTRUCTOR ARGUMENTS" in IO::Socket](IO::Socket#CONSTRUCTOR-ARGUMENTS).
Any of the ["CONSTRUCTOR ARGUMENTS" in IO::Socket](IO::Socket#CONSTRUCTOR-ARGUMENTS) may be passed to the constructor, but if any arguments are provided, then one of them must be the ["Domain" in IO::Socket](IO::Socket#Domain) argument. The ["Domain" in IO::Socket](IO::Socket#Domain) argument can, by default, be either `AF_INET` or `AF_UNIX`. Other domains can be used if a proper subclass for the domain family is registered. All other arguments will be passed to the `configuration` method of the package for that domain.
If the constructor fails it will return `undef` and set the `$errstr` package variable to contain an error message.
```
$sock = IO::Socket->new(...)
or die "Cannot create socket - $IO::Socket::errstr\n";
```
For legacy reasons the error message is also set into the global `$@` variable, and you may still find older code which looks here instead.
```
$sock = IO::Socket->new(...)
or die "Cannot create socket - $@\n";
```
METHODS
-------
`IO::Socket` inherits all methods from <IO::Handle> and implements the following new ones.
### accept
```
my $client_sock = $sock->accept();
my $inet_sock = $sock->accept('IO::Socket::INET');
```
The accept method will perform the system call `accept` on the socket and return a new object. The new object will be created in the same class as the listen socket, unless a specific package name is specified. This object can be used to communicate with the client that was trying to connect.
This differs slightly from the `accept` function in <perlfunc>.
In a scalar context the new socket is returned, or `undef` upon failure. In a list context a two-element array is returned containing the new socket and the peer address; the list will be empty upon failure.
### atmark
```
my $integer = $sock->atmark();
# read in some data on a given socket
my $data;
$sock->read($data, 1024) until $sock->atmark;
# or, export the function to use:
use IO::Socket 'sockatmark';
$sock->read($data, 1024) until sockatmark($sock);
```
True if the socket is currently positioned at the urgent data mark, false otherwise. If your system doesn't yet implement `sockatmark` this will throw an exception.
If your system does not support `sockatmark`, the `use` declaration will fail at compile time.
### autoflush
```
# by default, autoflush will be turned on when referenced
$sock->autoflush(); # turns on autoflush
# turn off autoflush
$sock->autoflush(0);
# turn on autoflush
$sock->autoflush(1);
```
This attribute isn't overridden from <IO::Handle>'s implementation. However, since we turn it on by default, it's worth mentioning here.
### bind
```
use Socket qw(pack_sockaddr_in);
my $port = 3000;
my $ip_address = '0.0.0.0';
my $packed_addr = pack_sockaddr_in($port, $ip_address);
$sock->bind($packed_addr);
```
Binds a network address to a socket, just as `bind(2)` does. Returns true if it succeeded, false otherwise. You should provide a packed address of the appropriate type for the socket.
### connected
```
my $peer_addr = $sock->connected();
if ($peer_addr) {
say "We're connected to $peer_addr";
}
```
If the socket is in a connected state, the peer address is returned. If the socket is not in a connected state, `undef` is returned.
Note that this method considers a half-open TCP socket to be "in a connected state". Specifically, it does not distinguish between the **ESTABLISHED** and **CLOSE-WAIT** TCP states; it returns the peer address, rather than `undef`, in either case. Thus, in general, it cannot be used to reliably learn whether the peer has initiated a graceful shutdown because in most cases (see below) the local TCP state machine remains in **CLOSE-WAIT** until the local application calls ["shutdown" in IO::Socket](IO::Socket#shutdown) or `close`. Only at that point does this function return `undef`.
The "in most cases" hedge is because local TCP state machine behavior may depend on the peer's socket options. In particular, if the peer socket has `SO_LINGER` enabled with a zero timeout, then the peer's `close` will generate a `RST` segment. Upon receipt of that segment, the local TCP transitions immediately to **CLOSED**, and in that state, this method *will* return `undef`.
### getsockopt
```
my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
say "Receive buffer is $buf bytes";
```
Get an option associated with the socket. Levels other than `SOL_SOCKET` may be specified here. As a convenience, this method will unpack a byte buffer of the correct size back into a number.
### listen
```
$sock->listen(5);
```
Does the same thing that the `listen(2)` system call does. Returns true if it succeeded, false otherwise. Listens to a socket with a given queue size.
### peername
```
my $sockaddr_in = $sock->peername();
```
Returns the packed `sockaddr` address of the other end of the socket connection. It calls `getpeername`.
### protocol
```
my $proto = $sock->protocol();
```
Returns the number for the protocol being used on the socket, if known. If the protocol is unknown, as with an `AF_UNIX` socket, zero is returned.
### recv
```
my $buffer = "";
my $length = 1024;
my $flags = 0; # default. optional
$sock->recv($buffer, $length);
$sock->recv($buffer, $length, $flags);
```
Similar in functionality to ["recv" in perlfunc](perlfunc#recv).
Receives a message on a socket. Attempts to receive `$length` characters of data into `$buffer` from the specified socket. `$buffer` will be grown or shrunk to the length actually read. Takes the same flags as the system call of the same name. Returns the address of the sender if socket's protocol supports this; returns an empty string otherwise. If there's an error, returns `undef`. This call is actually implemented in terms of the `recvfrom(2)` system call.
Flags are ORed together values, such as `MSG_BCAST`, `MSG_OOB`, `MSG_TRUNC`. The default value for the flags is `0`.
The cached value of ["peername" in IO::Socket](IO::Socket#peername) is updated with the result of `recv`.
**Note:** In Perl v5.30 and newer, if the socket has been marked as `:utf8`, `recv` will throw an exception. The `:encoding(...)` layer implicitly introduces the `:utf8` layer. See ["binmode" in perlfunc](perlfunc#binmode).
**Note:** In Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using ["binmode" in perlfunc](perlfunc#binmode) to operate with the `:encoding(UTF-8)` I/O layer (see the ["open" in perlfunc](perlfunc#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.
### send
```
my $message = "Hello, world!";
my $flags = 0; # defaults to zero
my $to = '0.0.0.0'; # optional destination
my $sent = $sock->send($message);
$sent = $sock->send($message, $flags);
$sent = $sock->send($message, $flags, $to);
```
Similar in functionality to ["send" in perlfunc](perlfunc#send).
Sends a message on a socket. Attempts to send the scalar message to the socket. Takes the same flags as the system call of the same name. On unconnected sockets, you must specify a destination to send to, in which case it does a `sendto(2)` syscall. Returns the number of characters sent, or `undef` on error. The `sendmsg(2)` syscall is currently unimplemented.
The `flags` option is optional and defaults to `0`.
After a successful send with `$to`, further calls to `send` on an unconnected socket without `$to` will send to the same address, and `$to` will be used as the result of ["peername" in IO::Socket](IO::Socket#peername).
**Note:** In Perl v5.30 and newer, if the socket has been marked as `:utf8`, `send` will throw an exception. The `:encoding(...)` layer implicitly introduces the `:utf8` layer. See ["binmode" in perlfunc](perlfunc#binmode).
**Note:** In Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are sent. By default all sockets operate on bytes, but for example if the socket has been changed using ["binmode" in perlfunc](perlfunc#binmode) to operate with the `:encoding(UTF-8)` I/O layer (see the ["open" in perlfunc](perlfunc#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 sent.
### setsockopt
```
$sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
$sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);
```
Set option associated with the socket. Levels other than `SOL_SOCKET` may be specified here. As a convenience, this method will convert a number into a packed byte buffer.
### shutdown
```
$sock->shutdown(SHUT_RD); # we stopped reading data
$sock->shutdown(SHUT_WR); # we stopped writing data
$sock->shutdown(SHUT_RDWR); # we stopped using this socket
```
Shuts down a socket connection in the manner indicated by the value passed in, which has the same interpretation as in the syscall of the same name.
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 socket is not a valid filehandle, or returns `0` and sets `$!` for any other failure.
### sockdomain
```
my $domain = $sock->sockdomain();
```
Returns the number for the socket domain type. For example, for an `AF_INET` socket the value of `&AF_INET` will be returned.
### socket
```
my $sock = IO::Socket->new(); # no values given
# now let's actually get a socket with the socket method
# domain, type, and protocol are required
$sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');
```
Opens a socket of the specified kind and returns it. Domain, type, and protocol are specified the same as for the syscall of the same name.
### socketpair
```
my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
($r, $w) = IO::Socket::UNIX
->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
```
Will return a list of two sockets created (read and write), or an empty list on failure.
Differs slightly from `socketpair` in <perlfunc> in that the argument list is a bit simpler.
### sockname
```
my $packed_addr = $sock->sockname();
```
Returns the packed `sockaddr` address of this end of the connection. It's the same as `getsockname(2)`.
### sockopt
```
my $value = $sock->sockopt(SO_REUSEADDR);
$sock->sockopt(SO_REUSEADDR, 1);
```
Unified method to both set and get options in the `SOL_SOCKET` level. If called with one argument then ["getsockopt" in IO::Socket](IO::Socket#getsockopt) is called, otherwise ["setsockopt" in IO::Socket](IO::Socket#setsockopt) is called.
### socktype
```
my $type = $sock->socktype();
```
Returns the number for the socket type. For example, for a `SOCK_STREAM` socket the value of `&SOCK_STREAM` will be returned.
### timeout
```
my $seconds = $sock->timeout();
my $old_val = $sock->timeout(5); # set new and return old value
```
Set or get the timeout value (in seconds) associated with this socket. If called without any arguments then the current setting is returned. If called with an argument the current setting is changed and the previous value returned.
This method is available to all `IO::Socket` implementations but may or may not be used by the individual domain subclasses.
EXAMPLES
--------
Let's create a TCP server on `localhost:3333`.
```
use strict;
use warnings;
use feature 'say';
use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
my $server = IO::Socket->new(
Domain => AF_INET,
Type => SOCK_STREAM,
Proto => 'tcp',
LocalHost => '0.0.0.0',
LocalPort => 3333,
ReusePort => 1,
Listen => 5,
) || die "Can't open socket: $IO::Socket::errstr";
say "Waiting on 3333";
while (1) {
# waiting for a new client connection
my $client = $server->accept();
# get information about a newly connected client
my $client_address = $client->peerhost();
my $client_port = $client->peerport();
say "Connection from $client_address:$client_port";
# read up to 1024 characters from the connected client
my $data = "";
$client->recv($data, 1024);
say "received data: $data";
# write response data to the connected client
$data = "ok";
$client->send($data);
# notify client that response has been sent
$client->shutdown(SHUT_WR);
}
$server->close();
```
A client for such a server could be
```
use strict;
use warnings;
use feature 'say';
use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
my $client = IO::Socket->new(
Domain => AF_INET,
Type => SOCK_STREAM,
proto => 'tcp',
PeerPort => 3333,
PeerHost => '0.0.0.0',
) || die "Can't open socket: $IO::Socket::errstr";
say "Sending Hello World!";
my $size = $client->send("Hello World!");
say "Sent data of length: $size";
$client->shutdown(SHUT_WR);
my $buffer;
$client->recv($buffer, 1024);
say "Got back $buffer";
$client->close();
```
LIMITATIONS
-----------
On some systems, for an IO::Socket object created with `new_from_fd`, or created with ["accept" in IO::Socket](IO::Socket#accept) from such an object, the ["protocol" in IO::Socket](IO::Socket#protocol), ["sockdomain" in IO::Socket](IO::Socket#sockdomain) and ["socktype" in IO::Socket](IO::Socket#socktype) methods may return `undef`.
SEE ALSO
---------
[Socket](socket), <IO::Handle>, <IO::Socket::INET>, <IO::Socket::UNIX>, <IO::Socket::IP>
AUTHOR
------
Graham Barr. atmark() by Lincoln Stein. Currently maintained by the Perl 5 Porters. Please report all bugs at <https://github.com/Perl/perl5/issues>.
COPYRIGHT
---------
Copyright (c) 1997-8 Graham Barr <[email protected]>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The atmark() implementation: Copyright 2001, Lincoln Stein <[email protected]>. This module is distributed under the same terms as Perl itself. Feel free to use, modify and redistribute it as long as you retain the correct attribution.
perl DirHandle DirHandle
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
DirHandle - (obsolete) supply object methods for directory handles
SYNOPSIS
--------
```
# recommended approach since Perl 5.6: do not use DirHandle
if (opendir my $d, '.') {
while (readdir $d) { something($_); }
rewind $d;
while (readdir $d) { something_else($_); }
}
# how you would use this module if you were going to
use DirHandle;
if (my $d = DirHandle->new(".")) {
while (defined($_ = $d->read)) { something($_); }
$d->rewind;
while (defined($_ = $d->read)) { something_else($_); }
}
```
DESCRIPTION
-----------
**There is no reason to use this module nowadays.**
The `DirHandle` method provide an alternative interface to the opendir(), closedir(), readdir(), and rewinddir() functions.
Up to Perl 5.5, opendir() could not autovivify a directory handle from `undef`, so using a lexical handle required using a function from [Symbol](symbol) to create an anonymous glob, which took a separate step. `DirHandle` encapsulates this, which allowed cleaner code than opendir(). Since Perl 5.6, opendir() alone has been all you need for lexical handles.
| programming_docs |
perl CPAN::Meta::Merge CPAN::Meta::Merge
=================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [new](#new)
+ [merge(@fragments)](#merge(@fragments))
* [MERGE STRATEGIES](#MERGE-STRATEGIES)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
CPAN::Meta::Merge - Merging CPAN Meta fragments
VERSION
-------
version 2.150010
SYNOPSIS
--------
```
my $merger = CPAN::Meta::Merge->new(default_version => "2");
my $meta = $merger->merge($base, @additional);
```
DESCRIPTION
-----------
METHODS
-------
### new
This creates a CPAN::Meta::Merge object. It takes one mandatory named argument, `version`, declaring the version of the meta-spec that must be used for the merge. It can optionally take an `extra_mappings` argument that allows one to add additional merging functions for specific elements.
The `extra_mappings` arguments takes a hash ref with the same type of structure as described in <CPAN::Meta::Spec>, except with its values as one of the [defined merge strategies](#MERGE-STRATEGIES) or a code ref to a merging function.
```
my $merger = CPAN::Meta::Merge->new(
default_version => '2',
extra_mappings => {
'optional_features' => \&custom_merge_function,
'x_custom' => 'set_addition',
'x_meta_meta' => {
name => 'identical',
tags => 'set_addition',
}
}
);
```
###
merge(@fragments)
Merge all `@fragments` together. It will accept both CPAN::Meta objects and (possibly incomplete) hashrefs of metadata.
MERGE STRATEGIES
-----------------
`merge` uses various strategies to combine different elements of the CPAN::Meta objects. The following strategies can be used with the extra\_mappings argument of `new`:
identical The elements must be identical
set\_addition The union of two array refs
```
[ a, b ] U [ a, c] = [ a, b, c ]
```
uniq\_map Key value pairs from the right hash are merged to the left hash. Key collisions are only allowed if their values are the same. This merge function will recurse into nested hash refs following the same merge rules.
improvise This merge strategy will try to pick the appropriate predefined strategy based on what element type. Array refs will try to use the `set_addition` strategy, Hash refs will try to use the `uniq_map` strategy, and everything else will try the `identical` strategy.
AUTHORS
-------
* David Golden <[email protected]>
* Ricardo Signes <[email protected]>
* Adam Kennedy <[email protected]>
COPYRIGHT AND LICENSE
----------------------
This software is copyright (c) 2010 by David Golden, Ricardo Signes, Adam Kennedy and Contributors.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
perl perlutil perlutil
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [LIST OF UTILITIES](#LIST-OF-UTILITIES)
+ [Documentation](#Documentation)
+ [Converters](#Converters)
+ [Administration](#Administration)
+ [Development](#Development)
+ [General tools](#General-tools)
+ [Installation](#Installation)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlutil - utilities packaged with the Perl distribution
DESCRIPTION
-----------
Along with the Perl interpreter itself, the Perl distribution installs a range of utilities on your system. There are also several utilities which are used by the Perl distribution itself as part of the install process. This document exists to list all of these utilities, explain what they are for and provide pointers to each module's documentation, if appropriate.
LIST OF UTILITIES
------------------
### Documentation
<perldoc> The main interface to Perl's documentation is *perldoc*, although if you're reading this, it's more than likely that you've already found it. *perldoc* will extract and format the documentation from any file in the current directory, any Perl module installed on the system, or any of the standard documentation pages, such as this one. Use `perldoc <name>` to get information on any of the utilities described in this document.
<pod2man> <pod2text> If it's run from a terminal, *perldoc* will usually call *pod2man* to translate POD (Plain Old Documentation - see <perlpod> for an explanation) into a manpage, and then run *man* to display it; if *man* isn't available, *pod2text* will be used instead and the output piped through your favourite pager.
<pod2html> As well as these two, there is another converter: *pod2html* will produce HTML pages from POD.
<pod2usage> If you just want to know how to use the utilities described here, *pod2usage* will just extract the "USAGE" section; some of the utilities will automatically call *pod2usage* on themselves when you call them with `-help`.
<podchecker> If you're writing your own documentation in POD, the *podchecker* utility will look for errors in your markup.
<splain> *splain* is an interface to <perldiag> - paste in your error message to it, and it'll explain it for you.
*roffitall* The *roffitall* utility is not installed on your system but lives in the *pod/* directory of your Perl source kit; it converts all the documentation from the distribution to *\*roff* format, and produces a typeset PostScript or text file of the whole lot.
### Converters
<pl2pm> To help you convert legacy programs to more modern Perl, the *pl2pm* utility will help you convert old-style Perl 4 libraries to new-style Perl5 modules.
### Administration
<libnetcfg> To display and change the libnet configuration run the libnetcfg command.
<perlivp> The *perlivp* program is set up at Perl source code build time to test the Perl version it was built under. It can be used after running `make install` (or your platform's equivalent procedure) to verify that perl and its libraries have been installed correctly.
### Development
There are a set of utilities which help you in developing Perl programs, and in particular, extending Perl with C.
<perlbug> *perlbug* used to be the recommended way to report bugs in the perl interpreter itself or any of the standard library modules back to the developers; bug reports and patches should now be submitted to <https://github.com/Perl/perl5/issues>.
[perlthanks](perlbug) This program provides an easy way to send a thank-you message back to the authors and maintainers of perl. It's just *perlbug* installed under another name.
<h2ph> Back before Perl had the XS system for connecting with C libraries, programmers used to get library constants by reading through the C header files. You may still see `require 'syscall.ph'` or similar around - the *.ph* file should be created by running *h2ph* on the corresponding *.h* file. See the *h2ph* documentation for more on how to convert a whole bunch of header files at once.
<h2xs> *h2xs* converts C header files into XS modules, and will try and write as much glue between C libraries and Perl modules as it can. It's also very useful for creating skeletons of pure Perl modules.
<enc2xs> *enc2xs* builds a Perl extension for use by Encode from either Unicode Character Mapping files (.ucm) or Tcl Encoding Files (.enc). Besides being used internally during the build process of the Encode module, you can use *enc2xs* to add your own encoding to perl. No knowledge of XS is necessary.
<xsubpp> *xsubpp* is a compiler to convert Perl XS code into C code. It is typically run by the makefiles created by <ExtUtils::MakeMaker>.
*xsubpp* will compile XS code into C code by embedding the constructs necessary to let C functions manipulate Perl values and creates the glue necessary to let Perl access those functions.
<prove> *prove* is a command-line interface to the test-running functionality of <Test::Harness>. It's an alternative to `make test`.
<corelist> A command-line front-end to <Module::CoreList>, to query what modules were shipped with given versions of perl.
###
General tools
A few general-purpose tools are shipped with perl, mostly because they came along modules included in the perl distribution.
<encguess> *encguess* will attempt to guess the character encoding of files.
<json_pp> *json\_pp* is a pure Perl JSON converter and formatter.
<piconv> *piconv* is a Perl version of [iconv(1)](http://man.he.net/man1/iconv), a character encoding converter widely available for various Unixen today. This script was primarily a technology demonstrator for Perl v5.8.0, but you can use piconv in the place of iconv for virtually any case.
<ptar> *ptar* is a tar-like program, written in pure Perl.
<ptardiff> *ptardiff* is a small utility that produces a diff between an extracted archive and an unextracted one. (Note that this utility requires the <Text::Diff> module to function properly; this module isn't distributed with perl, but is available from the CPAN.)
<ptargrep> *ptargrep* is a utility to apply pattern matching to the contents of files in a tar archive.
<shasum> This utility, that comes with the <Digest::SHA> module, is used to print or verify SHA checksums.
<streamzip> *streamzip* compresses data streamed to STDIN into a streamed zip container.
<zipdetails> *zipdetails* displays information about the internal record structure of the zip file. It is not concerned with displaying any details of the compressed data stored in the zip file.
### Installation
These utilities help manage extra Perl modules that don't come with the perl distribution.
<cpan> *cpan* is a command-line interface to CPAN.pm. It allows you to install modules or distributions from CPAN, or just get information about them, and a lot more. It is similar to the command line mode of the [CPAN](cpan) module,
```
perl -MCPAN -e shell
```
<instmodsh> A little interface to <ExtUtils::Installed> to examine installed modules, validate your packlists and even create a tarball from an installed module.
SEE ALSO
---------
<perldoc>, <pod2man>, <pod2text>, <pod2html>, <pod2usage>, <podchecker>, <splain>, <pl2pm>, <perlbug>, <h2ph>, <h2xs>, <enc2xs>, <xsubpp>, <cpan>, <encguess>, <instmodsh>, <json_pp>, <piconv>, <prove>, <corelist>, <ptar>, <ptardiff>, <shasum>, <streamzip>, <zipdetails>
perl ptar ptar
====
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [OPTIONS](#OPTIONS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ptar - a tar-like program written in perl
DESCRIPTION
-----------
ptar is a small, tar look-alike program that uses the perl module Archive::Tar to extract, create and list tar archives.
SYNOPSIS
--------
```
ptar -c [-v] [-z] [-C] [-f ARCHIVE_FILE | -] FILE FILE ...
ptar -c [-v] [-z] [-C] [-T index | -] [-f ARCHIVE_FILE | -]
ptar -x [-v] [-z] [-f ARCHIVE_FILE | -]
ptar -t [-z] [-f ARCHIVE_FILE | -]
ptar -h
```
OPTIONS
-------
```
c Create ARCHIVE_FILE or STDOUT (-) from FILE
x Extract from ARCHIVE_FILE or STDIN (-)
t List the contents of ARCHIVE_FILE or STDIN (-)
f Name of the ARCHIVE_FILE to use. Default is './default.tar'
z Read/Write zlib compressed ARCHIVE_FILE (not always available)
v Print filenames as they are added or extracted from ARCHIVE_FILE
h Prints this help message
C CPAN mode - drop 022 from permissions
T get names to create from file
```
SEE ALSO
---------
[tar(1)](http://man.he.net/man1/tar), <Archive::Tar>.
perl perlipc perlipc
=======
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [Signals](#Signals)
+ [Handling the SIGHUP Signal in Daemons](#Handling-the-SIGHUP-Signal-in-Daemons)
+ [Deferred Signals (Safe Signals)](#Deferred-Signals-(Safe-Signals))
* [Named Pipes](#Named-Pipes)
* [Using open() for IPC](#Using-open()-for-IPC)
+ [Filehandles](#Filehandles)
+ [Background Processes](#Background-Processes)
+ [Complete Dissociation of Child from Parent](#Complete-Dissociation-of-Child-from-Parent)
+ [Safe Pipe Opens](#Safe-Pipe-Opens)
+ [Avoiding Pipe Deadlocks](#Avoiding-Pipe-Deadlocks)
+ [Bidirectional Communication with Another Process](#Bidirectional-Communication-with-Another-Process)
+ [Bidirectional Communication with Yourself](#Bidirectional-Communication-with-Yourself)
* [Sockets: Client/Server Communication](#Sockets:-Client/Server-Communication)
+ [Internet Line Terminators](#Internet-Line-Terminators)
+ [Internet TCP Clients and Servers](#Internet-TCP-Clients-and-Servers)
+ [Unix-Domain TCP Clients and Servers](#Unix-Domain-TCP-Clients-and-Servers)
* [TCP Clients with IO::Socket](#TCP-Clients-with-IO::Socket)
+ [A Simple Client](#A-Simple-Client)
+ [A Webget Client](#A-Webget-Client)
+ [Interactive Client with IO::Socket](#Interactive-Client-with-IO::Socket)
* [TCP Servers with IO::Socket](#TCP-Servers-with-IO::Socket)
* [UDP: Message Passing](#UDP:-Message-Passing)
* [SysV IPC](#SysV-IPC)
* [NOTES](#NOTES)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)
DESCRIPTION
-----------
The basic IPC facilities of Perl are built out of the good old Unix signals, named pipes, pipe opens, the Berkeley socket routines, and SysV IPC calls. Each is used in slightly different situations.
Signals
-------
Perl uses a simple signal handling model: the %SIG hash contains names or references of user-installed signal handlers. These handlers will be called with an argument which is the name of the signal that triggered it. A signal may be generated intentionally from a particular keyboard sequence like control-C or control-Z, sent to you from another process, or triggered automatically by the kernel when special events transpire, like a child process exiting, your own process running out of stack space, or hitting a process file-size limit.
For example, to trap an interrupt signal, set up a handler like this:
```
our $shucks;
sub catch_zap {
my $signame = shift;
$shucks++;
die "Somebody sent me a SIG$signame";
}
$SIG{INT} = __PACKAGE__ . "::catch_zap";
$SIG{INT} = \&catch_zap; # best strategy
```
Prior to Perl 5.8.0 it was necessary to do as little as you possibly could in your handler; notice how all we do is set a global variable and then raise an exception. That's because on most systems, libraries are not re-entrant; particularly, memory allocation and I/O routines are not. That meant that doing nearly *anything* in your handler could in theory trigger a memory fault and subsequent core dump - see ["Deferred Signals (Safe Signals)"](#Deferred-Signals-%28Safe-Signals%29) below.
The names of the signals are the ones listed out by `kill -l` on your system, or you can retrieve them using the CPAN module <IPC::Signal>.
You may also choose to assign the strings `"IGNORE"` or `"DEFAULT"` as the handler, in which case Perl will try to discard the signal or do the default thing.
On most Unix platforms, the `CHLD` (sometimes also known as `CLD`) signal has special behavior with respect to a value of `"IGNORE"`. Setting `$SIG{CHLD}` to `"IGNORE"` on such a platform has the effect of not creating zombie processes when the parent process fails to `wait()` on its child processes (i.e., child processes are automatically reaped). Calling `wait()` with `$SIG{CHLD}` set to `"IGNORE"` usually returns `-1` on such platforms.
Some signals can be neither trapped nor ignored, such as the KILL and STOP (but not the TSTP) signals. Note that ignoring signals makes them disappear. If you only want them blocked temporarily without them getting lost you'll have to use the `POSIX` module's [sigprocmask](posix#sigprocmask).
Sending a signal to a negative process ID means that you send the signal to the entire Unix process group. This code sends a hang-up signal to all processes in the current process group, and also sets $SIG{HUP} to `"IGNORE"` so it doesn't kill itself:
```
# block scope for local
{
local $SIG{HUP} = "IGNORE";
kill HUP => -getpgrp();
# snazzy writing of: kill("HUP", -getpgrp())
}
```
Another interesting signal to send is signal number zero. This doesn't actually affect a child process, but instead checks whether it's alive or has changed its UIDs.
```
unless (kill 0 => $kid_pid) {
warn "something wicked happened to $kid_pid";
}
```
Signal number zero may fail because you lack permission to send the signal when directed at a process whose real or saved UID is not identical to the real or effective UID of the sending process, even though the process is alive. You may be able to determine the cause of failure using `$!` or `%!`.
```
unless (kill(0 => $pid) || $!{EPERM}) {
warn "$pid looks dead";
}
```
You might also want to employ anonymous functions for simple signal handlers:
```
$SIG{INT} = sub { die "\nOutta here!\n" };
```
SIGCHLD handlers require some special care. If a second child dies while in the signal handler caused by the first death, we won't get another signal. So must loop here else we will leave the unreaped child as a zombie. And the next time two children die we get another zombie. And so on.
```
use POSIX ":sys_wait_h";
$SIG{CHLD} = sub {
while ((my $child = waitpid(-1, WNOHANG)) > 0) {
$Kid_Status{$child} = $?;
}
};
# do something that forks...
```
Be careful: qx(), system(), and some modules for calling external commands do a fork(), then wait() for the result. Thus, your signal handler will be called. Because wait() was already called by system() or qx(), the wait() in the signal handler will see no more zombies and will therefore block.
The best way to prevent this issue is to use waitpid(), as in the following example:
```
use POSIX ":sys_wait_h"; # for nonblocking read
my %children;
$SIG{CHLD} = sub {
# don't change $! and $? outside handler
local ($!, $?);
while ( (my $pid = waitpid(-1, WNOHANG)) > 0 ) {
delete $children{$pid};
cleanup_child($pid, $?);
}
};
while (1) {
my $pid = fork();
die "cannot fork" unless defined $pid;
if ($pid == 0) {
# ...
exit 0;
} else {
$children{$pid}=1;
# ...
system($command);
# ...
}
}
```
Signal handling is also used for timeouts in Unix. While safely protected within an `eval{}` block, you set a signal handler to trap alarm signals and then schedule to have one delivered to you in some number of seconds. Then try your blocking operation, clearing the alarm when it's done but not before you've exited your `eval{}` block. If it goes off, you'll use die() to jump out of the block.
Here's an example:
```
my $ALARM_EXCEPTION = "alarm clock restart";
eval {
local $SIG{ALRM} = sub { die $ALARM_EXCEPTION };
alarm 10;
flock($fh, 2) # blocking write lock
|| die "cannot flock: $!";
alarm 0;
};
if ($@ && $@ !~ quotemeta($ALARM_EXCEPTION)) { die }
```
If the operation being timed out is system() or qx(), this technique is liable to generate zombies. If this matters to you, you'll need to do your own fork() and exec(), and kill the errant child process.
For more complex signal handling, you might see the standard POSIX module. Lamentably, this is almost entirely undocumented, but the *ext/POSIX/t/sigaction.t* file from the Perl source distribution has some examples in it.
###
Handling the SIGHUP Signal in Daemons
A process that usually starts when the system boots and shuts down when the system is shut down is called a daemon (Disk And Execution MONitor). If a daemon process has a configuration file which is modified after the process has been started, there should be a way to tell that process to reread its configuration file without stopping the process. Many daemons provide this mechanism using a `SIGHUP` signal handler. When you want to tell the daemon to reread the file, simply send it the `SIGHUP` signal.
The following example implements a simple daemon, which restarts itself every time the `SIGHUP` signal is received. The actual code is located in the subroutine `code()`, which just prints some debugging info to show that it works; it should be replaced with the real code.
```
#!/usr/bin/perl
use v5.36;
use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions qw(catfile);
$| = 1;
# make the daemon cross-platform, so exec always calls the script
# itself with the right path, no matter how the script was invoked.
my $script = File::Basename::basename($0);
my $SELF = catfile($FindBin::Bin, $script);
# POSIX unmasks the sigprocmask properly
$SIG{HUP} = sub {
print "got SIGHUP\n";
exec($SELF, @ARGV) || die "$0: couldn't restart: $!";
};
code();
sub code {
print "PID: $$\n";
print "ARGV: @ARGV\n";
my $count = 0;
while (1) {
sleep 2;
print ++$count, "\n";
}
}
```
###
Deferred Signals (Safe Signals)
Before Perl 5.8.0, installing Perl code to deal with signals exposed you to danger from two things. First, few system library functions are re-entrant. If the signal interrupts while Perl is executing one function (like malloc(3) or printf(3)), and your signal handler then calls the same function again, you could get unpredictable behavior--often, a core dump. Second, Perl isn't itself re-entrant at the lowest levels. If the signal interrupts Perl while Perl is changing its own internal data structures, similarly unpredictable behavior may result.
There were two things you could do, knowing this: be paranoid or be pragmatic. The paranoid approach was to do as little as possible in your signal handler. Set an existing integer variable that already has a value, and return. This doesn't help you if you're in a slow system call, which will just restart. That means you have to `die` to longjmp(3) out of the handler. Even this is a little cavalier for the true paranoiac, who avoids `die` in a handler because the system *is* out to get you. The pragmatic approach was to say "I know the risks, but prefer the convenience", and to do anything you wanted in your signal handler, and be prepared to clean up core dumps now and again.
Perl 5.8.0 and later avoid these problems by "deferring" signals. That is, when the signal is delivered to the process by the system (to the C code that implements Perl) a flag is set, and the handler returns immediately. Then at strategic "safe" points in the Perl interpreter (e.g. when it is about to execute a new opcode) the flags are checked and the Perl level handler from %SIG is executed. The "deferred" scheme allows much more flexibility in the coding of signal handlers as we know the Perl interpreter is in a safe state, and that we are not in a system library function when the handler is called. However the implementation does differ from previous Perls in the following ways:
Long-running opcodes As the Perl interpreter looks at signal flags only when it is about to execute a new opcode, a signal that arrives during a long-running opcode (e.g. a regular expression operation on a very large string) will not be seen until the current opcode completes.
If a signal of any given type fires multiple times during an opcode (such as from a fine-grained timer), the handler for that signal will be called only once, after the opcode completes; all other instances will be discarded. Furthermore, if your system's signal queue gets flooded to the point that there are signals that have been raised but not yet caught (and thus not deferred) at the time an opcode completes, those signals may well be caught and deferred during subsequent opcodes, with sometimes surprising results. For example, you may see alarms delivered even after calling `alarm(0)` as the latter stops the raising of alarms but does not cancel the delivery of alarms raised but not yet caught. Do not depend on the behaviors described in this paragraph as they are side effects of the current implementation and may change in future versions of Perl.
Interrupting IO When a signal is delivered (e.g., SIGINT from a control-C) the operating system breaks into IO operations like *read*(2), which is used to implement Perl's readline() function, the `<>` operator. On older Perls the handler was called immediately (and as `read` is not "unsafe", this worked well). With the "deferred" scheme the handler is *not* called immediately, and if Perl is using the system's `stdio` library that library may restart the `read` without returning to Perl to give it a chance to call the %SIG handler. If this happens on your system the solution is to use the `:perlio` layer to do IO--at least on those handles that you want to be able to break into with signals. (The `:perlio` layer checks the signal flags and calls %SIG handlers before resuming IO operation.)
The default in Perl 5.8.0 and later is to automatically use the `:perlio` layer.
Note that it is not advisable to access a file handle within a signal handler where that signal has interrupted an I/O operation on that same handle. While perl will at least try hard not to crash, there are no guarantees of data integrity; for example, some data might get dropped or written twice.
Some networking library functions like gethostbyname() are known to have their own implementations of timeouts which may conflict with your timeouts. If you have problems with such functions, try using the POSIX sigaction() function, which bypasses Perl safe signals. Be warned that this does subject you to possible memory corruption, as described above.
Instead of setting `$SIG{ALRM}`:
```
local $SIG{ALRM} = sub { die "alarm" };
```
try something like the following:
```
use POSIX qw(SIGALRM);
POSIX::sigaction(SIGALRM,
POSIX::SigAction->new(sub { die "alarm" }))
|| die "Error setting SIGALRM handler: $!\n";
```
Another way to disable the safe signal behavior locally is to use the `Perl::Unsafe::Signals` module from CPAN, which affects all signals.
Restartable system calls On systems that supported it, older versions of Perl used the SA\_RESTART flag when installing %SIG handlers. This meant that restartable system calls would continue rather than returning when a signal arrived. In order to deliver deferred signals promptly, Perl 5.8.0 and later do *not* use SA\_RESTART. Consequently, restartable system calls can fail (with $! set to `EINTR`) in places where they previously would have succeeded.
The default `:perlio` layer retries `read`, `write` and `close` as described above; interrupted `wait` and `waitpid` calls will always be retried.
Signals as "faults" Certain signals like SEGV, ILL, BUS and FPE are generated by virtual memory addressing errors and similar "faults". These are normally fatal: there is little a Perl-level handler can do with them. So Perl delivers them immediately rather than attempting to defer them.
It is possible to catch these with a `%SIG` handler (see <perlvar>), but on top of the usual problems of "unsafe" signals the signal is likely to get rethrown immediately on return from the signal handler, so such a handler should `die` or `exit` instead.
Signals triggered by operating system state On some operating systems certain signal handlers are supposed to "do something" before returning. One example can be CHLD or CLD, which indicates a child process has completed. On some operating systems the signal handler is expected to `wait` for the completed child process. On such systems the deferred signal scheme will not work for those signals: it does not do the `wait`. Again the failure will look like a loop as the operating system will reissue the signal because there are completed child processes that have not yet been `wait`ed for.
If you want the old signal behavior back despite possible memory corruption, set the environment variable `PERL_SIGNALS` to `"unsafe"`. This feature first appeared in Perl 5.8.1.
Named Pipes
------------
A named pipe (often referred to as a FIFO) is an old Unix IPC mechanism for processes communicating on the same machine. It works just like regular anonymous pipes, except that the processes rendezvous using a filename and need not be related.
To create a named pipe, use the `POSIX::mkfifo()` function.
```
use POSIX qw(mkfifo);
mkfifo($path, 0700) || die "mkfifo $path failed: $!";
```
You can also use the Unix command mknod(1), or on some systems, mkfifo(1). These may not be in your normal path, though.
```
# system return val is backwards, so && not ||
#
$ENV{PATH} .= ":/etc:/usr/etc";
if ( system("mknod", $path, "p")
&& system("mkfifo", $path) )
{
die "mk{nod,fifo} $path failed";
}
```
A fifo is convenient when you want to connect a process to an unrelated one. When you open a fifo, the program will block until there's something on the other end.
For example, let's say you'd like to have your *.signature* file be a named pipe that has a Perl program on the other end. Now every time any program (like a mailer, news reader, finger program, etc.) tries to read from that file, the reading program will read the new signature from your program. We'll use the pipe-checking file-test operator, **-p**, to find out whether anyone (or anything) has accidentally removed our fifo.
```
chdir(); # go home
my $FIFO = ".signature";
while (1) {
unless (-p $FIFO) {
unlink $FIFO; # discard any failure, will catch later
require POSIX; # delayed loading of heavy module
POSIX::mkfifo($FIFO, 0700)
|| die "can't mkfifo $FIFO: $!";
}
# next line blocks till there's a reader
open (my $fh, ">", $FIFO) || die "can't open $FIFO: $!";
print $fh "John Smith (smith\@host.org)\n", `fortune -s`;
close($fh) || die "can't close $FIFO: $!";
sleep 2; # to avoid dup signals
}
```
Using open() for IPC
---------------------
Perl's basic open() statement can also be used for unidirectional interprocess communication by specifying the open mode as `|-` or `-|`. Here's how to start something up in a child process you intend to write to:
```
open(my $spooler, "|-", "cat -v | lpr -h 2>/dev/null")
|| die "can't fork: $!";
local $SIG{PIPE} = sub { die "spooler pipe broke" };
print $spooler "stuff\n";
close $spooler || die "bad spool: $! $?";
```
And here's how to start up a child process you intend to read from:
```
open(my $status, "-|", "netstat -an 2>&1")
|| die "can't fork: $!";
while (<$status>) {
next if /^(tcp|udp)/;
print;
}
close $status || die "bad netstat: $! $?";
```
Be aware that these operations are full Unix forks, which means they may not be correctly implemented on all alien systems. See ["open" in perlport](perlport#open) for portability details.
In the two-argument form of open(), a pipe open can be achieved by either appending or prepending a pipe symbol to the second argument:
```
open(my $spooler, "| cat -v | lpr -h 2>/dev/null")
|| die "can't fork: $!";
open(my $status, "netstat -an 2>&1 |")
|| die "can't fork: $!";
```
This can be used even on systems that do not support forking, but this possibly allows code intended to read files to unexpectedly execute programs. If one can be sure that a particular program is a Perl script expecting filenames in @ARGV using the two-argument form of open() or the `<>` operator, the clever programmer can write something like this:
```
% program f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
```
and no matter which sort of shell it's called from, the Perl program will read from the file *f1*, the process *cmd1*, standard input (*tmpfile* in this case), the *f2* file, the *cmd2* command, and finally the *f3* file. Pretty nifty, eh?
You might notice that you could use backticks for much the same effect as opening a pipe for reading:
```
print grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;
die "bad netstatus ($?)" if $?;
```
While this is true on the surface, it's much more efficient to process the file one line or record at a time because then you don't have to read the whole thing into memory at once. It also gives you finer control of the whole process, letting you kill off the child process early if you'd like.
Be careful to check the return values from both open() and close(). If you're *writing* to a pipe, you should also trap SIGPIPE. Otherwise, think of what happens when you start up a pipe to a command that doesn't exist: the open() will in all likelihood succeed (it only reflects the fork()'s success), but then your output will fail--spectacularly. Perl can't know whether the command worked, because your command is actually running in a separate process whose exec() might have failed. Therefore, while readers of bogus commands return just a quick EOF, writers to bogus commands will get hit with a signal, which they'd best be prepared to handle. Consider:
```
open(my $fh, "|-", "bogus") || die "can't fork: $!";
print $fh "bang\n"; # neither necessary nor sufficient
# to check print retval!
close($fh) || die "can't close: $!";
```
The reason for not checking the return value from print() is because of pipe buffering; physical writes are delayed. That won't blow up until the close, and it will blow up with a SIGPIPE. To catch it, you could use this:
```
$SIG{PIPE} = "IGNORE";
open(my $fh, "|-", "bogus") || die "can't fork: $!";
print $fh "bang\n";
close($fh) || die "can't close: status=$?";
```
### Filehandles
Both the main process and any child processes it forks share the same STDIN, STDOUT, and STDERR filehandles. If both processes try to access them at once, strange things can happen. You may also want to close or reopen the filehandles for the child. You can get around this by opening your pipe with open(), but on some systems this means that the child process cannot outlive the parent.
###
Background Processes
You can run a command in the background with:
```
system("cmd &");
```
The command's STDOUT and STDERR (and possibly STDIN, depending on your shell) will be the same as the parent's. You won't need to catch SIGCHLD because of the double-fork taking place; see below for details.
###
Complete Dissociation of Child from Parent
In some cases (starting server processes, for instance) you'll want to completely dissociate the child process from the parent. This is often called daemonization. A well-behaved daemon will also chdir() to the root directory so it doesn't prevent unmounting the filesystem containing the directory from which it was launched, and redirect its standard file descriptors from and to */dev/null* so that random output doesn't wind up on the user's terminal.
```
use POSIX "setsid";
sub daemonize {
chdir("/") || die "can't chdir to /: $!";
open(STDIN, "<", "/dev/null") || die "can't read /dev/null: $!";
open(STDOUT, ">", "/dev/null") || die "can't write /dev/null: $!";
defined(my $pid = fork()) || die "can't fork: $!";
exit if $pid; # non-zero now means I am the parent
(setsid() != -1) || die "Can't start a new session: $!";
open(STDERR, ">&", STDOUT) || die "can't dup stdout: $!";
}
```
The fork() has to come before the setsid() to ensure you aren't a process group leader; the setsid() will fail if you are. If your system doesn't have the setsid() function, open */dev/tty* and use the `TIOCNOTTY` ioctl() on it instead. See tty(4) for details.
Non-Unix users should check their `*Your\_OS*::Process` module for other possible solutions.
###
Safe Pipe Opens
Another interesting approach to IPC is making your single program go multiprocess and communicate between--or even amongst--yourselves. The two-argument form of the open() function will accept a file argument of either `"-|"` or `"|-"` to do a very interesting thing: it forks a child connected to the filehandle you've opened. The child is running the same program as the parent. This is useful for safely opening a file when running under an assumed UID or GID, for example. If you open a pipe *to* minus, you can write to the filehandle you opened and your kid will find it in *his* STDIN. If you open a pipe *from* minus, you can read from the filehandle you opened whatever your kid writes to *his* STDOUT.
```
my $PRECIOUS = "/path/to/some/safe/file";
my $sleep_count;
my $pid;
my $kid_to_write;
do {
$pid = open($kid_to_write, "|-");
unless (defined $pid) {
warn "cannot fork: $!";
die "bailing out" if $sleep_count++ > 6;
sleep 10;
}
} until defined $pid;
if ($pid) { # I am the parent
print $kid_to_write @some_data;
close($kid_to_write) || warn "kid exited $?";
} else { # I am the child
# drop permissions in setuid and/or setgid programs:
($>, $)) = ($<, $();
open (my $outfile, ">", $PRECIOUS)
|| die "can't open $PRECIOUS: $!";
while (<STDIN>) {
print $outfile; # child STDIN is parent $kid_to_write
}
close($outfile) || die "can't close $PRECIOUS: $!";
exit(0); # don't forget this!!
}
```
Another common use for this construct is when you need to execute something without the shell's interference. With system(), it's straightforward, but you can't use a pipe open or backticks safely. That's because there's no way to stop the shell from getting its hands on your arguments. Instead, use lower-level control to call exec() directly.
Here's a safe backtick or pipe open for read:
```
my $pid = open(my $kid_to_read, "-|");
defined($pid) || die "can't fork: $!";
if ($pid) { # parent
while (<$kid_to_read>) {
# do something interesting
}
close($kid_to_read) || warn "kid exited $?";
} else { # child
($>, $)) = ($<, $(); # suid only
exec($program, @options, @args)
|| die "can't exec program: $!";
# NOTREACHED
}
```
And here's a safe pipe open for writing:
```
my $pid = open(my $kid_to_write, "|-");
defined($pid) || die "can't fork: $!";
$SIG{PIPE} = sub { die "whoops, $program pipe broke" };
if ($pid) { # parent
print $kid_to_write @data;
close($kid_to_write) || warn "kid exited $?";
} else { # child
($>, $)) = ($<, $();
exec($program, @options, @args)
|| die "can't exec program: $!";
# NOTREACHED
}
```
It is very easy to dead-lock a process using this form of open(), or indeed with any use of pipe() with multiple subprocesses. The example above is "safe" because it is simple and calls exec(). See ["Avoiding Pipe Deadlocks"](#Avoiding-Pipe-Deadlocks) for general safety principles, but there are extra gotchas with Safe Pipe Opens.
In particular, if you opened the pipe using `open $fh, "|-"`, then you cannot simply use close() in the parent process to close an unwanted writer. Consider this code:
```
my $pid = open(my $writer, "|-"); # fork open a kid
defined($pid) || die "first fork failed: $!";
if ($pid) {
if (my $sub_pid = fork()) {
defined($sub_pid) || die "second fork failed: $!";
close($writer) || die "couldn't close writer: $!";
# now do something else...
}
else {
# first write to $writer
# ...
# then when finished
close($writer) || die "couldn't close writer: $!";
exit(0);
}
}
else {
# first do something with STDIN, then
exit(0);
}
```
In the example above, the true parent does not want to write to the $writer filehandle, so it closes it. However, because $writer was opened using `open $fh, "|-"`, it has a special behavior: closing it calls waitpid() (see ["waitpid" in perlfunc](perlfunc#waitpid)), which waits for the subprocess to exit. If the child process ends up waiting for something happening in the section marked "do something else", you have deadlock.
This can also be a problem with intermediate subprocesses in more complicated code, which will call waitpid() on all open filehandles during global destruction--in no predictable order.
To solve this, you must manually use pipe(), fork(), and the form of open() which sets one file descriptor to another, as shown below:
```
pipe(my $reader, my $writer) || die "pipe failed: $!";
my $pid = fork();
defined($pid) || die "first fork failed: $!";
if ($pid) {
close $reader;
if (my $sub_pid = fork()) {
defined($sub_pid) || die "first fork failed: $!";
close($writer) || die "can't close writer: $!";
}
else {
# write to $writer...
# ...
# then when finished
close($writer) || die "can't close writer: $!";
exit(0);
}
# write to $writer...
}
else {
open(STDIN, "<&", $reader) || die "can't reopen STDIN: $!";
close($writer) || die "can't close writer: $!";
# do something...
exit(0);
}
```
Since Perl 5.8.0, you can also use the list form of `open` for pipes. This is preferred when you wish to avoid having the shell interpret metacharacters that may be in your command string.
So for example, instead of using:
```
open(my $ps_pipe, "-|", "ps aux") || die "can't open ps pipe: $!";
```
One would use either of these:
```
open(my $ps_pipe, "-|", "ps", "aux")
|| die "can't open ps pipe: $!";
my @ps_args = qw[ ps aux ];
open(my $ps_pipe, "-|", @ps_args)
|| die "can't open @ps_args|: $!";
```
Because there are more than three arguments to open(), it forks the ps(1) command *without* spawning a shell, and reads its standard output via the `$ps_pipe` filehandle. The corresponding syntax to *write* to command pipes is to use `"|-"` in place of `"-|"`.
This was admittedly a rather silly example, because you're using string literals whose content is perfectly safe. There is therefore no cause to resort to the harder-to-read, multi-argument form of pipe open(). However, whenever you cannot be assured that the program arguments are free of shell metacharacters, the fancier form of open() should be used. For example:
```
my @grep_args = ("egrep", "-i", $some_pattern, @many_files);
open(my $grep_pipe, "-|", @grep_args)
|| die "can't open @grep_args|: $!";
```
Here the multi-argument form of pipe open() is preferred because the pattern and indeed even the filenames themselves might hold metacharacters.
###
Avoiding Pipe Deadlocks
Whenever you have more than one subprocess, you must be careful that each closes whichever half of any pipes created for interprocess communication it is not using. This is because any child process reading from the pipe and expecting an EOF will never receive it, and therefore never exit. A single process closing a pipe is not enough to close it; the last process with the pipe open must close it for it to read EOF.
Certain built-in Unix features help prevent this most of the time. For instance, filehandles have a "close on exec" flag, which is set *en masse* under control of the `$^F` variable. This is so any filehandles you didn't explicitly route to the STDIN, STDOUT or STDERR of a child *program* will be automatically closed.
Always explicitly and immediately call close() on the writable end of any pipe, unless that process is actually writing to it. Even if you don't explicitly call close(), Perl will still close() all filehandles during global destruction. As previously discussed, if those filehandles have been opened with Safe Pipe Open, this will result in calling waitpid(), which may again deadlock.
###
Bidirectional Communication with Another Process
While this works reasonably well for unidirectional communication, what about bidirectional communication? The most obvious approach doesn't work:
```
# THIS DOES NOT WORK!!
open(my $prog_for_reading_and_writing, "| some program |")
```
If you forget to `use warnings`, you'll miss out entirely on the helpful diagnostic message:
```
Can't do bidirectional pipe at -e line 1.
```
If you really want to, you can use the standard open2() from the <IPC::Open2> module to catch both ends. There's also an open3() in <IPC::Open3> for tridirectional I/O so you can also catch your child's STDERR, but doing so would then require an awkward select() loop and wouldn't allow you to use normal Perl input operations.
If you look at its source, you'll see that open2() uses low-level primitives like the pipe() and exec() syscalls to create all the connections. Although it might have been more efficient by using socketpair(), this would have been even less portable than it already is. The open2() and open3() functions are unlikely to work anywhere except on a Unix system, or at least one purporting POSIX compliance.
Here's an example of using open2():
```
use IPC::Open2;
my $pid = open2(my $reader, my $writer, "cat -un");
print $writer "stuff\n";
my $got = <$reader>;
waitpid $pid, 0;
```
The problem with this is that buffering is really going to ruin your day. Even though your `$writer` filehandle is auto-flushed so the process on the other end gets your data in a timely manner, you can't usually do anything to force that process to give its data to you in a similarly quick fashion. In this special case, we could actually so, because we gave *cat* a **-u** flag to make it unbuffered. But very few commands are designed to operate over pipes, so this seldom works unless you yourself wrote the program on the other end of the double-ended pipe.
A solution to this is to use a library which uses pseudottys to make your program behave more reasonably. This way you don't have to have control over the source code of the program you're using. The `Expect` module from CPAN also addresses this kind of thing. This module requires two other modules from CPAN, `IO::Pty` and `IO::Stty`. It sets up a pseudo terminal to interact with programs that insist on talking to the terminal device driver. If your system is supported, this may be your best bet.
###
Bidirectional Communication with Yourself
If you want, you may make low-level pipe() and fork() syscalls to stitch this together by hand. This example only talks to itself, but you could reopen the appropriate handles to STDIN and STDOUT and call other processes. (The following example lacks proper error checking.)
```
#!/usr/bin/perl
# pipe1 - bidirectional communication using two pipe pairs
# designed for the socketpair-challenged
use v5.36;
use IO::Handle; # enable autoflush method before Perl 5.14
pipe(my $parent_rdr, my $child_wtr); # XXX: check failure?
pipe(my $child_rdr, my $parent_wtr); # XXX: check failure?
$child_wtr->autoflush(1);
$parent_wtr->autoflush(1);
if ($pid = fork()) {
close $parent_rdr;
close $parent_wtr;
print $child_wtr "Parent Pid $$ is sending this\n";
chomp(my $line = <$child_rdr>);
print "Parent Pid $$ just read this: '$line'\n";
close $child_rdr; close $child_wtr;
waitpid($pid, 0);
} else {
die "cannot fork: $!" unless defined $pid;
close $child_rdr;
close $child_wtr;
chomp(my $line = <$parent_rdr>);
print "Child Pid $$ just read this: '$line'\n";
print $parent_wtr "Child Pid $$ is sending this\n";
close $parent_rdr;
close $parent_wtr;
exit(0);
}
```
But you don't actually have to make two pipe calls. If you have the socketpair() system call, it will do this all for you.
```
#!/usr/bin/perl
# pipe2 - bidirectional communication using socketpair
# "the best ones always go both ways"
use v5.36;
use Socket;
use IO::Handle; # enable autoflush method before Perl 5.14
# We say AF_UNIX because although *_LOCAL is the
# POSIX 1003.1g form of the constant, many machines
# still don't have it.
socketpair(my $child, my $parent, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
|| die "socketpair: $!";
$child->autoflush(1);
$parent->autoflush(1);
if ($pid = fork()) {
close $parent;
print $child "Parent Pid $$ is sending this\n";
chomp(my $line = <$child>);
print "Parent Pid $$ just read this: '$line'\n";
close $child;
waitpid($pid, 0);
} else {
die "cannot fork: $!" unless defined $pid;
close $child;
chomp(my $line = <$parent>);
print "Child Pid $$ just read this: '$line'\n";
print $parent "Child Pid $$ is sending this\n";
close $parent;
exit(0);
}
```
Sockets: Client/Server Communication
-------------------------------------
While not entirely limited to Unix-derived operating systems (e.g., WinSock on PCs provides socket support, as do some VMS libraries), you might not have sockets on your system, in which case this section probably isn't going to do you much good. With sockets, you can do both virtual circuits like TCP streams and datagrams like UDP packets. You may be able to do even more depending on your system.
The Perl functions for dealing with sockets have the same names as the corresponding system calls in C, but their arguments tend to differ for two reasons. First, Perl filehandles work differently than C file descriptors. Second, Perl already knows the length of its strings, so you don't need to pass that information.
One of the major problems with ancient, antemillennial socket code in Perl was that it used hard-coded values for some of the constants, which severely hurt portability. If you ever see code that does anything like explicitly setting `$AF_INET = 2`, you know you're in for big trouble. An immeasurably superior approach is to use the [Socket](socket) module, which more reliably grants access to the various constants and functions you'll need.
If you're not writing a server/client for an existing protocol like NNTP or SMTP, you should give some thought to how your server will know when the client has finished talking, and vice-versa. Most protocols are based on one-line messages and responses (so one party knows the other has finished when a "\n" is received) or multi-line messages and responses that end with a period on an empty line ("\n.\n" terminates a message/response).
###
Internet Line Terminators
The Internet line terminator is "\015\012". Under ASCII variants of Unix, that could usually be written as "\r\n", but under other systems, "\r\n" might at times be "\015\015\012", "\012\012\015", or something completely different. The standards specify writing "\015\012" to be conformant (be strict in what you provide), but they also recommend accepting a lone "\012" on input (be lenient in what you require). We haven't always been very good about that in the code in this manpage, but unless you're on a Mac from way back in its pre-Unix dark ages, you'll probably be ok.
###
Internet TCP Clients and Servers
Use Internet-domain sockets when you want to do client-server communication that might extend to machines outside of your own system.
Here's a sample TCP client using Internet-domain sockets:
```
#!/usr/bin/perl
use v5.36;
use Socket;
my $remote = shift || "localhost";
my $port = shift || 2345; # random port
if ($port =~ /\D/) { $port = getservbyname($port, "tcp") }
die "No port" unless $port;
my $iaddr = inet_aton($remote) || die "no host: $remote";
my $paddr = sockaddr_in($port, $iaddr);
my $proto = getprotobyname("tcp");
socket(my $sock, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
connect($sock, $paddr) || die "connect: $!";
while (my $line = <$sock>) {
print $line;
}
close ($sock) || die "close: $!";
exit(0);
```
And here's a corresponding server to go along with it. We'll leave the address as `INADDR_ANY` so that the kernel can choose the appropriate interface on multihomed hosts. If you want sit on a particular interface (like the external side of a gateway or firewall machine), fill this in with your real address instead.
```
#!/usr/bin/perl -T
use v5.36;
BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
use Socket;
use Carp;
my $EOL = "\015\012";
sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
my $port = shift || 2345;
die "invalid port" unless $port =~ /^ \d+ $/x;
my $proto = getprotobyname("tcp");
socket(my $server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
setsockopt($server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
|| die "setsockopt: $!";
bind($server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";
listen($server, SOMAXCONN) || die "listen: $!";
logmsg "server started on port $port";
for (my $paddr; $paddr = accept(my $client, $server); close $client) {
my($port, $iaddr) = sockaddr_in($paddr);
my $name = gethostbyaddr($iaddr, AF_INET);
logmsg "connection from $name [",
inet_ntoa($iaddr), "]
at port $port";
print $client "Hello there, $name, it's now ",
scalar localtime(), $EOL;
}
```
And here's a multitasking version. It's multitasked in that like most typical servers, it spawns (fork()s) a child server to handle the client request so that the master server can quickly go back to service a new client.
```
#!/usr/bin/perl -T
use v5.36;
BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
use Socket;
use Carp;
my $EOL = "\015\012";
sub spawn; # forward declaration
sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
my $port = shift || 2345;
die "invalid port" unless $port =~ /^ \d+ $/x;
my $proto = getprotobyname("tcp");
socket(my $server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
setsockopt($server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
|| die "setsockopt: $!";
bind($server, sockaddr_in($port, INADDR_ANY)) || die "bind: $!";
listen($server, SOMAXCONN) || die "listen: $!";
logmsg "server started on port $port";
my $waitedpid = 0;
use POSIX ":sys_wait_h";
use Errno;
sub REAPER {
local $!; # don't let waitpid() overwrite current error
while ((my $pid = waitpid(-1, WNOHANG)) > 0 && WIFEXITED($?)) {
logmsg "reaped $waitedpid" . ($? ? " with exit $?" : "");
}
$SIG{CHLD} = \&REAPER; # loathe SysV
}
$SIG{CHLD} = \&REAPER;
while (1) {
my $paddr = accept(my $client, $server) || do {
# try again if accept() returned because got a signal
next if $!{EINTR};
die "accept: $!";
};
my ($port, $iaddr) = sockaddr_in($paddr);
my $name = gethostbyaddr($iaddr, AF_INET);
logmsg "connection from $name [",
inet_ntoa($iaddr),
"] at port $port";
spawn $client, sub {
$| = 1;
print "Hello there, $name, it's now ",
scalar localtime(),
$EOL;
exec "/usr/games/fortune" # XXX: "wrong" line terminators
or confess "can't exec fortune: $!";
};
close $client;
}
sub spawn {
my $client = shift;
my $coderef = shift;
unless (@_ == 0 && $coderef && ref($coderef) eq "CODE") {
confess "usage: spawn CLIENT CODEREF";
}
my $pid;
unless (defined($pid = fork())) {
logmsg "cannot fork: $!";
return;
}
elsif ($pid) {
logmsg "begat $pid";
return; # I'm the parent
}
# else I'm the child -- go spawn
open(STDIN, "<&", $client) || die "can't dup client to stdin";
open(STDOUT, ">&", $client) || die "can't dup client to stdout";
## open(STDERR, ">&", STDOUT) || die "can't dup stdout to stderr";
exit($coderef->());
}
```
This server takes the trouble to clone off a child version via fork() for each incoming request. That way it can handle many requests at once, which you might not always want. Even if you don't fork(), the listen() will allow that many pending connections. Forking servers have to be particularly careful about cleaning up their dead children (called "zombies" in Unix parlance), because otherwise you'll quickly fill up your process table. The REAPER subroutine is used here to call waitpid() for any child processes that have finished, thereby ensuring that they terminate cleanly and don't join the ranks of the living dead.
Within the while loop we call accept() and check to see if it returns a false value. This would normally indicate a system error needs to be reported. However, the introduction of safe signals (see ["Deferred Signals (Safe Signals)"](#Deferred-Signals-%28Safe-Signals%29) above) in Perl 5.8.0 means that accept() might also be interrupted when the process receives a signal. This typically happens when one of the forked subprocesses exits and notifies the parent process with a CHLD signal.
If accept() is interrupted by a signal, $! will be set to EINTR. If this happens, we can safely continue to the next iteration of the loop and another call to accept(). It is important that your signal handling code not modify the value of $!, or else this test will likely fail. In the REAPER subroutine we create a local version of $! before calling waitpid(). When waitpid() sets $! to ECHILD as it inevitably does when it has no more children waiting, it updates the local copy and leaves the original unchanged.
You should use the **-T** flag to enable taint checking (see <perlsec>) even if we aren't running setuid or setgid. This is always a good idea for servers or any program run on behalf of someone else (like CGI scripts), because it lessens the chances that people from the outside will be able to compromise your system. Note that perl can be built without taint support. There are two different modes: in one, **-T** will silently do nothing. In the other mode **-T** results in a fatal error.
Let's look at another TCP client. This one connects to the TCP "time" service on a number of different machines and shows how far their clocks differ from the system on which it's being run:
```
#!/usr/bin/perl
use v5.36;
use Socket;
my $SECS_OF_70_YEARS = 2208988800;
sub ctime { scalar localtime(shift() || time()) }
my $iaddr = gethostbyname("localhost");
my $proto = getprotobyname("tcp");
my $port = getservbyname("time", "tcp");
my $paddr = sockaddr_in(0, $iaddr);
$| = 1;
printf "%-24s %8s %s\n", "localhost", 0, ctime();
foreach my $host (@ARGV) {
printf "%-24s ", $host;
my $hisiaddr = inet_aton($host) || die "unknown host";
my $hispaddr = sockaddr_in($port, $hisiaddr);
socket(my $socket, PF_INET, SOCK_STREAM, $proto)
|| die "socket: $!";
connect($socket, $hispaddr) || die "connect: $!";
my $rtime = pack("C4", ());
read($socket, $rtime, 4);
close($socket);
my $histime = unpack("N", $rtime) - $SECS_OF_70_YEARS;
printf "%8d %s\n", $histime - time(), ctime($histime);
}
```
###
Unix-Domain TCP Clients and Servers
That's fine for Internet-domain clients and servers, but what about local communications? While you can use the same setup, sometimes you don't want to. Unix-domain sockets are local to the current host, and are often used internally to implement pipes. Unlike Internet domain sockets, Unix domain sockets can show up in the file system with an ls(1) listing.
```
% ls -l /dev/log
srw-rw-rw- 1 root 0 Oct 31 07:23 /dev/log
```
You can test for these with Perl's **-S** file test:
```
unless (-S "/dev/log") {
die "something's wicked with the log system";
}
```
Here's a sample Unix-domain client:
```
#!/usr/bin/perl
use v5.36;
use Socket;
my $rendezvous = shift || "catsock";
socket(my $sock, PF_UNIX, SOCK_STREAM, 0) || die "socket: $!";
connect($sock, sockaddr_un($rendezvous)) || die "connect: $!";
while (defined(my $line = <$sock>)) {
print $line;
}
exit(0);
```
And here's a corresponding server. You don't have to worry about silly network terminators here because Unix domain sockets are guaranteed to be on the localhost, and thus everything works right.
```
#!/usr/bin/perl -T
use v5.36;
use Socket;
use Carp;
BEGIN { $ENV{PATH} = "/usr/bin:/bin" }
sub spawn; # forward declaration
sub logmsg { print "$0 $$: @_ at ", scalar localtime(), "\n" }
my $NAME = "catsock";
my $uaddr = sockaddr_un($NAME);
my $proto = getprotobyname("tcp");
socket(my $server, PF_UNIX, SOCK_STREAM, 0) || die "socket: $!";
unlink($NAME);
bind ($server, $uaddr) || die "bind: $!";
listen($server, SOMAXCONN) || die "listen: $!";
logmsg "server started on $NAME";
my $waitedpid;
use POSIX ":sys_wait_h";
sub REAPER {
my $child;
while (($waitedpid = waitpid(-1, WNOHANG)) > 0) {
logmsg "reaped $waitedpid" . ($? ? " with exit $?" : "");
}
$SIG{CHLD} = \&REAPER; # loathe SysV
}
$SIG{CHLD} = \&REAPER;
for ( $waitedpid = 0;
accept(my $client, $server) || $waitedpid;
$waitedpid = 0, close $client)
{
next if $waitedpid;
logmsg "connection on $NAME";
spawn $client, sub {
print "Hello there, it's now ", scalar localtime(), "\n";
exec("/usr/games/fortune") || die "can't exec fortune: $!";
};
}
sub spawn {
my $client = shift();
my $coderef = shift();
unless (@_ == 0 && $coderef && ref($coderef) eq "CODE") {
confess "usage: spawn CLIENT CODEREF";
}
my $pid;
unless (defined($pid = fork())) {
logmsg "cannot fork: $!";
return;
}
elsif ($pid) {
logmsg "begat $pid";
return; # I'm the parent
}
else {
# I'm the child -- go spawn
}
open(STDIN, "<&", $client)
|| die "can't dup client to stdin";
open(STDOUT, ">&", $client)
|| die "can't dup client to stdout";
## open(STDERR, ">&", STDOUT)
## || die "can't dup stdout to stderr";
exit($coderef->());
}
```
As you see, it's remarkably similar to the Internet domain TCP server, so much so, in fact, that we've omitted several duplicate functions--spawn(), logmsg(), ctime(), and REAPER()--which are the same as in the other server.
So why would you ever want to use a Unix domain socket instead of a simpler named pipe? Because a named pipe doesn't give you sessions. You can't tell one process's data from another's. With socket programming, you get a separate session for each client; that's why accept() takes two arguments.
For example, let's say that you have a long-running database server daemon that you want folks to be able to access from the Web, but only if they go through a CGI interface. You'd have a small, simple CGI program that does whatever checks and logging you feel like, and then acts as a Unix-domain client and connects to your private server.
TCP Clients with IO::Socket
----------------------------
For those preferring a higher-level interface to socket programming, the IO::Socket module provides an object-oriented approach. If for some reason you lack this module, you can just fetch IO::Socket from CPAN, where you'll also find modules providing easy interfaces to the following systems: DNS, FTP, Ident (RFC 931), NIS and NISPlus, NNTP, Ping, POP3, SMTP, SNMP, SSLeay, Telnet, and Time--to name just a few.
###
A Simple Client
Here's a client that creates a TCP connection to the "daytime" service at port 13 of the host name "localhost" and prints out everything that the server there cares to provide.
```
#!/usr/bin/perl
use v5.36;
use IO::Socket;
my $remote = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => "localhost",
PeerPort => "daytime(13)",
)
|| die "can't connect to daytime service on localhost";
while (<$remote>) { print }
```
When you run this program, you should get something back that looks like this:
```
Wed May 14 08:40:46 MDT 1997
```
Here are what those parameters to the new() constructor mean:
`Proto` This is which protocol to use. In this case, the socket handle returned will be connected to a TCP socket, because we want a stream-oriented connection, that is, one that acts pretty much like a plain old file. Not all sockets are this of this type. For example, the UDP protocol can be used to make a datagram socket, used for message-passing.
`PeerAddr` This is the name or Internet address of the remote host the server is running on. We could have specified a longer name like `"www.perl.com"`, or an address like `"207.171.7.72"`. For demonstration purposes, we've used the special hostname `"localhost"`, which should always mean the current machine you're running on. The corresponding Internet address for localhost is `"127.0.0.1"`, if you'd rather use that.
`PeerPort` This is the service name or port number we'd like to connect to. We could have gotten away with using just `"daytime"` on systems with a well-configured system services file,[FOOTNOTE: The system services file is found in */etc/services* under Unixy systems.] but here we've specified the port number (13) in parentheses. Using just the number would have also worked, but numeric literals make careful programmers nervous.
###
A Webget Client
Here's a simple client that takes a remote host to fetch a document from, and then a list of files to get from that host. This is a more interesting client than the previous one because it first sends something to the server before fetching the server's response.
```
#!/usr/bin/perl
use v5.36;
use IO::Socket;
unless (@ARGV > 1) { die "usage: $0 host url ..." }
my $host = shift(@ARGV);
my $EOL = "\015\012";
my $BLANK = $EOL x 2;
for my $document (@ARGV) {
my $remote = IO::Socket::INET->new( Proto => "tcp",
PeerAddr => $host,
PeerPort => "http(80)",
) || die "cannot connect to httpd on $host";
$remote->autoflush(1);
print $remote "GET $document HTTP/1.0" . $BLANK;
while ( <$remote> ) { print }
close $remote;
}
```
The web server handling the HTTP service is assumed to be at its standard port, number 80. If the server you're trying to connect to is at a different port, like 1080 or 8080, you should specify it as the named-parameter pair, `PeerPort => 8080`. The `autoflush` method is used on the socket because otherwise the system would buffer up the output we sent it. (If you're on a prehistoric Mac, you'll also need to change every `"\n"` in your code that sends data over the network to be a `"\015\012"` instead.)
Connecting to the server is only the first part of the process: once you have the connection, you have to use the server's language. Each server on the network has its own little command language that it expects as input. The string that we send to the server starting with "GET" is in HTTP syntax. In this case, we simply request each specified document. Yes, we really are making a new connection for each document, even though it's the same host. That's the way you always used to have to speak HTTP. Recent versions of web browsers may request that the remote server leave the connection open a little while, but the server doesn't have to honor such a request.
Here's an example of running that program, which we'll call *webget*:
```
% webget www.perl.com /guanaco.html
HTTP/1.1 404 File Not Found
Date: Thu, 08 May 1997 18:02:32 GMT
Server: Apache/1.2b6
Connection: close
Content-type: text/html
<HEAD><TITLE>404 File Not Found</TITLE></HEAD>
<BODY><H1>File Not Found</H1>
The requested URL /guanaco.html was not found on this server.<P>
</BODY>
```
Ok, so that's not very interesting, because it didn't find that particular document. But a long response wouldn't have fit on this page.
For a more featureful version of this program, you should look to the *lwp-request* program included with the LWP modules from CPAN.
###
Interactive Client with IO::Socket
Well, that's all fine if you want to send one command and get one answer, but what about setting up something fully interactive, somewhat like the way *telnet* works? That way you can type a line, get the answer, type a line, get the answer, etc.
This client is more complicated than the two we've done so far, but if you're on a system that supports the powerful `fork` call, the solution isn't that rough. Once you've made the connection to whatever service you'd like to chat with, call `fork` to clone your process. Each of these two identical process has a very simple job to do: the parent copies everything from the socket to standard output, while the child simultaneously copies everything from standard input to the socket. To accomplish the same thing using just one process would be *much* harder, because it's easier to code two processes to do one thing than it is to code one process to do two things. (This keep-it-simple principle a cornerstones of the Unix philosophy, and good software engineering as well, which is probably why it's spread to other systems.)
Here's the code:
```
#!/usr/bin/perl
use v5.36;
use IO::Socket;
unless (@ARGV == 2) { die "usage: $0 host port" }
my ($host, $port) = @ARGV;
# create a tcp connection to the specified host and port
my $handle = IO::Socket::INET->new(Proto => "tcp",
PeerAddr => $host,
PeerPort => $port)
|| die "can't connect to port $port on $host: $!";
$handle->autoflush(1); # so output gets there right away
print STDERR "[Connected to $host:$port]\n";
# split the program into two processes, identical twins
die "can't fork: $!" unless defined(my $kidpid = fork());
# the if{} block runs only in the parent process
if ($kidpid) {
# copy the socket to standard output
while (defined (my $line = <$handle>)) {
print STDOUT $line;
}
kill("TERM", $kidpid); # send SIGTERM to child
}
# the else{} block runs only in the child process
else {
# copy standard input to the socket
while (defined (my $line = <STDIN>)) {
print $handle $line;
}
exit(0); # just in case
}
```
The `kill` function in the parent's `if` block is there to send a signal to our child process, currently running in the `else` block, as soon as the remote server has closed its end of the connection.
If the remote server sends data a byte at time, and you need that data immediately without waiting for a newline (which might not happen), you may wish to replace the `while` loop in the parent with the following:
```
my $byte;
while (sysread($handle, $byte, 1) == 1) {
print STDOUT $byte;
}
```
Making a system call for each byte you want to read is not very efficient (to put it mildly) but is the simplest to explain and works reasonably well.
TCP Servers with IO::Socket
----------------------------
As always, setting up a server is little bit more involved than running a client. The model is that the server creates a special kind of socket that does nothing but listen on a particular port for incoming connections. It does this by calling the `IO::Socket::INET->new()` method with slightly different arguments than the client did.
Proto This is which protocol to use. Like our clients, we'll still specify `"tcp"` here.
LocalPort We specify a local port in the `LocalPort` argument, which we didn't do for the client. This is service name or port number for which you want to be the server. (Under Unix, ports under 1024 are restricted to the superuser.) In our sample, we'll use port 9000, but you can use any port that's not currently in use on your system. If you try to use one already in used, you'll get an "Address already in use" message. Under Unix, the `netstat -a` command will show which services current have servers.
Listen The `Listen` parameter is set to the maximum number of pending connections we can accept until we turn away incoming clients. Think of it as a call-waiting queue for your telephone. The low-level Socket module has a special symbol for the system maximum, which is SOMAXCONN.
Reuse The `Reuse` parameter is needed so that we restart our server manually without waiting a few minutes to allow system buffers to clear out.
Once the generic server socket has been created using the parameters listed above, the server then waits for a new client to connect to it. The server blocks in the `accept` method, which eventually accepts a bidirectional connection from the remote client. (Make sure to autoflush this handle to circumvent buffering.)
To add to user-friendliness, our server prompts the user for commands. Most servers don't do this. Because of the prompt without a newline, you'll have to use the `sysread` variant of the interactive client above.
This server accepts one of five different commands, sending output back to the client. Unlike most network servers, this one handles only one incoming client at a time. Multitasking servers are covered in Chapter 16 of the Camel.
Here's the code.
```
#!/usr/bin/perl
use v5.36;
use IO::Socket;
use Net::hostent; # for OOish version of gethostbyaddr
my $PORT = 9000; # pick something not in use
my $server = IO::Socket::INET->new( Proto => "tcp",
LocalPort => $PORT,
Listen => SOMAXCONN,
Reuse => 1);
die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
while (my $client = $server->accept()) {
$client->autoflush(1);
print $client "Welcome to $0; type help for command list.\n";
my $hostinfo = gethostbyaddr($client->peeraddr);
printf "[Connect from %s]\n",
$hostinfo ? $hostinfo->name : $client->peerhost;
print $client "Command? ";
while ( <$client>) {
next unless /\S/; # blank line
if (/quit|exit/i) { last }
elsif (/date|time/i) { printf $client "%s\n", scalar localtime() }
elsif (/who/i ) { print $client `who 2>&1` }
elsif (/cookie/i ) { print $client `/usr/games/fortune 2>&1` }
elsif (/motd/i ) { print $client `cat /etc/motd 2>&1` }
else {
print $client "Commands: quit date who cookie motd\n";
}
} continue {
print $client "Command? ";
}
close $client;
}
```
UDP: Message Passing
---------------------
Another kind of client-server setup is one that uses not connections, but messages. UDP communications involve much lower overhead but also provide less reliability, as there are no promises that messages will arrive at all, let alone in order and unmangled. Still, UDP offers some advantages over TCP, including being able to "broadcast" or "multicast" to a whole bunch of destination hosts at once (usually on your local subnet). If you find yourself overly concerned about reliability and start building checks into your message system, then you probably should use just TCP to start with.
UDP datagrams are *not* a bytestream and should not be treated as such. This makes using I/O mechanisms with internal buffering like stdio (i.e. print() and friends) especially cumbersome. Use syswrite(), or better send(), like in the example below.
Here's a UDP program similar to the sample Internet TCP client given earlier. However, instead of checking one host at a time, the UDP version will check many of them asynchronously by simulating a multicast and then using select() to do a timed-out wait for I/O. To do something similar with TCP, you'd have to use a different socket handle for each host.
```
#!/usr/bin/perl
use v5.36;
use Socket;
use Sys::Hostname;
my $SECS_OF_70_YEARS = 2_208_988_800;
my $iaddr = gethostbyname(hostname());
my $proto = getprotobyname("udp");
my $port = getservbyname("time", "udp");
my $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick
socket(my $socket, PF_INET, SOCK_DGRAM, $proto) || die "socket: $!";
bind($socket, $paddr) || die "bind: $!";
$| = 1;
printf "%-12s %8s %s\n", "localhost", 0, scalar localtime();
my $count = 0;
for my $host (@ARGV) {
$count++;
my $hisiaddr = inet_aton($host) || die "unknown host";
my $hispaddr = sockaddr_in($port, $hisiaddr);
defined(send($socket, 0, 0, $hispaddr)) || die "send $host: $!";
}
my $rout = my $rin = "";
vec($rin, fileno($socket), 1) = 1;
# timeout after 10.0 seconds
while ($count && select($rout = $rin, undef, undef, 10.0)) {
my $rtime = "";
my $hispaddr = recv($socket, $rtime, 4, 0) || die "recv: $!";
my ($port, $hisiaddr) = sockaddr_in($hispaddr);
my $host = gethostbyaddr($hisiaddr, AF_INET);
my $histime = unpack("N", $rtime) - $SECS_OF_70_YEARS;
printf "%-12s ", $host;
printf "%8d %s\n", $histime - time(), scalar localtime($histime);
$count--;
}
```
This example does not include any retries and may consequently fail to contact a reachable host. The most prominent reason for this is congestion of the queues on the sending host if the number of hosts to contact is sufficiently large.
SysV IPC
---------
While System V IPC isn't so widely used as sockets, it still has some interesting uses. However, you cannot use SysV IPC or Berkeley mmap() to have a variable shared amongst several processes. That's because Perl would reallocate your string when you weren't wanting it to. You might look into the `IPC::Shareable` or `threads::shared` modules for that.
Here's a small example showing shared memory usage.
```
use IPC::SysV qw(IPC_PRIVATE IPC_RMID S_IRUSR S_IWUSR);
my $size = 2000;
my $id = shmget(IPC_PRIVATE, $size, S_IRUSR | S_IWUSR);
defined($id) || die "shmget: $!";
print "shm key $id\n";
my $message = "Message #1";
shmwrite($id, $message, 0, 60) || die "shmwrite: $!";
print "wrote: '$message'\n";
shmread($id, my $buff, 0, 60) || die "shmread: $!";
print "read : '$buff'\n";
# the buffer of shmread is zero-character end-padded.
substr($buff, index($buff, "\0")) = "";
print "un" unless $buff eq $message;
print "swell\n";
print "deleting shm $id\n";
shmctl($id, IPC_RMID, 0) || die "shmctl: $!";
```
Here's an example of a semaphore:
```
use IPC::SysV qw(IPC_CREAT);
my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 10, 0666 | IPC_CREAT);
defined($id) || die "semget: $!";
print "sem id $id\n";
```
Put this code in a separate file to be run in more than one process. Call the file *take*:
```
# create a semaphore
my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 0, 0);
defined($id) || die "semget: $!";
my $semnum = 0;
my $semflag = 0;
# "take" semaphore
# wait for semaphore to be zero
my $semop = 0;
my $opstring1 = pack("s!s!s!", $semnum, $semop, $semflag);
# Increment the semaphore count
$semop = 1;
my $opstring2 = pack("s!s!s!", $semnum, $semop, $semflag);
my $opstring = $opstring1 . $opstring2;
semop($id, $opstring) || die "semop: $!";
```
Put this code in a separate file to be run in more than one process. Call this file *give*:
```
# "give" the semaphore
# run this in the original process and you will see
# that the second process continues
my $IPC_KEY = 1234;
my $id = semget($IPC_KEY, 0, 0);
die unless defined($id);
my $semnum = 0;
my $semflag = 0;
# Decrement the semaphore count
my $semop = -1;
my $opstring = pack("s!s!s!", $semnum, $semop, $semflag);
semop($id, $opstring) || die "semop: $!";
```
The SysV IPC code above was written long ago, and it's definitely clunky looking. For a more modern look, see the IPC::SysV module.
A small example demonstrating SysV message queues:
```
use IPC::SysV qw(IPC_PRIVATE IPC_RMID IPC_CREAT S_IRUSR S_IWUSR);
my $id = msgget(IPC_PRIVATE, IPC_CREAT | S_IRUSR | S_IWUSR);
defined($id) || die "msgget failed: $!";
my $sent = "message";
my $type_sent = 1234;
msgsnd($id, pack("l! a*", $type_sent, $sent), 0)
|| die "msgsnd failed: $!";
msgrcv($id, my $rcvd_buf, 60, 0, 0)
|| die "msgrcv failed: $!";
my($type_rcvd, $rcvd) = unpack("l! a*", $rcvd_buf);
if ($rcvd eq $sent) {
print "okay\n";
} else {
print "not okay\n";
}
msgctl($id, IPC_RMID, 0) || die "msgctl failed: $!\n";
```
NOTES
-----
Most of these routines quietly but politely return `undef` when they fail instead of causing your program to die right then and there due to an uncaught exception. (Actually, some of the new *Socket* conversion functions do croak() on bad arguments.) It is therefore essential to check return values from these functions. Always begin your socket programs this way for optimal success, and don't forget to add the **-T** taint-checking flag to the `#!` line for servers:
```
#!/usr/bin/perl -T
use v5.36;
use sigtrap;
use Socket;
```
BUGS
----
These routines all create system-specific portability problems. As noted elsewhere, Perl is at the mercy of your C libraries for much of its system behavior. It's probably safest to assume broken SysV semantics for signals and to stick with simple TCP and UDP socket operations; e.g., don't try to pass open file descriptors over a local UDP datagram socket if you want your code to stand a chance of being portable.
AUTHOR
------
Tom Christiansen, with occasional vestiges of Larry Wall's original version and suggestions from the Perl Porters.
SEE ALSO
---------
There's a lot more to networking than this, but this should get you started.
For intrepid programmers, the indispensable textbook is *Unix Network Programming, 2nd Edition, Volume 1* by W. Richard Stevens (published by Prentice-Hall). Most books on networking address the subject from the perspective of a C programmer; translation to Perl is left as an exercise for the reader.
The IO::Socket(3) manpage describes the object library, and the Socket(3) manpage describes the low-level interface to sockets. Besides the obvious functions in <perlfunc>, you should also check out the *modules* file at your nearest CPAN site, especially <http://www.cpan.org/modules/00modlist.long.html#ID5_Networking_>. See <perlmodlib> or best yet, the *Perl FAQ* for a description of what CPAN is and where to get it if the previous link doesn't work for you.
Section 5 of CPAN's *modules* file is devoted to "Networking, Device Control (modems), and Interprocess Communication", and contains numerous unbundled modules numerous networking modules, Chat and Expect operations, CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC, SNMP, SMTP, Telnet, Threads, and ToolTalk--to name just a few.
| programming_docs |
perl Pod::Text Pod::Text
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
* [BUGS](#BUGS)
* [CAVEATS](#CAVEATS)
* [NOTES](#NOTES)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Text - Convert POD data to formatted text
SYNOPSIS
--------
```
use Pod::Text;
my $parser = Pod::Text->new (sentence => 1, width => 78);
# Read POD from STDIN and write to STDOUT.
$parser->parse_from_filehandle;
# Read POD from file.pod and write to file.txt.
$parser->parse_from_file ('file.pod', 'file.txt');
```
DESCRIPTION
-----------
Pod::Text is a module that can convert documentation in the POD format (the preferred language for documenting Perl) into formatted text. It uses no special formatting controls or codes whatsoever, and its output is therefore suitable for nearly any device.
As a derived class from Pod::Simple, Pod::Text supports the same methods and interfaces. See <Pod::Simple> for all the details; briefly, one creates a new parser with `Pod::Text->new()` and then normally calls parse\_file().
new() can take options, in the form of key/value pairs, that control the behavior of the parser. The currently recognized options are:
alt If set to a true value, selects an alternate output format that, among other things, uses a different heading style and marks `=item` entries with a colon in the left margin. Defaults to false.
code If set to a true value, the non-POD parts of the input file will be included in the output. Useful for viewing code documented with POD blocks with the POD rendered and the code left intact.
errors How to report errors. `die` says to throw an exception on any POD formatting error. `stderr` says to report errors on standard error, but not to throw an exception. `pod` says to include a POD ERRORS section in the resulting documentation summarizing the errors. `none` ignores POD errors entirely, as much as possible.
The default is `pod`.
indent The number of spaces to indent regular text, and the default indentation for `=over` blocks. Defaults to 4.
loose If set to a true value, a blank line is printed after a `=head1` heading. If set to false (the default), no blank line is printed after `=head1`, although one is still printed after `=head2`. This is the default because it's the expected formatting for manual pages; if you're formatting arbitrary text documents, setting this to true may result in more pleasing output.
margin The width of the left margin in spaces. Defaults to 0. This is the margin for all text, including headings, not the amount by which regular text is indented; for the latter, see the *indent* option. To set the right margin, see the *width* option.
nourls Normally, L<> formatting codes with a URL but anchor text are formatted to show both the anchor text and the URL. In other words:
```
L<foo|http://example.com/>
```
is formatted as:
```
foo <http://example.com/>
```
This option, if set to a true value, suppresses the URL when anchor text is given, so this example would be formatted as just `foo`. This can produce less cluttered output in cases where the URLs are not particularly important.
quotes Sets the quote marks used to surround C<> text. If the value is a single character, it is used as both the left and right quote. Otherwise, it is split in half, and the first half of the string is used as the left quote and the second is used as the right quote.
This may also be set to the special value `none`, in which case no quote marks are added around C<> text.
sentence If set to a true value, Pod::Text will assume that each sentence ends in two spaces, and will try to preserve that spacing. If set to false, all consecutive whitespace in non-verbatim paragraphs is compressed into a single space. Defaults to false.
stderr Send error messages about invalid POD to standard error instead of appending a POD ERRORS section to the generated output. This is equivalent to setting `errors` to `stderr` if `errors` is not already set. It is supported for backward compatibility.
utf8 By default, Pod::Text uses the same output encoding as the input encoding of the POD source (provided that Perl was built with PerlIO; otherwise, it doesn't encode its output). If this option is given, the output encoding is forced to UTF-8.
Be aware that, when using this option, the input encoding of your POD source should be properly declared unless it's US-ASCII. Pod::Simple will attempt to guess the encoding and may be successful if it's Latin-1 or UTF-8, but it will produce warnings. Use the `=encoding` command to declare the encoding. See [perlpod(1)](http://man.he.net/man1/perlpod) for more information.
width The column at which to wrap text on the right-hand side. Defaults to 76.
The standard Pod::Simple method parse\_file() takes one argument naming the POD file to read from. By default, the output is sent to `STDOUT`, but this can be changed with the output\_fh() method.
The standard Pod::Simple method parse\_from\_file() takes up to two arguments, the first being the input file to read POD from and the second being the file to write the formatted output to.
You can also call parse\_lines() to parse an array of lines or parse\_string\_document() to parse a document already in memory. As with parse\_file(), parse\_lines() and parse\_string\_document() default to sending their output to `STDOUT` unless changed with the output\_fh() method. Be aware that parse\_lines() and parse\_string\_document() both expect raw bytes, not decoded characters.
To put the output from any parse method into a string instead of a file handle, call the output\_string() method instead of output\_fh().
See <Pod::Simple> for more specific details on the methods available to all derived parsers.
DIAGNOSTICS
-----------
Bizarre space in item
Item called without tag (W) Something has gone wrong in internal `=item` processing. These messages indicate a bug in Pod::Text; you should never see them.
Can't open %s for reading: %s (F) Pod::Text was invoked via the compatibility mode pod2text() interface and the input file it was given could not be opened.
Invalid errors setting "%s" (F) The `errors` parameter to the constructor was set to an unknown value.
Invalid quote specification "%s" (F) The quote specification given (the `quotes` option to the constructor) was invalid. A quote specification must be either one character long or an even number (greater than one) characters long.
POD document had syntax errors (F) The POD document being formatted had syntax errors and the `errors` option was set to `die`.
BUGS
----
Encoding handling assumes that PerlIO is available and does not work properly if it isn't. The `utf8` option is therefore not supported unless Perl is built with PerlIO support.
CAVEATS
-------
If Pod::Text is given the `utf8` option, the encoding of its output file handle will be forced to UTF-8 if possible, overriding any existing encoding. This will be done even if the file handle is not created by Pod::Text and was passed in from outside. This maintains consistency regardless of PERL\_UNICODE and other settings.
If the `utf8` option is not given, the encoding of its output file handle will be forced to the detected encoding of the input POD, which preserves whatever the input text is. This ensures backward compatibility with earlier, pre-Unicode versions of this module, without large numbers of Perl warnings.
This is not ideal, but it seems to be the best compromise. If it doesn't work for you, please let me know the details of how it broke.
NOTES
-----
This is a replacement for an earlier Pod::Text module written by Tom Christiansen. It has a revamped interface, since it now uses Pod::Simple, but an interface roughly compatible with the old Pod::Text::pod2text() function is still available. Please change to the new calling convention, though.
The original Pod::Text contained code to do formatting via termcap sequences, although it wasn't turned on by default and it was problematic to get it to work at all. This rewrite doesn't even try to do that, but a subclass of it does. Look for <Pod::Text::Termcap>.
AUTHOR
------
Russ Allbery <[email protected]>, based *very* heavily on the original Pod::Text by Tom Christiansen <[email protected]> and its conversion to Pod::Parser by Brad Appleton <[email protected]>. Sean Burke's initial conversion of Pod::Man to use Pod::Simple provided much-needed guidance on how to use Pod::Simple.
COPYRIGHT AND LICENSE
----------------------
Copyright 1999-2002, 2004, 2006, 2008-2009, 2012-2016, 2018-2019 Russ Allbery <[email protected]>
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<Pod::Simple>, <Pod::Text::Termcap>, [perlpod(1)](http://man.he.net/man1/perlpod), [pod2text(1)](http://man.he.net/man1/pod2text)
The current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>. It is also part of the Perl core distribution as of 5.6.0.
perl NDBM_File NDBM\_File
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DIAGNOSTICS](#DIAGNOSTICS)
+ [ndbm store returned -1, errno 22, key "..." at ...](#ndbm-store-returned-1,-errno-22,-key-%22...%22-at-...)
* [SECURITY AND PORTABILITY](#SECURITY-AND-PORTABILITY)
* [BUGS AND WARNINGS](#BUGS-AND-WARNINGS)
NAME
----
NDBM\_File - Tied access to ndbm files
SYNOPSIS
--------
```
use Fcntl; # For O_RDWR, O_CREAT, etc.
use NDBM_File;
tie(%h, 'NDBM_File', 'filename', O_RDWR|O_CREAT, 0666)
or die "Couldn't tie NDBM file 'filename': $!; aborting";
# Now read and change the hash
$h{newkey} = newvalue;
print $h{oldkey};
...
untie %h;
```
DESCRIPTION
-----------
`NDBM_File` establishes a connection between a Perl hash variable and a file in NDBM\_File format;. You can manipulate the data in the file just as if it were in a Perl hash, but when your program exits, the data will remain in the file, to be used the next time your program runs.
Use `NDBM_File` with the Perl built-in `tie` function to establish the connection between the variable and the file. The arguments to `tie` should be:
1. The hash variable you want to tie.
2. The string `"NDBM_File"`. (Ths tells Perl to use the `NDBM_File` package to perform the functions of the hash.)
3. The name of the file you want to tie to the hash.
4. Flags. Use one of:
`O_RDONLY` Read-only access to the data in the file.
`O_WRONLY` Write-only access to the data in the file.
`O_RDWR` Both read and write access.
If you want to create the file if it does not exist, add `O_CREAT` to any of these, as in the example. If you omit `O_CREAT` and the file does not already exist, the `tie` call will fail.
5. The default permissions to use if a new file is created. The actual permissions will be modified by the user's umask, so you should probably use 0666 here. (See ["umask" in perlfunc](perlfunc#umask).)
DIAGNOSTICS
-----------
On failure, the `tie` call returns an undefined value and probably sets `$!` to contain the reason the file could not be tied.
###
`ndbm store returned -1, errno 22, key "..." at ...`
This warning is emitted when you try to store a key or a value that is too long. It means that the change was not recorded in the database. See BUGS AND WARNINGS below.
SECURITY AND PORTABILITY
-------------------------
**Do not accept NDBM files from untrusted sources.**
On modern Linux systems these are typically GDBM files, which are not portable across platforms.
The GDBM documentation doesn't imply that files from untrusted sources can be safely used with `libgdbm`.
Systems that don't use GDBM compatibilty for ndbm support will be using a platform specific library, possibly inherited from BSD systems, where it may or may not be safe to use an untrusted file.
A maliciously crafted file might cause perl to crash or even expose a security vulnerability.
BUGS AND WARNINGS
------------------
There are a number of limits on the size of the data that you can store in the NDBM file. The most important is that the length of a key, plus the length of its associated value, may not exceed 1008 bytes.
See ["tie" in perlfunc](perlfunc#tie), <perldbmfilter>, [Fcntl](fcntl)
perl Net::netent Net::netent
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLES](#EXAMPLES)
* [NOTE](#NOTE)
* [AUTHOR](#AUTHOR)
NAME
----
Net::netent - by-name interface to Perl's built-in getnet\*() functions
SYNOPSIS
--------
```
use Net::netent qw(:FIELDS);
getnetbyname("loopback") or die "bad net";
printf "%s is %08X\n", $n_name, $n_net;
use Net::netent;
$n = getnetbyname("loopback") or die "bad net";
{ # there's gotta be a better way, eh?
@bytes = unpack("C4", pack("N", $n->net));
shift @bytes while @bytes && $bytes[0] == 0;
}
printf "%s is %08X [%d.%d.%d.%d]\n", $n->name, $n->net, @bytes;
```
DESCRIPTION
-----------
This module's default exports override the core getnetbyname() and getnetbyaddr() functions, replacing them with versions that return "Net::netent" objects. This object has methods that return the similarly named structure field name from the C's netent structure from *netdb.h*; namely name, aliases, addrtype, and net. The aliases method returns an array reference, the rest scalars.
You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. (Note that this still overrides your core functions.) Access these fields as variables named with a preceding `n_`. Thus, `$net_obj->name()` corresponds to $n\_name if you import the fields. Array references are available as regular array variables, so for example `@{ $net_obj->aliases() }` would be simply @n\_aliases.
The getnet() function is a simple front-end that forwards a numeric argument to getnetbyaddr(), and the rest to getnetbyname().
To access this functionality without the core overrides, pass the `use` an empty import list, and then access function functions with their full qualified names. On the other hand, the built-ins are still available via the `CORE::` pseudo-package.
EXAMPLES
--------
The getnet() functions do this in the Perl core:
```
sv_setiv(sv, (I32)nent->n_net);
```
The gethost() functions do this in the Perl core:
```
sv_setpvn(sv, hent->h_addr, len);
```
That means that the address comes back in binary for the host functions, and as a regular perl integer for the net ones. This seems a bug, but here's how to deal with it:
```
use strict;
use Socket;
use Net::netent;
@ARGV = ('loopback') unless @ARGV;
my($n, $net);
for $net ( @ARGV ) {
unless ($n = getnetbyname($net)) {
warn "$0: no such net: $net\n";
next;
}
printf "\n%s is %s%s\n",
$net,
lc($n->name) eq lc($net) ? "" : "*really* ",
$n->name;
print "\taliases are ", join(", ", @{$n->aliases}), "\n"
if @{$n->aliases};
# this is stupid; first, why is this not in binary?
# second, why am i going through these convolutions
# to make it looks right
{
my @a = unpack("C4", pack("N", $n->net));
shift @a while @a && $a[0] == 0;
printf "\taddr is %s [%d.%d.%d.%d]\n", $n->net, @a;
}
if ($n = getnetbyaddr($n->net)) {
if (lc($n->name) ne lc($net)) {
printf "\tThat addr reverses to net %s!\n", $n->name;
$net = $n->name;
redo;
}
}
}
```
NOTE
----
While this class is currently implemented using the Class::Struct module to build a struct-like class, you shouldn't rely upon this.
AUTHOR
------
Tom Christiansen
perl Storable Storable
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [MEMORY STORE](#MEMORY-STORE)
* [ADVISORY LOCKING](#ADVISORY-LOCKING)
* [SPEED](#SPEED)
* [CANONICAL REPRESENTATION](#CANONICAL-REPRESENTATION)
* [CODE REFERENCES](#CODE-REFERENCES)
* [FORWARD COMPATIBILITY](#FORWARD-COMPATIBILITY)
* [ERROR REPORTING](#ERROR-REPORTING)
* [WIZARDS ONLY](#WIZARDS-ONLY)
+ [Hooks](#Hooks)
+ [Predicates](#Predicates)
+ [Recursion](#Recursion)
+ [Deep Cloning](#Deep-Cloning)
* [Storable magic](#Storable-magic)
* [EXAMPLES](#EXAMPLES)
* [SECURITY WARNING](#SECURITY-WARNING)
* [WARNING](#WARNING)
* [REGULAR EXPRESSIONS](#REGULAR-EXPRESSIONS)
* [BUGS](#BUGS)
+ [64 bit data in perl 5.6.0 and 5.6.1](#64-bit-data-in-perl-5.6.0-and-5.6.1)
* [CREDITS](#CREDITS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Storable - persistence for Perl data structures
SYNOPSIS
--------
```
use Storable;
store \%table, 'file';
$hashref = retrieve('file');
use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
# Network order
nstore \%table, 'file';
$hashref = retrieve('file'); # There is NO nretrieve()
# Storing to and retrieving from an already opened file
store_fd \@array, \*STDOUT;
nstore_fd \%table, \*STDOUT;
$aryref = fd_retrieve(\*SOCKET);
$hashref = fd_retrieve(\*SOCKET);
# Serializing to memory
$serialized = freeze \%table;
%table_clone = %{ thaw($serialized) };
# Deep (recursive) cloning
$cloneref = dclone($ref);
# Advisory locking
use Storable qw(lock_store lock_nstore lock_retrieve)
lock_store \%table, 'file';
lock_nstore \%table, 'file';
$hashref = lock_retrieve('file');
```
DESCRIPTION
-----------
The Storable package brings persistence to your Perl data structures containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be conveniently stored to disk and retrieved at a later time.
It can be used in the regular procedural way by calling `store` with a reference to the object to be stored, along with the file name where the image should be written.
The routine returns `undef` for I/O problems or other internal error, a true value otherwise. Serious errors are propagated as a `die` exception.
To retrieve data stored to disk, use `retrieve` with a file name. The objects stored into that file are recreated into memory for you, and a *reference* to the root object is returned. In case an I/O error occurs while reading, `undef` is returned instead. Other serious errors are propagated via `die`.
Since storage is performed recursively, you might want to stuff references to objects that share a lot of common data into a single array or hash table, and then store that object. That way, when you retrieve back the whole thing, the objects will continue to share what they originally shared.
At the cost of a slight header overhead, you may store to an already opened file descriptor using the `store_fd` routine, and retrieve from a file via `fd_retrieve`. Those names aren't imported by default, so you will have to do that explicitly if you need those routines. The file descriptor you supply must be already opened, for read if you're going to retrieve and for write if you wish to store.
```
store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
$hashref = fd_retrieve(*STDIN);
```
You can also store data in network order to allow easy sharing across multiple platforms, or when storing on a socket known to be remotely connected. The routines to call have an initial `n` prefix for *network*, as in `nstore` and `nstore_fd`. At retrieval time, your data will be correctly restored so you don't have to know whether you're restoring from native or network ordered data. Double values are stored stringified to ensure portability as well, at the slight risk of loosing some precision in the last decimals.
When using `fd_retrieve`, objects are retrieved in sequence, one object (i.e. one recursive tree) per associated `store_fd`.
If you're more from the object-oriented camp, you can inherit from Storable and directly store your objects by invoking `store` as a method. The fact that the root of the to-be-stored tree is a blessed reference (i.e. an object) is special-cased so that the retrieve does not provide a reference to that object but rather the blessed object reference itself. (Otherwise, you'd get a reference to that blessed object).
MEMORY STORE
-------------
The Storable engine can also store data into a Perl scalar instead, to later retrieve them. This is mainly used to freeze a complex structure in some safe compact memory place (where it can possibly be sent to another process via some IPC, since freezing the structure also serializes it in effect). Later on, and maybe somewhere else, you can thaw the Perl scalar out and recreate the original complex structure in memory.
Surprisingly, the routines to be called are named `freeze` and `thaw`. If you wish to send out the frozen scalar to another machine, use `nfreeze` instead to get a portable image.
Note that freezing an object structure and immediately thawing it actually achieves a deep cloning of that structure:
```
dclone(.) = thaw(freeze(.))
```
Storable provides you with a `dclone` interface which does not create that intermediary scalar but instead freezes the structure in some internal memory space and then immediately thaws it out.
ADVISORY LOCKING
-----------------
The `lock_store` and `lock_nstore` routine are equivalent to `store` and `nstore`, except that they get an exclusive lock on the file before writing. Likewise, `lock_retrieve` does the same as `retrieve`, but also gets a shared lock on the file before reading.
As with any advisory locking scheme, the protection only works if you systematically use `lock_store` and `lock_retrieve`. If one side of your application uses `store` whilst the other uses `lock_retrieve`, you will get no protection at all.
The internal advisory locking is implemented using Perl's flock() routine. If your system does not support any form of flock(), or if you share your files across NFS, you might wish to use other forms of locking by using modules such as LockFile::Simple which lock a file using a filesystem entry, instead of locking the file descriptor.
SPEED
-----
The heart of Storable is written in C for decent speed. Extra low-level optimizations have been made when manipulating perl internals, to sacrifice encapsulation for the benefit of greater speed.
CANONICAL REPRESENTATION
-------------------------
Normally, Storable stores elements of hashes in the order they are stored internally by Perl, i.e. pseudo-randomly. If you set `$Storable::canonical` to some `TRUE` value, Storable will store hashes with the elements sorted by their key. This allows you to compare data structures by comparing their frozen representations (or even the compressed frozen representations), which can be useful for creating lookup tables for complicated queries.
Canonical order does not imply network order; those are two orthogonal settings.
CODE REFERENCES
----------------
Since Storable version 2.05, CODE references may be serialized with the help of <B::Deparse>. To enable this feature, set `$Storable::Deparse` to a true value. To enable deserialization, `$Storable::Eval` should be set to a true value. Be aware that deserialization is done through `eval`, which is dangerous if the Storable file contains malicious data. You can set `$Storable::Eval` to a subroutine reference which would be used instead of `eval`. See below for an example using a [Safe](safe) compartment for deserialization of CODE references.
If `$Storable::Deparse` and/or `$Storable::Eval` are set to false values, then the value of `$Storable::forgive_me` (see below) is respected while serializing and deserializing.
FORWARD COMPATIBILITY
----------------------
This release of Storable can be used on a newer version of Perl to serialize data which is not supported by earlier Perls. By default, Storable will attempt to do the right thing, by `croak()`ing if it encounters data that it cannot deserialize. However, the defaults can be changed as follows:
utf8 data Perl 5.6 added support for Unicode characters with code points > 255, and Perl 5.8 has full support for Unicode characters in hash keys. Perl internally encodes strings with these characters using utf8, and Storable serializes them as utf8. By default, if an older version of Perl encounters a utf8 value it cannot represent, it will `croak()`. To change this behaviour so that Storable deserializes utf8 encoded values as the string of bytes (effectively dropping the *is\_utf8* flag) set `$Storable::drop_utf8` to some `TRUE` value. This is a form of data loss, because with `$drop_utf8` true, it becomes impossible to tell whether the original data was the Unicode string, or a series of bytes that happen to be valid utf8.
restricted hashes Perl 5.8 adds support for restricted hashes, which have keys restricted to a given set, and can have values locked to be read only. By default, when Storable encounters a restricted hash on a perl that doesn't support them, it will deserialize it as a normal hash, silently discarding any placeholder keys and leaving the keys and all values unlocked. To make Storable `croak()` instead, set `$Storable::downgrade_restricted` to a `FALSE` value. To restore the default set it back to some `TRUE` value.
The cperl PERL\_PERTURB\_KEYS\_TOP hash strategy has a known problem with restricted hashes.
huge objects On 64bit systems some data structures may exceed the 2G (i.e. I32\_MAX) limit. On 32bit systems also strings between I32 and U32 (2G-4G). Since Storable 3.00 (not in perl5 core) we are able to store and retrieve these objects, even if perl5 itself is not able to handle them. These are strings longer then 4G, arrays with more then 2G elements and hashes with more then 2G elements. cperl forbids hashes with more than 2G elements, but this fail in cperl then. perl5 itself at least until 5.26 allows it, but cannot iterate over them. Note that creating those objects might cause out of memory exceptions by the operating system before perl has a chance to abort.
files from future versions of Storable Earlier versions of Storable would immediately croak if they encountered a file with a higher internal version number than the reading Storable knew about. Internal version numbers are increased each time new data types (such as restricted hashes) are added to the vocabulary of the file format. This meant that a newer Storable module had no way of writing a file readable by an older Storable, even if the writer didn't store newer data types.
This version of Storable will defer croaking until it encounters a data type in the file that it does not recognize. This means that it will continue to read files generated by newer Storable modules which are careful in what they write out, making it easier to upgrade Storable modules in a mixed environment.
The old behaviour of immediate croaking can be re-instated by setting `$Storable::accept_future_minor` to some `FALSE` value.
All these variables have no effect on a newer Perl which supports the relevant feature.
ERROR REPORTING
----------------
Storable uses the "exception" paradigm, in that it does not try to workaround failures: if something bad happens, an exception is generated from the caller's perspective (see [Carp](carp) and `croak()`). Use eval {} to trap those exceptions.
When Storable croaks, it tries to report the error via the `logcroak()` routine from the `Log::Agent` package, if it is available.
Normal errors are reported by having store() or retrieve() return `undef`. Such errors are usually I/O errors (or truncated stream errors at retrieval).
When Storable throws the "Max. recursion depth with nested structures exceeded" error we are already out of stack space. Unfortunately on some earlier perl versions cleaning up a recursive data structure recurses into the free calls, which will lead to stack overflows in the cleanup. This data structure is not properly cleaned up then, it will only be destroyed during global destruction.
WIZARDS ONLY
-------------
### Hooks
Any class may define hooks that will be called during the serialization and deserialization process on objects that are instances of that class. Those hooks can redefine the way serialization is performed (and therefore, how the symmetrical deserialization should be conducted).
Since we said earlier:
```
dclone(.) = thaw(freeze(.))
```
everything we say about hooks should also hold for deep cloning. However, hooks get to know whether the operation is a mere serialization, or a cloning.
Therefore, when serializing hooks are involved,
```
dclone(.) <> thaw(freeze(.))
```
Well, you could keep them in sync, but there's no guarantee it will always hold on classes somebody else wrote. Besides, there is little to gain in doing so: a serializing hook could keep only one attribute of an object, which is probably not what should happen during a deep cloning of that same object.
Here is the hooking interface:
`STORABLE_freeze` *obj*, *cloning*
The serializing hook, called on the object during serialization. It can be inherited, or defined in the class itself, like any other method.
Arguments: *obj* is the object to serialize, *cloning* is a flag indicating whether we're in a dclone() or a regular serialization via store() or freeze().
Returned value: A LIST `($serialized, $ref1, $ref2, ...)` where $serialized is the serialized form to be used, and the optional $ref1, $ref2, etc... are extra references that you wish to let the Storable engine serialize.
At deserialization time, you will be given back the same LIST, but all the extra references will be pointing into the deserialized structure.
The **first time** the hook is hit in a serialization flow, you may have it return an empty list. That will signal the Storable engine to further discard that hook for this class and to therefore revert to the default serialization of the underlying Perl data. The hook will again be normally processed in the next serialization.
Unless you know better, serializing hook should always say:
```
sub STORABLE_freeze {
my ($self, $cloning) = @_;
return if $cloning; # Regular default serialization
....
}
```
in order to keep reasonable dclone() semantics.
`STORABLE_thaw` *obj*, *cloning*, *serialized*, ... The deserializing hook called on the object during deserialization. But wait: if we're deserializing, there's no object yet... right?
Wrong: the Storable engine creates an empty one for you. If you know Eiffel, you can view `STORABLE_thaw` as an alternate creation routine.
This means the hook can be inherited like any other method, and that *obj* is your blessed reference for this particular instance.
The other arguments should look familiar if you know `STORABLE_freeze`: *cloning* is true when we're part of a deep clone operation, *serialized* is the serialized string you returned to the engine in `STORABLE_freeze`, and there may be an optional list of references, in the same order you gave them at serialization time, pointing to the deserialized objects (which have been processed courtesy of the Storable engine).
When the Storable engine does not find any `STORABLE_thaw` hook routine, it tries to load the class by requiring the package dynamically (using the blessed package name), and then re-attempts the lookup. If at that time the hook cannot be located, the engine croaks. Note that this mechanism will fail if you define several classes in the same file, but <perlmod> warned you.
It is up to you to use this information to populate *obj* the way you want.
Returned value: none.
`STORABLE_attach` *class*, *cloning*, *serialized*
While `STORABLE_freeze` and `STORABLE_thaw` are useful for classes where each instance is independent, this mechanism has difficulty (or is incompatible) with objects that exist as common process-level or system-level resources, such as singleton objects, database pools, caches or memoized objects.
The alternative `STORABLE_attach` method provides a solution for these shared objects. Instead of `STORABLE_freeze` --> `STORABLE_thaw`, you implement `STORABLE_freeze` --> `STORABLE_attach` instead.
Arguments: *class* is the class we are attaching to, *cloning* is a flag indicating whether we're in a dclone() or a regular de-serialization via thaw(), and *serialized* is the stored string for the resource object.
Because these resource objects are considered to be owned by the entire process/system, and not the "property" of whatever is being serialized, no references underneath the object should be included in the serialized string. Thus, in any class that implements `STORABLE_attach`, the `STORABLE_freeze` method cannot return any references, and `Storable` will throw an error if `STORABLE_freeze` tries to return references.
All information required to "attach" back to the shared resource object **must** be contained **only** in the `STORABLE_freeze` return string. Otherwise, `STORABLE_freeze` behaves as normal for `STORABLE_attach` classes.
Because `STORABLE_attach` is passed the class (rather than an object), it also returns the object directly, rather than modifying the passed object.
Returned value: object of type `class`
### Predicates
Predicates are not exportable. They must be called by explicitly prefixing them with the Storable package name.
`Storable::last_op_in_netorder`
The `Storable::last_op_in_netorder()` predicate will tell you whether network order was used in the last store or retrieve operation. If you don't know how to use this, just forget about it.
`Storable::is_storing`
Returns true if within a store operation (via STORABLE\_freeze hook).
`Storable::is_retrieving`
Returns true if within a retrieve operation (via STORABLE\_thaw hook).
### Recursion
With hooks comes the ability to recurse back to the Storable engine. Indeed, hooks are regular Perl code, and Storable is convenient when it comes to serializing and deserializing things, so why not use it to handle the serialization string?
There are a few things you need to know, however:
* From Storable 3.05 to 3.13 we probed for the stack recursion limit for references, arrays and hashes to a maximal depth of ~1200-35000, otherwise we might fall into a stack-overflow. On JSON::XS this limit is 512 btw. With references not immediately referencing each other there's no such limit yet, so you might fall into such a stack-overflow segfault.
This probing and the checks we performed have some limitations:
+ the stack size at build time might be different at run time, eg. the stack size may have been modified with ulimit(1). If it's larger at run time Storable may fail the freeze() or thaw() unnecessarily. If it's larger at build time Storable may segmentation fault when processing a deep structure at run time.
+ the stack size might be different in a thread.
+ array and hash recursion limits are checked separately against the same recursion depth, a frozen structure with a large sequence of nested arrays within many nested hashes may exhaust the processor stack without triggering Storable's recursion protection.So these now have simple defaults rather than probing at build-time.
You can control the maximum array and hash recursion depths by modifying `$Storable::recursion_limit` and `$Storable::recursion_limit_hash` respectively. Either can be set to `-1` to prevent any depth checks, though this isn't recommended.
If you want to test what the limits are, the *stacksize* tool is included in the `Storable` distribution.
* You can create endless loops if the things you serialize via freeze() (for instance) point back to the object we're trying to serialize in the hook.
* Shared references among objects will not stay shared: if we're serializing the list of object [A, C] where both object A and C refer to the SAME object B, and if there is a serializing hook in A that says freeze(B), then when deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D, a deep clone of B'. The topology was not preserved.
* The maximal stack recursion limit for your system is returned by `stack_depth()` and `stack_depth_hash()`. The hash limit is usually half the size of the array and ref limit, as the Perl hash API is not optimal.
That's why `STORABLE_freeze` lets you provide a list of references to serialize. The engine guarantees that those will be serialized in the same context as the other objects, and therefore that shared objects will stay shared.
In the above [A, C] example, the `STORABLE_freeze` hook could return:
```
("something", $self->{B})
```
and the B part would be serialized by the engine. In `STORABLE_thaw`, you would get back the reference to the B' object, deserialized for you.
Therefore, recursion should normally be avoided, but is nonetheless supported.
###
Deep Cloning
There is a Clone module available on CPAN which implements deep cloning natively, i.e. without freezing to memory and thawing the result. It is aimed to replace Storable's dclone() some day. However, it does not currently support Storable hooks to redefine the way deep cloning is performed.
Storable magic
---------------
Yes, there's a lot of that :-) But more precisely, in UNIX systems there's a utility called `file`, which recognizes data files based on their contents (usually their first few bytes). For this to work, a certain file called *magic* needs to taught about the *signature* of the data. Where that configuration file lives depends on the UNIX flavour; often it's something like */usr/share/misc/magic* or */etc/magic*. Your system administrator needs to do the updating of the *magic* file. The necessary signature information is output to STDOUT by invoking Storable::show\_file\_magic(). Note that the GNU implementation of the `file` utility, version 3.38 or later, is expected to contain support for recognising Storable files out-of-the-box, in addition to other kinds of Perl files.
You can also use the following functions to extract the file header information from Storable images:
$info = Storable::file\_magic( $filename ) If the given file is a Storable image return a hash describing it. If the file is readable, but not a Storable image return `undef`. If the file does not exist or is unreadable then croak.
The hash returned has the following elements:
`version` This returns the file format version. It is a string like "2.7".
Note that this version number is not the same as the version number of the Storable module itself. For instance Storable v0.7 create files in format v2.0 and Storable v2.15 create files in format v2.7. The file format version number only increment when additional features that would confuse older versions of the module are added.
Files older than v2.0 will have the one of the version numbers "-1", "0" or "1". No minor number was used at that time.
`version_nv` This returns the file format version as number. It is a string like "2.007". This value is suitable for numeric comparisons.
The constant function `Storable::BIN_VERSION_NV` returns a comparable number that represents the highest file version number that this version of Storable fully supports (but see discussion of `$Storable::accept_future_minor` above). The constant `Storable::BIN_WRITE_VERSION_NV` function returns what file version is written and might be less than `Storable::BIN_VERSION_NV` in some configurations.
`major`, `minor`
This also returns the file format version. If the version is "2.7" then major would be 2 and minor would be 7. The minor element is missing for when major is less than 2.
`hdrsize` The is the number of bytes that the Storable header occupies.
`netorder` This is TRUE if the image store data in network order. This means that it was created with nstore() or similar.
`byteorder` This is only present when `netorder` is FALSE. It is the $Config{byteorder} string of the perl that created this image. It is a string like "1234" (32 bit little endian) or "87654321" (64 bit big endian). This must match the current perl for the image to be readable by Storable.
`intsize`, `longsize`, `ptrsize`, `nvsize`
These are only present when `netorder` is FALSE. These are the sizes of various C datatypes of the perl that created this image. These must match the current perl for the image to be readable by Storable.
The `nvsize` element is only present for file format v2.2 and higher.
`file` The name of the file.
$info = Storable::read\_magic( $buffer )
$info = Storable::read\_magic( $buffer, $must\_be\_file ) The $buffer should be a Storable image or the first few bytes of it. If $buffer starts with a Storable header, then a hash describing the image is returned, otherwise `undef` is returned.
The hash has the same structure as the one returned by Storable::file\_magic(). The `file` element is true if the image is a file image.
If the $must\_be\_file argument is provided and is TRUE, then return `undef` unless the image looks like it belongs to a file dump.
The maximum size of a Storable header is currently 21 bytes. If the provided $buffer is only the first part of a Storable image it should at least be this long to ensure that read\_magic() will recognize it as such.
EXAMPLES
--------
Here are some code samples showing a possible usage of Storable:
```
use Storable qw(store retrieve freeze thaw dclone);
%color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";
$colref = retrieve('mycolors');
die "Unable to retrieve from mycolors!\n" unless defined $colref;
printf "Blue is still %lf\n", $colref->{'Blue'};
$colref2 = dclone(\%color);
$str = freeze(\%color);
printf "Serialization of %%color is %d bytes long.\n", length($str);
$colref3 = thaw($str);
```
which prints (on my machine):
```
Blue is still 0.100000
Serialization of %color is 102 bytes long.
```
Serialization of CODE references and deserialization in a safe compartment:
```
use Storable qw(freeze thaw);
use Safe;
use strict;
my $safe = new Safe;
# because of opcodes used in "use strict":
$safe->permit(qw(:default require));
local $Storable::Deparse = 1;
local $Storable::Eval = sub { $safe->reval($_[0]) };
my $serialized = freeze(sub { 42 });
my $code = thaw($serialized);
$code->() == 42;
```
SECURITY WARNING
-----------------
**Do not accept Storable documents from untrusted sources!**
Some features of Storable can lead to security vulnerabilities if you accept Storable documents from untrusted sources with the default flags. Most obviously, the optional (off by default) CODE reference serialization feature allows transfer of code to the deserializing process. Furthermore, any serialized object will cause Storable to helpfully load the module corresponding to the class of the object in the deserializing module. For manipulated module names, this can load almost arbitrary code. Finally, the deserialized object's destructors will be invoked when the objects get destroyed in the deserializing process. Maliciously crafted Storable documents may put such objects in the value of a hash key that is overridden by another key/value pair in the same hash, thus causing immediate destructor execution.
To disable blessing objects while thawing/retrieving remove the flag `BLESS_OK` = 2 from `$Storable::flags` or set the 2nd argument for thaw/retrieve to 0.
To disable tieing data while thawing/retrieving remove the flag `TIE_OK` = 4 from `$Storable::flags` or set the 2nd argument for thaw/retrieve to 0.
With the default setting of `$Storable::flags` = 6, creating or destroying random objects, even renamed objects can be controlled by an attacker. See CVE-2015-1592 and its metasploit module.
If your application requires accepting data from untrusted sources, you are best off with a less powerful and more-likely safe serialization format and implementation. If your data is sufficiently simple, <Cpanel::JSON::XS>, <Data::MessagePack> or [Sereal](sereal) are the best choices and offer maximum interoperability, but note that Sereal is [unsafe by default](Sereal::Decoder#ROBUSTNESS).
WARNING
-------
If you're using references as keys within your hash tables, you're bound to be disappointed when retrieving your data. Indeed, Perl stringifies references used as hash table keys. If you later wish to access the items via another reference stringification (i.e. using the same reference that was used for the key originally to record the value into the hash table), it will work because both references stringify to the same string.
It won't work across a sequence of `store` and `retrieve` operations, however, because the addresses in the retrieved objects, which are part of the stringified references, will probably differ from the original addresses. The topology of your structure is preserved, but not hidden semantics like those.
On platforms where it matters, be sure to call `binmode()` on the descriptors that you pass to Storable functions.
Storing data canonically that contains large hashes can be significantly slower than storing the same data normally, as temporary arrays to hold the keys for each hash have to be allocated, populated, sorted and freed. Some tests have shown a halving of the speed of storing -- the exact penalty will depend on the complexity of your data. There is no slowdown on retrieval.
REGULAR EXPRESSIONS
--------------------
Storable now has experimental support for storing regular expressions, but there are significant limitations:
* perl 5.8 or later is required.
* regular expressions with code blocks, ie `/(?{ ... })/` or `/(??{ ... })/` will throw an exception when thawed.
* regular expression syntax and flags have changed over the history of perl, so a regular expression that you freeze in one version of perl may fail to thaw or behave differently in another version of perl.
* depending on the version of perl, regular expressions can change in behaviour depending on the context, but later perls will bake that behaviour into the regexp.
Storable will throw an exception if a frozen regular expression cannot be thawed.
BUGS
----
You can't store GLOB, FORMLINE, etc.... If you can define semantics for those operations, feel free to enhance Storable so that it can deal with them.
The store functions will `croak` if they run into such references unless you set `$Storable::forgive_me` to some `TRUE` value. In that case, the fatal message is converted to a warning and some meaningless string is stored instead.
Setting `$Storable::canonical` may not yield frozen strings that compare equal due to possible stringification of numbers. When the string version of a scalar exists, it is the form stored; therefore, if you happen to use your numbers as strings between two freezing operations on the same data structures, you will get different results.
When storing doubles in network order, their value is stored as text. However, you should also not expect non-numeric floating-point values such as infinity and "not a number" to pass successfully through a nstore()/retrieve() pair.
As Storable neither knows nor cares about character sets (although it does know that characters may be more than eight bits wide), any difference in the interpretation of character codes between a host and a target system is your problem. In particular, if host and target use different code points to represent the characters used in the text representation of floating-point numbers, you will not be able be able to exchange floating-point data, even with nstore().
`Storable::drop_utf8` is a blunt tool. There is no facility either to return **all** strings as utf8 sequences, or to attempt to convert utf8 data back to 8 bit and `croak()` if the conversion fails.
Prior to Storable 2.01, no distinction was made between signed and unsigned integers on storing. By default Storable prefers to store a scalars string representation (if it has one) so this would only cause problems when storing large unsigned integers that had never been converted to string or floating point. In other words values that had been generated by integer operations such as logic ops and then not used in any string or arithmetic context before storing.
###
64 bit data in perl 5.6.0 and 5.6.1
This section only applies to you if you have existing data written out by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which has been configured with 64 bit integer support (not the default) If you got a precompiled perl, rather than running Configure to build your own perl from source, then it almost certainly does not affect you, and you can stop reading now (unless you're curious). If you're using perl on Windows it does not affect you.
Storable writes a file header which contains the sizes of various C language types for the C compiler that built Storable (when not writing in network order), and will refuse to load files written by a Storable not on the same (or compatible) architecture. This check and a check on machine byteorder is needed because the size of various fields in the file are given by the sizes of the C language types, and so files written on different architectures are incompatible. This is done for increased speed. (When writing in network order, all fields are written out as standard lengths, which allows full interworking, but takes longer to read and write)
Perl 5.6.x introduced the ability to optional configure the perl interpreter to use C's `long long` type to allow scalars to store 64 bit integers on 32 bit systems. However, due to the way the Perl configuration system generated the C configuration files on non-Windows platforms, and the way Storable generates its header, nothing in the Storable file header reflected whether the perl writing was using 32 or 64 bit integers, despite the fact that Storable was storing some data differently in the file. Hence Storable running on perl with 64 bit integers will read the header from a file written by a 32 bit perl, not realise that the data is actually in a subtly incompatible format, and then go horribly wrong (possibly crashing) if it encountered a stored integer. This is a design failure.
Storable has now been changed to write out and read in a file header with information about the size of integers. It's impossible to detect whether an old file being read in was written with 32 or 64 bit integers (they have the same header) so it's impossible to automatically switch to a correct backwards compatibility mode. Hence this Storable defaults to the new, correct behaviour.
What this means is that if you have data written by Storable 1.x running on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux then by default this Storable will refuse to read it, giving the error *Byte order is not compatible*. If you have such data then you should set `$Storable::interwork_56_64bit` to a true value to make this Storable read and write files with the old header. You should also migrate your data, or any older perl you are communicating with, to this current version of Storable.
If you don't have data written with specific configuration of perl described above, then you do not and should not do anything. Don't set the flag - not only will Storable on an identically configured perl refuse to load them, but Storable a differently configured perl will load them believing them to be correct for it, and then may well fail or crash part way through reading them.
CREDITS
-------
Thank you to (in chronological order):
```
Jarkko Hietaniemi <[email protected]>
Ulrich Pfeifer <[email protected]>
Benjamin A. Holzman <[email protected]>
Andrew Ford <[email protected]>
Gisle Aas <[email protected]>
Jeff Gresham <[email protected]>
Murray Nesbitt <[email protected]>
Marc Lehmann <[email protected]>
Justin Banks <[email protected]>
Jarkko Hietaniemi <[email protected]> (AGAIN, as perl 5.7.0 Pumpkin!)
Salvador Ortiz Garcia <[email protected]>
Dominic Dunlop <[email protected]>
Erik Haugan <[email protected]>
Benjamin A. Holzman <[email protected]>
Reini Urban <[email protected]>
Todd Rinaldo <[email protected]>
Aaron Crane <[email protected]>
```
for their bug reports, suggestions and contributions.
Benjamin Holzman contributed the tied variable support, Andrew Ford contributed the canonical order for hashes, and Gisle Aas fixed a few misunderstandings of mine regarding the perl internals, and optimized the emission of "tags" in the output streams by simply counting the objects instead of tagging them (leading to a binary incompatibility for the Storable image starting at version 0.6--older images are, of course, still properly understood). Murray Nesbitt made Storable thread-safe. Marc Lehmann added overloading and references to tied items support. Benjamin Holzman added a performance improvement for overloaded classes; thanks to Grant Street Group for footing the bill. Reini Urban took over maintenance from p5p, and added security fixes and huge object support.
AUTHOR
------
Storable was written by Raphael Manfredi *<Raphael\[email protected]>* Maintenance is now done by cperl <http://perl11.org/cperl>
Please e-mail us with problems, bug fixes, comments and complaints, although if you have compliments you should send them to Raphael. Please don't e-mail Raphael with problems, as he no longer works on Storable, and your message will be delayed while he forwards it to us.
SEE ALSO
---------
[Clone](clone).
| programming_docs |
perl perlgov perlgov
=======
CONTENTS
--------
* [NAME](#NAME)
* [PREAMBLE](#PREAMBLE)
* [Mandate](#Mandate)
* [Definitions](#Definitions)
+ [The Core Team](#The-Core-Team)
- [Powers](#Powers)
- [Membership](#Membership)
- [Term](#Term)
- [Removal](#Removal)
- [Inactivity](#Inactivity)
- [No Confidence in the Steering Council](#No-Confidence-in-the-Steering-Council)
- [Amending Perl Rules of Governance](#Amending-Perl-Rules-of-Governance)
- [Rules for Voting](#Rules-for-Voting)
+ [The Steering Council](#The-Steering-Council)
- [Powers](#Powers1)
- [Term](#Term1)
- [Removal](#Removal1)
- [Rules for Elections](#Rules-for-Elections)
+ [The Vote Administrator](#The-Vote-Administrator)
* [Steering Council Members](#Steering-Council-Members)
* [Core Team Members](#Core-Team-Members)
+ [Active Members](#Active-Members)
+ [Inactive Members](#Inactive-Members)
NAME
----
perlgov - Perl Rules of Governance
PREAMBLE
--------
We are forming a system of governance for development of the Perl programming language.
The scope of governance includes the language definition, its implementation, its test suite, its documentation, and the policies and procedures by which it is developed and maintained.
The system of governance includes definitions of the groups that will make decisions, the rules by which these groups are formed and changed, and the enumerated powers and constraints on the activities of these governing groups.
In forming a system of governance, we seek to achieve the following goals:
* We want a system that is functional. That means the governing groups may decide to undertake large changes, or they may decide to act conservatively, but they will act with intent and clear communication rather than fail to reach decisions when needed.
* We want a system that is trusted. That means that a reasonable contributor to Perl might disagree with decisions made by the governing groups, but will accept that they were made in good faith in consultation with relevant communities outside the governing groups.
* We want a system that is sustainable. That means it has provisions to self-modify, including ways of adding new members to the governing groups, ways to survive members becoming inactive, and ways of amending the rules of governance themselves if needed.
* We want a system that is transparent. That means that it will prefer policies that manage ordinary matters in public, and it will prefer secrecy in a limited number of situations.
* We want a system that is respectful. That means that it will establish standards of civil discourse that allow for healthy disagreement but avoid rancor and hostility in the community for which it is responsible.
Mandate
-------
Perl language governance shall work to:
* Maintain the quality, stability, and continuity of the Perl language and interpreter
* Guide the evolution of the Perl language and interpreter
* Establish and oversee the policies, procedures, systems, and mechanisms that enable a community of contributors to the Perl language and interpreter
* Encourage discussion and consensus among contributors as preferential to formal decision making by governance groups
* Facilitate communication between contributors and external stakeholders in the broader Perl ecosystem
Definitions
-----------
This document describes three roles involved in governance:
"Core Team"
"Steering Council"
"Vote Administrator" A section on each follows.
###
The Core Team
The Core Team are a group of trusted volunteers involved in the ongoing development of the Perl language and interpreter. They are not required to be language developers or committers.
References to specific votes are explained in the "Rules for Voting" section.
#### Powers
In addition to their contributions to the Perl language, the Core Team sets the rules of Perl governance, decides who participates in what role in governance, and delegates substantial decision making power to the Steering Council.
Specifically:
* They elect the Steering Council and have the power to remove Steering Council members.
* In concert with the Steering Council, they manage Core Team membership.
* In concert with the Steering Council, they have the power to modify the Perl Rules of Governance.
The Core Team do not have any authority over parts of the Perl ecosystem unrelated to developing and releasing the language itself. These include, but are not limited to:
* The Perl Foundation
* CPAN administration and CPAN authors
* perl.org, metacpan.org, and other community-maintained websites and services
* Perl conferences and events, except those organized directly by the Core Team
* Perl-related intellectual property legally owned by third-parties, except as allowed by applicable licenses or agreements
#### Membership
The initial Core Team members will be specified when this document is first ratified.
Any Core Team member may nominate someone to be added to the Core Team by sending the nomination to the Steering Council. The Steering Council must approve or reject the nomination. If approved, the Steering Council will organize a Membership Change Vote to ratify the addition.
Core Team members should demonstrate:
* A solid track record of being constructive and helpful
* Significant contributions to the project's goals, in any form
* Willingness to dedicate some time to improving Perl
Contributions are not limited to code. Here is an incomplete list of areas where contributions may be considered for joining the Core Team:
* Working on community management and outreach
* Providing support on mailing lists, IRC, or other forums
* Triaging tickets
* Writing patches (code, docs, or tests)
* Reviewing patches (code, docs, or tests)
* Participating in design discussions
* Providing expertise in a particular domain (security, i18n, etc.)
* Managing Perl infrastructure (websites, CI, documentation, etc.)
* Maintaining significant projects in the Perl ecosystem
* Creating visual designs
Core Team membership acknowledges sustained and valuable efforts that align well with the philosophy and the goals of the Perl project.
Core Team members are expected to act as role models for the community and custodians of the project, on behalf of the community and all those who rely on Perl.
#### Term
Core Team members serve until they are removed.
#### Removal
Core Team Members may resign their position at any time.
In exceptional circumstances, it may be necessary to remove someone from the Core Team against their will, such as for flagrant or repeated violations of a Code of Conduct. Any Core Team member may send a recall request to the Steering Council naming the individual to be removed. The Steering Council must approve or reject the recall request. If approved, the Steering Council will organize a Membership Change vote to ratify the removal.
If the removed member is also on the Steering Council, then they are removed from the Steering Council as well.
#### Inactivity
Core Team members who have stopped contributing are encouraged to declare themselves "inactive". Inactive members do not nominate or vote. Inactive members may declare themselves active at any time, except when a vote has been proposed and is not concluded. Eligibility to nominate or vote will be determined by the Vote Administrator.
To record and honor their contributions, inactive Core Team members will continue to be listed alongside active members.
####
No Confidence in the Steering Council
The Core Team may remove either a single Steering Council member or the entire Steering Council via a No Confidence Vote.
A No Confidence Vote is triggered when a Core Team member calls for one publicly on an appropriate project communication channel, and another Core Team member seconds the proposal.
If a No Confidence Vote removes all Steering Council members, the Vote Administrator of the No Confidence Vote will then administer an election to select a new Steering Council.
####
Amending Perl Rules of Governance
Any Core Team member may propose amending the Perl Rules of Governance by sending a proposal to the Steering Council. The Steering Council must decide to approve or reject the proposal. If approved, the Steering Council will organize an Amendment Vote.
####
Rules for Voting
Membership Change, Amendment, and No Confidence Votes require 2/3 of participating votes from Core Team members to pass.
A Vote Administrator must be selected following the rules in the "Vote Administrator" section.
The vote occurs in two steps:
1. The Vote Administrator describes the proposal being voted upon. The Core Team then may discuss the matter in advance of voting.
2. Active Core Team members vote in favor or against the proposal. Voting is performed anonymously.
For a Membership Change Vote, each phase will last one week. For Amendment and No Confidence Votes, each phase will last two weeks.
###
The Steering Council
The Steering Council is a 3-person committee, elected by the Core Team. Candidates are not required to be members of the Core Team. Non-member candidates are added to the Core Team if elected as if by a Membership Change Vote.
References to specific elections are explained in the "Rules for Elections" section.
#### Powers
The Steering Council has broad authority to make decisions about the development of the Perl language, the interpreter, and all other components, systems and processes that result in new releases of the language interpreter.
For example, it can:
* Manage the schedule and process for shipping new releases
* Establish procedures for proposing, discussing and deciding upon changes to the language
* Delegate power to individuals on or outside the Steering Council
Decisions of the Steering Council will be made by majority vote of non-vacant seats on the council.
The Steering Council should look for ways to use these powers as little as possible. Instead of voting, it's better to seek consensus. Instead of ruling on individual cases, it's better to define standards and processes that apply to all cases.
As with the Core Team, the Steering Council does not have any authority over parts of the Perl ecosystem unrelated to developing and releasing the language itself.
The Steering Council does not have the power to modify the Perl Rules of Governance, except as provided in the section "Amending Perl Rules of Governance".
#### Term
A new Steering Council will be chosen by a Term Election after each stable feature release (that is, change to `PERL_REVISION` or `PERL_VERSION`) or after two years, whichever comes first. The Term Election will be organized within two weeks of the triggering event. The council members will serve until the completion of the next Term Election unless they are removed.
#### Removal
Steering Council members may resign their position at any time.
Whenever there are vacancies on the Steering Council, the council will organize a Special Election within one week after the vacancy occurs. If the entire Steering Council is ever vacant, a Term Election will be held instead.
The Steering Council may defer the Special Election for up to twelve weeks. Their intent to do so must be publicly stated to the Core Team. If any active Core Team member objects within one week, the Special Election must be organized within two weeks. At any time, the Steering Council may choose to cancel the deferment and immediately commence organizing a Special Election.
If a Steering Council member is deceased, or drops out of touch and cannot be contacted for a month or longer, then the rest of the council may vote to declare their seat vacant. If an absent member returns after such a declaration is made, they are not reinstated automatically, but may run in the Special Election to fill the vacancy.
Otherwise, Steering Council members may only be removed before the end of their term through a No Confidence Vote by the Core Team.
####
Rules for Elections
Term and Special Election are ranked-choice votes to construct an ordered list of candidates to fill vacancies in the Steering Council.
A Vote Administrator must be selected following the rules in the "Vote Administrator" section.
Both Term and Special Elections occur in two stages:
1. Candidates advertise their interest in serving. Candidates must be nominated by an active Core Team member. Self-nominations are allowed. Nominated candidates may share a statement about their candidacy with the Core Team.
2. If there are no more candidates than open seats, no vote is required. The candidates will be declared to have won when the nomination period ends.
Otherwise, active Core Team Members vote by ranking all candidates. Voting is performed anonymously. After voting is complete, candidates are ranked using the Condorcet Internet Voting Service's proportional representation mode. If a tie occurs, it may be resolved by mutual agreement among the tied candidates, or else the tie will be resolved through random selection by the Vote Administrator.
Anyone voted off the Core Team is not eligible to be a candidate for Steering Council unless re-instated to the Core Team.
For a Term Election, each phase will last two weeks. At the end of the second phase, the top three ranked candidates are elected as the new Steering Council.
For a Special Election, each phase will last one week. At the end of the second phase, vacancies are filled from the ordered list of candidates until no vacancies remain.
The election of the first Steering Council will be a Term Election. Ricardo Signes will be the Vote Administrator for the initial Term Election unless he is a candidate, in which case he will select a non-candidate administrator to replace him.
###
The Vote Administrator
Every election or vote requires a Vote Administrator who manages communication, collection of secret ballots, and all other necessary activities to complete the voting process.
Unless otherwise specified, the Steering Council selects the Vote Administrator.
A Vote Administrator must not be a member of the Steering Council nor a candidate or subject of the vote. A Vote Administrator may be a member of the Core Team and, if so, may cast a vote while also serving as administrator. If the Vote Administrator becomes a candidate during an election vote, they will appoint a non-candidate replacement.
If the entire Steering Council is vacant or is the subject of a No Confidence Vote, then the Core Team will select a Vote Administrator by consensus. If consensus cannot be reached within one week, the President of The Perl Foundation will select a Vote Administrator.
Steering Council Members
-------------------------
* Neil Bowers
* Paul Evans
* Ricardo Signes
Core Team Members
------------------
The current members of the Perl Core Team are:
###
Active Members
Chad Granum <[email protected]>
Chris 'BinGOs' Williams <[email protected]>
Craig Berry <[email protected]>
Dagfinn Ilmari Mannsåker <[email protected]>
David Golden <[email protected]>
David Mitchell <[email protected]>
H. Merijn Brand <[email protected]>
Hugo van der Sanden <[email protected]>
James E Keenan <[email protected]>
Jason McIntosh <[email protected]>
Karen Etheridge <[email protected]>
Karl Williamson <[email protected]>
Leon Timmermans <[email protected]>
Matthew Horsfall <[email protected]>
Max Maischein <[email protected]>
Neil Bowers <[email protected]>
Nicholas Clark <[email protected]>
Nicolas R <[email protected]>
Paul "LeoNerd" Evans <[email protected]>
Philippe "BooK" Bruhat <[email protected]>
Ricardo Signes <[email protected]>
Steve Hay <[email protected]>
Stuart Mackintosh <[email protected]>
Todd Rinaldo <[email protected]>
Tony Cook <[email protected]> ###
Inactive Members
Abhijit Menon-Sen <[email protected]>
Andy Dougherty <[email protected]>
Jan Dubois <[email protected]>
Jesse Vincent <[email protected]>
perl Digest::SHA Digest::SHA
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [SYNOPSIS (HMAC-SHA)](#SYNOPSIS-(HMAC-SHA))
* [ABSTRACT](#ABSTRACT)
* [DESCRIPTION](#DESCRIPTION)
* [UNICODE AND SIDE EFFECTS](#UNICODE-AND-SIDE-EFFECTS)
* [NIST STATEMENT ON SHA-1](#NIST-STATEMENT-ON-SHA-1)
* [PADDING OF BASE64 DIGESTS](#PADDING-OF-BASE64-DIGESTS)
* [EXPORT](#EXPORT)
* [EXPORTABLE FUNCTIONS](#EXPORTABLE-FUNCTIONS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [ACKNOWLEDGMENTS](#ACKNOWLEDGMENTS)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Digest::SHA - Perl extension for SHA-1/224/256/384/512
SYNOPSIS
--------
In programs:
```
# Functional interface
use Digest::SHA qw(sha1 sha1_hex sha1_base64 ...);
$digest = sha1($data);
$digest = sha1_hex($data);
$digest = sha1_base64($data);
$digest = sha256($data);
$digest = sha384_hex($data);
$digest = sha512_base64($data);
# Object-oriented
use Digest::SHA;
$sha = Digest::SHA->new($alg);
$sha->add($data); # feed data into stream
$sha->addfile(*F);
$sha->addfile($filename);
$sha->add_bits($bits);
$sha->add_bits($data, $nbits);
$sha_copy = $sha->clone; # make copy of digest object
$state = $sha->getstate; # save current state to string
$sha->putstate($state); # restore previous $state
$digest = $sha->digest; # compute digest
$digest = $sha->hexdigest;
$digest = $sha->b64digest;
```
From the command line:
```
$ shasum files
$ shasum --help
```
SYNOPSIS (HMAC-SHA)
--------------------
```
# Functional interface only
use Digest::SHA qw(hmac_sha1 hmac_sha1_hex ...);
$digest = hmac_sha1($data, $key);
$digest = hmac_sha224_hex($data, $key);
$digest = hmac_sha256_base64($data, $key);
```
ABSTRACT
--------
Digest::SHA is a complete implementation of the NIST Secure Hash Standard. It gives Perl programmers a convenient way to calculate SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256 message digests. The module can handle all types of input, including partial-byte data.
DESCRIPTION
-----------
Digest::SHA is written in C for speed. If your platform lacks a C compiler, you can install the functionally equivalent (but much slower) <Digest::SHA::PurePerl> module.
The programming interface is easy to use: it's the same one found in CPAN's [Digest](digest) module. So, if your applications currently use <Digest::MD5> and you'd prefer the stronger security of SHA, it's a simple matter to convert them.
The interface provides two ways to calculate digests: all-at-once, or in stages. To illustrate, the following short program computes the SHA-256 digest of "hello world" using each approach:
```
use Digest::SHA qw(sha256_hex);
$data = "hello world";
@frags = split(//, $data);
# all-at-once (Functional style)
$digest1 = sha256_hex($data);
# in-stages (OOP style)
$state = Digest::SHA->new(256);
for (@frags) { $state->add($_) }
$digest2 = $state->hexdigest;
print $digest1 eq $digest2 ?
"whew!\n" : "oops!\n";
```
To calculate the digest of an n-bit message where *n* is not a multiple of 8, use the *add\_bits()* method. For example, consider the 446-bit message consisting of the bit-string "110" repeated 148 times, followed by "11". Here's how to display its SHA-1 digest:
```
use Digest::SHA;
$bits = "110" x 148 . "11";
$sha = Digest::SHA->new(1)->add_bits($bits);
print $sha->hexdigest, "\n";
```
Note that for larger bit-strings, it's more efficient to use the two-argument version *add\_bits($data, $nbits)*, where *$data* is in the customary packed binary format used for Perl strings.
The module also lets you save intermediate SHA states to a string. The *getstate()* method generates portable, human-readable text describing the current state of computation. You can subsequently restore that state with *putstate()* to resume where the calculation left off.
To see what a state description looks like, just run the following:
```
use Digest::SHA;
print Digest::SHA->new->add("Shaw" x 1962)->getstate;
```
As an added convenience, the Digest::SHA module offers routines to calculate keyed hashes using the HMAC-SHA-1/224/256/384/512 algorithms. These services exist in functional form only, and mimic the style and behavior of the *sha()*, *sha\_hex()*, and *sha\_base64()* functions.
```
# Test vector from draft-ietf-ipsec-ciph-sha-256-01.txt
use Digest::SHA qw(hmac_sha256_hex);
print hmac_sha256_hex("Hi There", chr(0x0b) x 32), "\n";
```
UNICODE AND SIDE EFFECTS
-------------------------
Perl supports Unicode strings as of version 5.6. Such strings may contain wide characters, namely, characters whose ordinal values are greater than 255. This can cause problems for digest algorithms such as SHA that are specified to operate on sequences of bytes.
The rule by which Digest::SHA handles a Unicode string is easy to state, but potentially confusing to grasp: the string is interpreted as a sequence of byte values, where each byte value is equal to the ordinal value (viz. code point) of its corresponding Unicode character. That way, the Unicode string 'abc' has exactly the same digest value as the ordinary string 'abc'.
Since a wide character does not fit into a byte, the Digest::SHA routines croak if they encounter one. Whereas if a Unicode string contains no wide characters, the module accepts it quite happily. The following code illustrates the two cases:
```
$str1 = pack('U*', (0..255));
print sha1_hex($str1); # ok
$str2 = pack('U*', (0..256));
print sha1_hex($str2); # croaks
```
Be aware that the digest routines silently convert UTF-8 input into its equivalent byte sequence in the native encoding (cf. utf8::downgrade). This side effect influences only the way Perl stores the data internally, but otherwise leaves the actual value of the data intact.
NIST STATEMENT ON SHA-1
------------------------
NIST acknowledges that the work of Prof. Xiaoyun Wang constitutes a practical collision attack on SHA-1. Therefore, NIST encourages the rapid adoption of the SHA-2 hash functions (e.g. SHA-256) for applications requiring strong collision resistance, such as digital signatures.
ref. <http://csrc.nist.gov/groups/ST/hash/statement.html>
PADDING OF BASE64 DIGESTS
--------------------------
By convention, CPAN Digest modules do **not** pad their Base64 output. Problems can occur when feeding such digests to other software that expects properly padded Base64 encodings.
For the time being, any necessary padding must be done by the user. Fortunately, this is a simple operation: if the length of a Base64-encoded digest isn't a multiple of 4, simply append "=" characters to the end of the digest until it is:
```
while (length($b64_digest) % 4) {
$b64_digest .= '=';
}
```
To illustrate, *sha256\_base64("abc")* is computed to be
```
ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0
```
which has a length of 43. So, the properly padded version is
```
ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=
```
EXPORT
------
None by default.
EXPORTABLE FUNCTIONS
---------------------
Provided your C compiler supports a 64-bit type (e.g. the *long long* of C99, or *\_\_int64* used by Microsoft C/C++), all of these functions will be available for use. Otherwise, you won't be able to perform the SHA-384 and SHA-512 transforms, both of which require 64-bit operations.
*Functional style*
**sha1($data, ...)**
**sha224($data, ...)**
**sha256($data, ...)**
**sha384($data, ...)**
**sha512($data, ...)**
**sha512224($data, ...)**
**sha512256($data, ...)**
Logically joins the arguments into a single string, and returns its SHA-1/224/256/384/512 digest encoded as a binary string.
**sha1\_hex($data, ...)**
**sha224\_hex($data, ...)**
**sha256\_hex($data, ...)**
**sha384\_hex($data, ...)**
**sha512\_hex($data, ...)**
**sha512224\_hex($data, ...)**
**sha512256\_hex($data, ...)**
Logically joins the arguments into a single string, and returns its SHA-1/224/256/384/512 digest encoded as a hexadecimal string.
**sha1\_base64($data, ...)**
**sha224\_base64($data, ...)**
**sha256\_base64($data, ...)**
**sha384\_base64($data, ...)**
**sha512\_base64($data, ...)**
**sha512224\_base64($data, ...)**
**sha512256\_base64($data, ...)**
Logically joins the arguments into a single string, and returns its SHA-1/224/256/384/512 digest encoded as a Base64 string.
It's important to note that the resulting string does **not** contain the padding characters typical of Base64 encodings. This omission is deliberate, and is done to maintain compatibility with the family of CPAN Digest modules. See ["PADDING OF BASE64 DIGESTS"](#PADDING-OF-BASE64-DIGESTS) for details.
*OOP style*
**new($alg)**
Returns a new Digest::SHA object. Allowed values for *$alg* are 1, 224, 256, 384, 512, 512224, or 512256. It's also possible to use common string representations of the algorithm (e.g. "sha256", "SHA-384"). If the argument is missing, SHA-1 will be used by default.
Invoking *new* as an instance method will reset the object to the initial state associated with *$alg*. If the argument is missing, the object will continue using the same algorithm that was selected at creation.
**reset($alg)**
This method has exactly the same effect as *new($alg)*. In fact, *reset* is just an alias for *new*.
**hashsize** Returns the number of digest bits for this object. The values are 160, 224, 256, 384, 512, 224, and 256 for SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256, respectively.
**algorithm** Returns the digest algorithm for this object. The values are 1, 224, 256, 384, 512, 512224, and 512256 for SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256, respectively.
**clone** Returns a duplicate copy of the object.
**add($data, ...)**
Logically joins the arguments into a single string, and uses it to update the current digest state. In other words, the following statements have the same effect:
```
$sha->add("a"); $sha->add("b"); $sha->add("c");
$sha->add("a")->add("b")->add("c");
$sha->add("a", "b", "c");
$sha->add("abc");
```
The return value is the updated object itself.
**add\_bits($data, $nbits)**
**add\_bits($bits)**
Updates the current digest state by appending bits to it. The return value is the updated object itself.
The first form causes the most-significant *$nbits* of *$data* to be appended to the stream. The *$data* argument is in the customary binary format used for Perl strings.
The second form takes an ASCII string of "0" and "1" characters as its argument. It's equivalent to
```
$sha->add_bits(pack("B*", $bits), length($bits));
```
So, the following two statements do the same thing:
```
$sha->add_bits("111100001010");
$sha->add_bits("\xF0\xA0", 12);
```
Note that SHA-1 and SHA-2 use *most-significant-bit ordering* for their internal state. This means that
```
$sha3->add_bits("110");
```
is equivalent to
```
$sha3->add_bits("1")->add_bits("1")->add_bits("0");
```
**addfile(\*FILE)**
Reads from *FILE* until EOF, and appends that data to the current state. The return value is the updated object itself.
**addfile($filename [, $mode])**
Reads the contents of *$filename*, and appends that data to the current state. The return value is the updated object itself.
By default, *$filename* is simply opened and read; no special modes or I/O disciplines are used. To change this, set the optional *$mode* argument to one of the following values:
```
"b" read file in binary mode
"U" use universal newlines
"0" use BITS mode
```
The "U" mode is modeled on Python's "Universal Newlines" concept, whereby DOS and Mac OS line terminators are converted internally to UNIX newlines before processing. This ensures consistent digest values when working simultaneously across multiple file systems. **The "U" mode influences only text files**, namely those passing Perl's *-T* test; binary files are processed with no translation whatsoever.
The BITS mode ("0") interprets the contents of *$filename* as a logical stream of bits, where each ASCII '0' or '1' character represents a 0 or 1 bit, respectively. All other characters are ignored. This provides a convenient way to calculate the digest values of partial-byte data by using files, rather than having to write separate programs employing the *add\_bits* method.
**getstate** Returns a string containing a portable, human-readable representation of the current SHA state.
**putstate($str)**
Returns a Digest::SHA object representing the SHA state contained in *$str*. The format of *$str* matches the format of the output produced by method *getstate*. If called as a class method, a new object is created; if called as an instance method, the object is reset to the state contained in *$str*.
**dump($filename)**
Writes the output of *getstate* to *$filename*. If the argument is missing, or equal to the empty string, the state information will be written to STDOUT.
**load($filename)**
Returns a Digest::SHA object that results from calling *putstate* on the contents of *$filename*. If the argument is missing, or equal to the empty string, the state information will be read from STDIN.
**digest** Returns the digest encoded as a binary string.
Note that the *digest* method is a read-once operation. Once it has been performed, the Digest::SHA object is automatically reset in preparation for calculating another digest value. Call *$sha->clone->digest* if it's necessary to preserve the original digest state.
**hexdigest** Returns the digest encoded as a hexadecimal string.
Like *digest*, this method is a read-once operation. Call *$sha->clone->hexdigest* if it's necessary to preserve the original digest state.
**b64digest** Returns the digest encoded as a Base64 string.
Like *digest*, this method is a read-once operation. Call *$sha->clone->b64digest* if it's necessary to preserve the original digest state.
It's important to note that the resulting string does **not** contain the padding characters typical of Base64 encodings. This omission is deliberate, and is done to maintain compatibility with the family of CPAN Digest modules. See ["PADDING OF BASE64 DIGESTS"](#PADDING-OF-BASE64-DIGESTS) for details.
*HMAC-SHA-1/224/256/384/512*
**hmac\_sha1($data, $key)**
**hmac\_sha224($data, $key)**
**hmac\_sha256($data, $key)**
**hmac\_sha384($data, $key)**
**hmac\_sha512($data, $key)**
**hmac\_sha512224($data, $key)**
**hmac\_sha512256($data, $key)**
Returns the HMAC-SHA-1/224/256/384/512 digest of *$data*/*$key*, with the result encoded as a binary string. Multiple *$data* arguments are allowed, provided that *$key* is the last argument in the list.
**hmac\_sha1\_hex($data, $key)**
**hmac\_sha224\_hex($data, $key)**
**hmac\_sha256\_hex($data, $key)**
**hmac\_sha384\_hex($data, $key)**
**hmac\_sha512\_hex($data, $key)**
**hmac\_sha512224\_hex($data, $key)**
**hmac\_sha512256\_hex($data, $key)**
Returns the HMAC-SHA-1/224/256/384/512 digest of *$data*/*$key*, with the result encoded as a hexadecimal string. Multiple *$data* arguments are allowed, provided that *$key* is the last argument in the list.
**hmac\_sha1\_base64($data, $key)**
**hmac\_sha224\_base64($data, $key)**
**hmac\_sha256\_base64($data, $key)**
**hmac\_sha384\_base64($data, $key)**
**hmac\_sha512\_base64($data, $key)**
**hmac\_sha512224\_base64($data, $key)**
**hmac\_sha512256\_base64($data, $key)**
Returns the HMAC-SHA-1/224/256/384/512 digest of *$data*/*$key*, with the result encoded as a Base64 string. Multiple *$data* arguments are allowed, provided that *$key* is the last argument in the list.
It's important to note that the resulting string does **not** contain the padding characters typical of Base64 encodings. This omission is deliberate, and is done to maintain compatibility with the family of CPAN Digest modules. See ["PADDING OF BASE64 DIGESTS"](#PADDING-OF-BASE64-DIGESTS) for details.
SEE ALSO
---------
[Digest](digest), <Digest::SHA::PurePerl>
The Secure Hash Standard (Draft FIPS PUB 180-4) can be found at:
<http://csrc.nist.gov/publications/drafts/fips180-4/Draft-FIPS180-4_Feb2011.pdf>
The Keyed-Hash Message Authentication Code (HMAC):
<http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf>
AUTHOR
------
```
Mark Shelor <[email protected]>
```
ACKNOWLEDGMENTS
---------------
The author is particularly grateful to
```
Gisle Aas
H. Merijn Brand
Sean Burke
Chris Carey
Alexandr Ciornii
Chris David
Jim Doble
Thomas Drugeon
Julius Duque
Jeffrey Friedl
Robert Gilmour
Brian Gladman
Jarkko Hietaniemi
Adam Kennedy
Mark Lawrence
Andy Lester
Alex Muntada
Steve Peters
Chris Skiscim
Martin Thurn
Gunnar Wolf
Adam Woodbury
```
"who by trained skill rescued life from such great billows and such thick darkness and moored it in so perfect a calm and in so brilliant a light" - Lucretius
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2003-2018 Mark Shelor
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
[perlartistic](https://perldoc.perl.org/5.36.0/perlartistic)
| programming_docs |
perl Pod::Simple::XHTML Pod::Simple::XHTML
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Minimal code](#Minimal-code)
* [METHODS](#METHODS)
+ [perldoc\_url\_prefix](#perldoc_url_prefix)
+ [perldoc\_url\_postfix](#perldoc_url_postfix)
+ [man\_url\_prefix](#man_url_prefix)
+ [man\_url\_postfix](#man_url_postfix)
+ [title\_prefix, title\_postfix](#title_prefix,-title_postfix)
+ [html\_css](#html_css)
+ [html\_javascript](#html_javascript)
+ [html\_doctype](#html_doctype)
+ [html\_charset](#html_charset)
+ [html\_header\_tags](#html_header_tags)
- [html\_encode\_chars](#html_encode_chars)
+ [html\_h\_level](#html_h_level)
+ [default\_title](#default_title)
+ [force\_title](#force_title)
+ [html\_header, html\_footer](#html_header,-html_footer)
+ [index](#index)
+ [anchor\_items](#anchor_items)
+ [backlink](#backlink)
* [SUBCLASSING](#SUBCLASSING)
+ [handle\_text](#handle_text)
+ [handle\_code](#handle_code)
+ [accept\_targets\_as\_html](#accept_targets_as_html)
+ [resolve\_pod\_page\_link](#resolve_pod_page_link)
+ [resolve\_man\_page\_link](#resolve_man_page_link)
+ [idify](#idify)
+ [batch\_mode\_page\_object\_init](#batch_mode_page_object_init)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [ACKNOWLEDGEMENTS](#ACKNOWLEDGEMENTS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::XHTML -- format Pod as validating XHTML
SYNOPSIS
--------
```
use Pod::Simple::XHTML;
my $parser = Pod::Simple::XHTML->new();
...
$parser->parse_file('path/to/file.pod');
```
DESCRIPTION
-----------
This class is a formatter that takes Pod and renders it as XHTML validating HTML.
This is a subclass of <Pod::Simple::Methody> and inherits all its methods. The implementation is entirely different than <Pod::Simple::HTML>, but it largely preserves the same interface.
###
Minimal code
```
use Pod::Simple::XHTML;
my $psx = Pod::Simple::XHTML->new;
$psx->output_string(\my $html);
$psx->parse_file('path/to/Module/Name.pm');
open my $out, '>', 'out.html' or die "Cannot open 'out.html': $!\n";
print $out $html;
```
You can also control the character encoding and entities. For example, if you're sure that the POD is properly encoded (using the `=encoding` command), you can prevent high-bit characters from being encoded as HTML entities and declare the output character set as UTF-8 before parsing, like so:
```
$psx->html_charset('UTF-8');
$psx->html_encode_chars(q{&<>'"});
```
METHODS
-------
Pod::Simple::XHTML offers a number of methods that modify the format of the HTML output. Call these after creating the parser object, but before the call to `parse_file`:
```
my $parser = Pod::PseudoPod::HTML->new();
$parser->set_optional_param("value");
$parser->parse_file($file);
```
### perldoc\_url\_prefix
In turning <Foo::Bar> into http://whatever/Foo%3a%3aBar, what to put before the "Foo%3a%3aBar". The default value is "https://metacpan.org/pod/".
### perldoc\_url\_postfix
What to put after "Foo%3a%3aBar" in the URL. This option is not set by default.
### man\_url\_prefix
In turning `[crontab(5)](http://man.he.net/man5/crontab)` into http://whatever/man/1/crontab, what to put before the "1/crontab". The default value is "http://man.he.net/man".
### man\_url\_postfix
What to put after "1/crontab" in the URL. This option is not set by default.
###
title\_prefix, title\_postfix
What to put before and after the title in the head. The values should already be &-escaped.
### html\_css
```
$parser->html_css('path/to/style.css');
```
The URL or relative path of a CSS file to include. This option is not set by default.
### html\_javascript
The URL or relative path of a JavaScript file to pull in. This option is not set by default.
### html\_doctype
A document type tag for the file. This option is not set by default.
### html\_charset
The character set to declare in the Content-Type meta tag created by default for `html_header_tags`. Note that this option will be ignored if the value of `html_header_tags` is changed. Defaults to "ISO-8859-1".
### html\_header\_tags
Additional arbitrary HTML tags for the header of the document. The default value is just a content type header tag:
```
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
```
Add additional meta tags here, or blocks of inline CSS or JavaScript (wrapped in the appropriate tags).
#### html\_encode\_chars
A string containing all characters that should be encoded as HTML entities, specified using the regular expression character class syntax (what you find within brackets in regular expressions). This value will be passed as the second argument to the `encode_entities` function of <HTML::Entities>. If <HTML::Entities> is not installed, then any characters other than `&<`"'> will be encoded numerically.
### html\_h\_level
This is the level of HTML "Hn" element to which a Pod "head1" corresponds. For example, if `html_h_level` is set to 2, a head1 will produce an H2, a head2 will produce an H3, and so on.
### default\_title
Set a default title for the page if no title can be determined from the content. The value of this string should already be &-escaped.
### force\_title
Force a title for the page (don't try to determine it from the content). The value of this string should already be &-escaped.
###
html\_header, html\_footer
Set the HTML output at the beginning and end of each file. The default header includes a title, a doctype tag (if `html_doctype` is set), a content tag (customized by `html_header_tags`), a tag for a CSS file (if `html_css` is set), and a tag for a Javascript file (if `html_javascript` is set). The default footer simply closes the `html` and `body` tags.
The options listed above customize parts of the default header, but setting `html_header` or `html_footer` completely overrides the built-in header or footer. These may be useful if you want to use template tags instead of literal HTML headers and footers or are integrating converted POD pages in a larger website.
If you want no headers or footers output in the HTML, set these options to the empty string.
### index
Whether to add a table-of-contents at the top of each page (called an index for the sake of tradition).
### anchor\_items
Whether to anchor every definition `=item` directive. This needs to be enabled if you want to be able to link to specific `=item` directives, which are output as `<dt>` elements. Disabled by default.
### backlink
Whether to turn every =head1 directive into a link pointing to the top of the page (specifically, the opening body tag).
SUBCLASSING
-----------
If the standard options aren't enough, you may want to subclass Pod::Simple::XHMTL. These are the most likely candidates for methods you'll want to override when subclassing.
### handle\_text
This method handles the body of text within any element: it's the body of a paragraph, or everything between a "=begin" tag and the corresponding "=end" tag, or the text within an L entity, etc. You would want to override this if you are adding a custom element type that does more than just display formatted text. Perhaps adding a way to generate HTML tables from an extended version of POD.
So, let's say you want to add a custom element called 'foo'. In your subclass's `new` method, after calling `SUPER::new` you'd call:
```
$new->accept_targets_as_text( 'foo' );
```
Then override the `start_for` method in the subclass to check for when "$flags->{'target'}" is equal to 'foo' and set a flag that marks that you're in a foo block (maybe "$self->{'in\_foo'} = 1"). Then override the `handle_text` method to check for the flag, and pass $text to your custom subroutine to construct the HTML output for 'foo' elements, something like:
```
sub handle_text {
my ($self, $text) = @_;
if ($self->{'in_foo'}) {
$self->{'scratch'} .= build_foo_html($text);
return;
}
$self->SUPER::handle_text($text);
}
```
### handle\_code
This method handles the body of text that is marked up to be code. You might for instance override this to plug in a syntax highlighter. The base implementation just escapes the text.
The callback methods `start_code` and `end_code` emits the `code` tags before and after `handle_code` is invoked, so you might want to override these together with `handle_code` if this wrapping isn't suitable.
Note that the code might be broken into multiple segments if there are nested formatting codes inside a `C<...>` sequence. In between the calls to `handle_code` other markup tags might have been emitted in that case. The same is true for verbatim sections if the `codes_in_verbatim` option is turned on.
### accept\_targets\_as\_html
This method behaves like `accept_targets_as_text`, but also marks the region as one whose content should be emitted literally, without HTML entity escaping or wrapping in a `div` element.
### resolve\_pod\_page\_link
```
my $url = $pod->resolve_pod_page_link('Net::Ping', 'INSTALL');
my $url = $pod->resolve_pod_page_link('perlpodspec');
my $url = $pod->resolve_pod_page_link(undef, 'SYNOPSIS');
```
Resolves a POD link target (typically a module or POD file name) and section name to a URL. The resulting link will be returned for the above examples as:
```
https://metacpan.org/pod/Net::Ping#INSTALL
https://metacpan.org/pod/perlpodspec
#SYNOPSIS
```
Note that when there is only a section argument the URL will simply be a link to a section in the current document.
### resolve\_man\_page\_link
```
my $url = $pod->resolve_man_page_link('crontab(5)', 'EXAMPLE CRON FILE');
my $url = $pod->resolve_man_page_link('crontab');
```
Resolves a man page link target and numeric section to a URL. The resulting link will be returned for the above examples as:
```
http://man.he.net/man5/crontab
http://man.he.net/man1/crontab
```
Note that the first argument is required. The section number will be parsed from it, and if it's missing will default to 1. The second argument is currently ignored, as [man.he.net](http://man.he.net) does not currently include linkable IDs or anchor names in its pages. Subclass to link to a different man page HTTP server.
### idify
```
my $id = $pod->idify($text);
my $hash = $pod->idify($text, 1);
```
This method turns an arbitrary string into a valid XHTML ID attribute value. The rules enforced, following <http://webdesign.about.com/od/htmltags/a/aa031707.htm>, are:
* The id must start with a letter (a-z or A-Z)
* All subsequent characters can be letters, numbers (0-9), hyphens (-), underscores (\_), colons (:), and periods (.).
* The final character can't be a hyphen, colon, or period. URLs ending with these characters, while allowed by XHTML, can be awkward to extract from plain text.
* Each id must be unique within the document.
In addition, the returned value will be unique within the context of the Pod::Simple::XHTML object unless a second argument is passed a true value. ID attributes should always be unique within a single XHTML document, but pass the true value if you are creating not an ID but a URL hash to point to an ID (i.e., if you need to put the "#foo" in `<a href="#foo">foo</a>`.
### batch\_mode\_page\_object\_init
```
$pod->batch_mode_page_object_init($batchconvobj, $module, $infile, $outfile, $depth);
```
Called by <Pod::Simple::HTMLBatch> so that the class has a chance to initialize the converter. Internally it sets the `batch_mode` property to true and sets `batch_mode_current_level()`, but Pod::Simple::XHTML does not currently use those features. Subclasses might, though.
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::Text>, <Pod::Spell>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2003-2005 Allison Randal.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
ACKNOWLEDGEMENTS
----------------
Thanks to [Hurricane Electric](http://he.net/) for permission to use its [Linux man pages online](http://man.he.net/) site for man page links.
Thanks to [search.cpan.org](http://search.cpan.org/) for permission to use the site for Perl module links.
AUTHOR
------
Pod::Simpele::XHTML was created by Allison Randal <[email protected]>.
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl Memoize Memoize
=======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [DETAILS](#DETAILS)
* [OPTIONS](#OPTIONS)
+ [INSTALL](#INSTALL)
+ [NORMALIZER](#NORMALIZER)
+ [SCALAR\_CACHE, LIST\_CACHE](#SCALAR_CACHE,-LIST_CACHE)
- [List values in scalar context](#List-values-in-scalar-context)
- [Merged disk caches](#Merged-disk-caches)
* [OTHER FACILITIES](#OTHER-FACILITIES)
+ [unmemoize](#unmemoize)
+ [flush\_cache](#flush_cache)
* [CAVEATS](#CAVEATS)
* [PERSISTENT CACHE SUPPORT](#PERSISTENT-CACHE-SUPPORT)
* [EXPIRATION SUPPORT](#EXPIRATION-SUPPORT)
* [BUGS](#BUGS)
* [MAILING LIST](#MAILING-LIST)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [THANK YOU](#THANK-YOU)
NAME
----
Memoize - Make functions faster by trading space for time
SYNOPSIS
--------
```
# This is the documentation for Memoize 1.03
use Memoize;
memoize('slow_function');
slow_function(arguments); # Is faster than it was before
```
This is normally all you need to know. However, many options are available:
```
memoize(function, options...);
```
Options include:
```
NORMALIZER => function
INSTALL => new_name
SCALAR_CACHE => 'MEMORY'
SCALAR_CACHE => ['HASH', \%cache_hash ]
SCALAR_CACHE => 'FAULT'
SCALAR_CACHE => 'MERGE'
LIST_CACHE => 'MEMORY'
LIST_CACHE => ['HASH', \%cache_hash ]
LIST_CACHE => 'FAULT'
LIST_CACHE => 'MERGE'
```
DESCRIPTION
-----------
`Memoizing' a function makes it faster by trading space for time. It does this by caching the return values of the function in a table. If you call the function again with the same arguments, `memoize` jumps in and gives you the value out of the table, instead of letting the function compute the value all over again.
Here is an extreme example. Consider the Fibonacci sequence, defined by the following function:
```
# Compute Fibonacci numbers
sub fib {
my $n = shift;
return $n if $n < 2;
fib($n-1) + fib($n-2);
}
```
This function is very slow. Why? To compute fib(14), it first wants to compute fib(13) and fib(12), and add the results. But to compute fib(13), it first has to compute fib(12) and fib(11), and then it comes back and computes fib(12) all over again even though the answer is the same. And both of the times that it wants to compute fib(12), it has to compute fib(11) from scratch, and then it has to do it again each time it wants to compute fib(13). This function does so much recomputing of old results that it takes a really long time to run---fib(14) makes 1,200 extra recursive calls to itself, to compute and recompute things that it already computed.
This function is a good candidate for memoization. If you memoize the `fib' function above, it will compute fib(14) exactly once, the first time it needs to, and then save the result in a table. Then if you ask for fib(14) again, it gives you the result out of the table. While computing fib(14), instead of computing fib(12) twice, it does it once; the second time it needs the value it gets it from the table. It doesn't compute fib(11) four times; it computes it once, getting it from the table the next three times. Instead of making 1,200 recursive calls to `fib', it makes 15. This makes the function about 150 times faster.
You could do the memoization yourself, by rewriting the function, like this:
```
# Compute Fibonacci numbers, memoized version
{ my @fib;
sub fib {
my $n = shift;
return $fib[$n] if defined $fib[$n];
return $fib[$n] = $n if $n < 2;
$fib[$n] = fib($n-1) + fib($n-2);
}
}
```
Or you could use this module, like this:
```
use Memoize;
memoize('fib');
# Rest of the fib function just like the original version.
```
This makes it easy to turn memoizing on and off.
Here's an even simpler example: I wrote a simple ray tracer; the program would look in a certain direction, figure out what it was looking at, and then convert the `color' value (typically a string like `red') of that object to a red, green, and blue pixel value, like this:
```
for ($direction = 0; $direction < 300; $direction++) {
# Figure out which object is in direction $direction
$color = $object->{color};
($r, $g, $b) = @{&ColorToRGB($color)};
...
}
```
Since there are relatively few objects in a picture, there are only a few colors, which get looked up over and over again. Memoizing `ColorToRGB` sped up the program by several percent.
DETAILS
-------
This module exports exactly one function, `memoize`. The rest of the functions in this package are None of Your Business.
You should say
```
memoize(function)
```
where `function` is the name of the function you want to memoize, or a reference to it. `memoize` returns a reference to the new, memoized version of the function, or `undef` on a non-fatal error. At present, there are no non-fatal errors, but there might be some in the future.
If `function` was the name of a function, then `memoize` hides the old version and installs the new memoized version under the old name, so that `&function(...)` actually invokes the memoized version.
OPTIONS
-------
There are some optional options you can pass to `memoize` to change the way it behaves a little. To supply options, invoke `memoize` like this:
```
memoize(function, NORMALIZER => function,
INSTALL => newname,
SCALAR_CACHE => option,
LIST_CACHE => option
);
```
Each of these options is optional; you can include some, all, or none of them.
### INSTALL
If you supply a function name with `INSTALL`, memoize will install the new, memoized version of the function under the name you give. For example,
```
memoize('fib', INSTALL => 'fastfib')
```
installs the memoized version of `fib` as `fastfib`; without the `INSTALL` option it would have replaced the old `fib` with the memoized version.
To prevent `memoize` from installing the memoized version anywhere, use `INSTALL => undef`.
### NORMALIZER
Suppose your function looks like this:
```
# Typical call: f('aha!', A => 11, B => 12);
sub f {
my $a = shift;
my %hash = @_;
$hash{B} ||= 2; # B defaults to 2
$hash{C} ||= 7; # C defaults to 7
# Do something with $a, %hash
}
```
Now, the following calls to your function are all completely equivalent:
```
f(OUCH);
f(OUCH, B => 2);
f(OUCH, C => 7);
f(OUCH, B => 2, C => 7);
f(OUCH, C => 7, B => 2);
(etc.)
```
However, unless you tell `Memoize` that these calls are equivalent, it will not know that, and it will compute the values for these invocations of your function separately, and store them separately.
To prevent this, supply a `NORMALIZER` function that turns the program arguments into a string in a way that equivalent arguments turn into the same string. A `NORMALIZER` function for `f` above might look like this:
```
sub normalize_f {
my $a = shift;
my %hash = @_;
$hash{B} ||= 2;
$hash{C} ||= 7;
join(',', $a, map ($_ => $hash{$_}) sort keys %hash);
}
```
Each of the argument lists above comes out of the `normalize_f` function looking exactly the same, like this:
```
OUCH,B,2,C,7
```
You would tell `Memoize` to use this normalizer this way:
```
memoize('f', NORMALIZER => 'normalize_f');
```
`memoize` knows that if the normalized version of the arguments is the same for two argument lists, then it can safely look up the value that it computed for one argument list and return it as the result of calling the function with the other argument list, even if the argument lists look different.
The default normalizer just concatenates the arguments with character 28 in between. (In ASCII, this is called FS or control-\.) This always works correctly for functions with only one string argument, and also when the arguments never contain character 28. However, it can confuse certain argument lists:
```
normalizer("a\034", "b")
normalizer("a", "\034b")
normalizer("a\034\034b")
```
for example.
Since hash keys are strings, the default normalizer will not distinguish between `undef` and the empty string. It also won't work when the function's arguments are references. For example, consider a function `g` which gets two arguments: A number, and a reference to an array of numbers:
```
g(13, [1,2,3,4,5,6,7]);
```
The default normalizer will turn this into something like `"13\034ARRAY(0x436c1f)"`. That would be all right, except that a subsequent array of numbers might be stored at a different location even though it contains the same data. If this happens, `Memoize` will think that the arguments are different, even though they are equivalent. In this case, a normalizer like this is appropriate:
```
sub normalize { join ' ', $_[0], @{$_[1]} }
```
For the example above, this produces the key "13 1 2 3 4 5 6 7".
Another use for normalizers is when the function depends on data other than those in its arguments. Suppose you have a function which returns a value which depends on the current hour of the day:
```
sub on_duty {
my ($problem_type) = @_;
my $hour = (localtime)[2];
open my $fh, "$DIR/$problem_type" or die...;
my $line;
while ($hour-- > 0)
$line = <$fh>;
}
return $line;
}
```
At 10:23, this function generates the 10th line of a data file; at 3:45 PM it generates the 15th line instead. By default, `Memoize` will only see the $problem\_type argument. To fix this, include the current hour in the normalizer:
```
sub normalize { join ' ', (localtime)[2], @_ }
```
The calling context of the function (scalar or list context) is propagated to the normalizer. This means that if the memoized function will treat its arguments differently in list context than it would in scalar context, you can have the normalizer function select its behavior based on the results of `wantarray`. Even if called in a list context, a normalizer should still return a single string.
###
`SCALAR_CACHE`, `LIST_CACHE`
Normally, `Memoize` caches your function's return values into an ordinary Perl hash variable. However, you might like to have the values cached on the disk, so that they persist from one run of your program to the next, or you might like to associate some other interesting semantics with the cached values.
There's a slight complication under the hood of `Memoize`: There are actually *two* caches, one for scalar values and one for list values. When your function is called in scalar context, its return value is cached in one hash, and when your function is called in list context, its value is cached in the other hash. You can control the caching behavior of both contexts independently with these options.
The argument to `LIST_CACHE` or `SCALAR_CACHE` must either be one of the following four strings:
```
MEMORY
FAULT
MERGE
HASH
```
or else it must be a reference to an array whose first element is one of these four strings, such as `[HASH, arguments...]`.
`MEMORY` `MEMORY` means that return values from the function will be cached in an ordinary Perl hash variable. The hash variable will not persist after the program exits. This is the default.
`HASH` `HASH` allows you to specify that a particular hash that you supply will be used as the cache. You can tie this hash beforehand to give it any behavior you want.
A tied hash can have any semantics at all. It is typically tied to an on-disk database, so that cached values are stored in the database and retrieved from it again when needed, and the disk file typically persists after your program has exited. See `perltie` for more complete details about `tie`.
A typical example is:
```
use DB_File;
tie my %cache => 'DB_File', $filename, O_RDWR|O_CREAT, 0666;
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
```
This has the effect of storing the cache in a `DB_File` database whose name is in `$filename`. The cache will persist after the program has exited. Next time the program runs, it will find the cache already populated from the previous run of the program. Or you can forcibly populate the cache by constructing a batch program that runs in the background and populates the cache file. Then when you come to run your real program the memoized function will be fast because all its results have been precomputed.
Another reason to use `HASH` is to provide your own hash variable. You can then inspect or modify the contents of the hash to gain finer control over the cache management.
`TIE` This option is no longer supported. It is still documented only to aid in the debugging of old programs that use it. Old programs should be converted to use the `HASH` option instead.
```
memoize ... ['TIE', PACKAGE, ARGS...]
```
is merely a shortcut for
```
require PACKAGE;
{ tie my %cache, PACKAGE, ARGS...;
memoize ... [HASH => \%cache];
}
```
`FAULT` `FAULT` means that you never expect to call the function in scalar (or list) context, and that if `Memoize` detects such a call, it should abort the program. The error message is one of
```
`foo' function called in forbidden list context at line ...
`foo' function called in forbidden scalar context at line ...
```
`MERGE` `MERGE` normally means that the memoized function does not distinguish between list and sclar context, and that return values in both contexts should be stored together. Both `LIST_CACHE => MERGE` and `SCALAR_CACHE => MERGE` mean the same thing.
Consider this function:
```
sub complicated {
# ... time-consuming calculation of $result
return $result;
}
```
The `complicated` function will return the same numeric `$result` regardless of whether it is called in list or in scalar context.
Normally, the following code will result in two calls to `complicated`, even if `complicated` is memoized:
```
$x = complicated(142);
($y) = complicated(142);
$z = complicated(142);
```
The first call will cache the result, say 37, in the scalar cache; the second will cach the list `(37)` in the list cache. The third call doesn't call the real `complicated` function; it gets the value 37 from the scalar cache.
Obviously, the second call to `complicated` is a waste of time, and storing its return value is a waste of space. Specifying `LIST_CACHE => MERGE` will make `memoize` use the same cache for scalar and list context return values, so that the second call uses the scalar cache that was populated by the first call. `complicated` ends up being called only once, and both subsequent calls return `3` from the cache, regardless of the calling context.
####
List values in scalar context
Consider this function:
```
sub iota { return reverse (1..$_[0]) }
```
This function normally returns a list. Suppose you memoize it and merge the caches:
```
memoize 'iota', SCALAR_CACHE => 'MERGE';
@i7 = iota(7);
$i7 = iota(7);
```
Here the first call caches the list (1,2,3,4,5,6,7). The second call does not really make sense. `Memoize` cannot guess what behavior `iota` should have in scalar context without actually calling it in scalar context. Normally `Memoize` *would* call `iota` in scalar context and cache the result, but the `SCALAR_CACHE => 'MERGE'` option says not to do that, but to use the cache list-context value instead. But it cannot return a list of seven elements in a scalar context. In this case `$i7` will receive the **first element** of the cached list value, namely 7.
####
Merged disk caches
Another use for `MERGE` is when you want both kinds of return values stored in the same disk file; this saves you from having to deal with two disk files instead of one. You can use a normalizer function to keep the two sets of return values separate. For example:
```
tie my %cache => 'MLDBM', 'DB_File', $filename, ...;
memoize 'myfunc',
NORMALIZER => 'n',
SCALAR_CACHE => [HASH => \%cache],
LIST_CACHE => 'MERGE',
;
sub n {
my $context = wantarray() ? 'L' : 'S';
# ... now compute the hash key from the arguments ...
$hashkey = "$context:$hashkey";
}
```
This normalizer function will store scalar context return values in the disk file under keys that begin with `S:`, and list context return values under keys that begin with `L:`.
OTHER FACILITIES
-----------------
### `unmemoize`
There's an `unmemoize` function that you can import if you want to. Why would you want to? Here's an example: Suppose you have your cache tied to a DBM file, and you want to make sure that the cache is written out to disk if someone interrupts the program. If the program exits normally, this will happen anyway, but if someone types control-C or something then the program will terminate immediately without synchronizing the database. So what you can do instead is
```
$SIG{INT} = sub { unmemoize 'function' };
```
`unmemoize` accepts a reference to, or the name of a previously memoized function, and undoes whatever it did to provide the memoized version in the first place, including making the name refer to the unmemoized version if appropriate. It returns a reference to the unmemoized version of the function.
If you ask it to unmemoize a function that was never memoized, it croaks.
### `flush_cache`
`flush_cache(function)` will flush out the caches, discarding *all* the cached data. The argument may be a function name or a reference to a function. For finer control over when data is discarded or expired, see the documentation for `Memoize::Expire`, included in this package.
Note that if the cache is a tied hash, `flush_cache` will attempt to invoke the `CLEAR` method on the hash. If there is no `CLEAR` method, this will cause a run-time error.
An alternative approach to cache flushing is to use the `HASH` option (see above) to request that `Memoize` use a particular hash variable as its cache. Then you can examine or modify the hash at any time in any way you desire. You may flush the cache by using `%hash = ()`.
CAVEATS
-------
Memoization is not a cure-all:
* Do not memoize a function whose behavior depends on program state other than its own arguments, such as global variables, the time of day, or file input. These functions will not produce correct results when memoized. For a particularly easy example:
```
sub f {
time;
}
```
This function takes no arguments, and as far as `Memoize` is concerned, it always returns the same result. `Memoize` is wrong, of course, and the memoized version of this function will call `time` once to get the current time, and it will return that same time every time you call it after that.
* Do not memoize a function with side effects.
```
sub f {
my ($a, $b) = @_;
my $s = $a + $b;
print "$a + $b = $s.\n";
}
```
This function accepts two arguments, adds them, and prints their sum. Its return value is the numuber of characters it printed, but you probably didn't care about that. But `Memoize` doesn't understand that. If you memoize this function, you will get the result you expect the first time you ask it to print the sum of 2 and 3, but subsequent calls will return 1 (the return value of `print`) without actually printing anything.
* Do not memoize a function that returns a data structure that is modified by its caller.
Consider these functions: `getusers` returns a list of users somehow, and then `main` throws away the first user on the list and prints the rest:
```
sub main {
my $userlist = getusers();
shift @$userlist;
foreach $u (@$userlist) {
print "User $u\n";
}
}
sub getusers {
my @users;
# Do something to get a list of users;
\@users; # Return reference to list.
}
```
If you memoize `getusers` here, it will work right exactly once. The reference to the users list will be stored in the memo table. `main` will discard the first element from the referenced list. The next time you invoke `main`, `Memoize` will not call `getusers`; it will just return the same reference to the same list it got last time. But this time the list has already had its head removed; `main` will erroneously remove another element from it. The list will get shorter and shorter every time you call `main`.
Similarly, this:
```
$u1 = getusers();
$u2 = getusers();
pop @$u1;
```
will modify $u2 as well as $u1, because both variables are references to the same array. Had `getusers` not been memoized, $u1 and $u2 would have referred to different arrays.
* Do not memoize a very simple function.
Recently someone mentioned to me that the Memoize module made his program run slower instead of faster. It turned out that he was memoizing the following function:
```
sub square {
$_[0] * $_[0];
}
```
I pointed out that `Memoize` uses a hash, and that looking up a number in the hash is necessarily going to take a lot longer than a single multiplication. There really is no way to speed up the `square` function.
Memoization is not magical.
PERSISTENT CACHE SUPPORT
-------------------------
You can tie the cache tables to any sort of tied hash that you want to, as long as it supports `TIEHASH`, `FETCH`, `STORE`, and `EXISTS`. For example,
```
tie my %cache => 'GDBM_File', $filename, O_RDWR|O_CREAT, 0666;
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
```
works just fine. For some storage methods, you need a little glue.
`SDBM_File` doesn't supply an `EXISTS` method, so included in this package is a glue module called `Memoize::SDBM_File` which does provide one. Use this instead of plain `SDBM_File` to store your cache table on disk in an `SDBM_File` database:
```
tie my %cache => 'Memoize::SDBM_File', $filename, O_RDWR|O_CREAT, 0666;
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
```
`NDBM_File` has the same problem and the same solution. (Use `Memoize::NDBM_File instead of plain NDBM_File.`)
`Storable` isn't a tied hash class at all. You can use it to store a hash to disk and retrieve it again, but you can't modify the hash while it's on the disk. So if you want to store your cache table in a `Storable` database, use `Memoize::Storable`, which puts a hashlike front-end onto `Storable`. The hash table is actually kept in memory, and is loaded from your `Storable` file at the time you memoize the function, and stored back at the time you unmemoize the function (or when your program exits):
```
tie my %cache => 'Memoize::Storable', $filename;
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
tie my %cache => 'Memoize::Storable', $filename, 'nstore';
memoize 'function', SCALAR_CACHE => [HASH => \%cache];
```
Include the `nstore' option to have the `Storable` database written in `network order'. (See [Storable](storable) for more details about this.)
The `flush_cache()` function will raise a run-time error unless the tied package provides a `CLEAR` method.
EXPIRATION SUPPORT
-------------------
See Memoize::Expire, which is a plug-in module that adds expiration functionality to Memoize. If you don't like the kinds of policies that Memoize::Expire implements, it is easy to write your own plug-in module to implement whatever policy you desire. Memoize comes with several examples. An expiration manager that implements a LRU policy is available on CPAN as Memoize::ExpireLRU.
BUGS
----
The test suite is much better, but always needs improvement.
There is some problem with the way `goto &f` works under threaded Perl, perhaps because of the lexical scoping of `@_`. This is a bug in Perl, and until it is resolved, memoized functions will see a slightly different `caller()` and will perform a little more slowly on threaded perls than unthreaded perls.
Some versions of `DB_File` won't let you store data under a key of length 0. That means that if you have a function `f` which you memoized and the cache is in a `DB_File` database, then the value of `f()` (`f` called with no arguments) will not be memoized. If this is a big problem, you can supply a normalizer function that prepends `"x"` to every key.
MAILING LIST
-------------
To join a very low-traffic mailing list for announcements about `Memoize`, send an empty note to `[email protected]`.
AUTHOR
------
Mark-Jason Dominus (`[email protected]`), Plover Systems co.
See the `Memoize.pm` Page at http://perl.plover.com/Memoize/ for news and upgrades. Near this page, at http://perl.plover.com/MiniMemoize/ there is an article about memoization and about the internals of Memoize that appeared in The Perl Journal, issue #13. (This article is also included in the Memoize distribution as `article.html'.)
The author's book *Higher-Order Perl* (2005, ISBN 1558607013, published by Morgan Kaufmann) discusses memoization (and many other topics) in tremendous detail. It is available on-line for free. For more information, visit http://hop.perl.plover.com/ .
To join a mailing list for announcements about `Memoize`, send an empty message to `[email protected]`. This mailing list is for announcements only and has extremely low traffic---fewer than two messages per year.
COPYRIGHT AND LICENSE
----------------------
Copyright 1998, 1999, 2000, 2001, 2012 by Mark Jason Dominus
This library is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
THANK YOU
----------
Many thanks to Florian Ragwitz for administration and packaging assistance, to John Tromp for bug reports, to Jonathan Roy for bug reports and suggestions, to Michael Schwern for other bug reports and patches, to Mike Cariaso for helping me to figure out the Right Thing to Do About Expiration, to Joshua Gerth, Joshua Chamas, Jonathan Roy (again), Mark D. Anderson, and Andrew Johnson for more suggestions about expiration, to Brent Powers for the Memoize::ExpireLRU module, to Ariel Scolnicov for delightful messages about the Fibonacci function, to Dion Almaer for thought-provoking suggestions about the default normalizer, to Walt Mankowski and Kurt Starsinic for much help investigating problems under threaded Perl, to Alex Dudkevich for reporting the bug in prototyped functions and for checking my patch, to Tony Bass for many helpful suggestions, to Jonathan Roy (again) for finding a use for `unmemoize()`, to Philippe Verdret for enlightening discussion of `Hook::PrePostCall`, to Nat Torkington for advice I ignored, to Chris Nandor for portability advice, to Randal Schwartz for suggesting the '`flush_cache` function, and to Jenda Krynicky for being a light in the world.
Special thanks to Jarkko Hietaniemi, the 5.8.0 pumpking, for including this module in the core and for his patient and helpful guidance during the integration process.
2 POD Errors
The following errors were encountered while parsing the POD:
Around line 755:
You forgot a '=back' before '=head3'
Around line 804:
=back without =over
| programming_docs |
perl Module::Metadata Module::Metadata
================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [CLASS METHODS](#CLASS-METHODS)
+ [new\_from\_file($filename, collect\_pod => 1, decode\_pod => 1)](#new_from_file(%24filename,-collect_pod-=%3E-1,-decode_pod-=%3E-1))
+ [new\_from\_handle($handle, $filename, collect\_pod => 1, decode\_pod => 1)](#new_from_handle(%24handle,-%24filename,-collect_pod-=%3E-1,-decode_pod-=%3E-1))
+ [new\_from\_module($module, collect\_pod => 1, inc => \@dirs, decode\_pod => 1)](#new_from_module(%24module,-collect_pod-=%3E-1,-inc-=%3E-%5C@dirs,-decode_pod-=%3E-1))
+ [find\_module\_by\_name($module, \@dirs)](#find_module_by_name(%24module,-%5C@dirs))
+ [find\_module\_dir\_by\_name($module, \@dirs)](#find_module_dir_by_name(%24module,-%5C@dirs))
+ [provides( %options )](#provides(-%25options-))
+ [package\_versions\_from\_directory($dir, \@files?)](#package_versions_from_directory(%24dir,-%5C@files?))
+ [log\_info (internal)](#log_info-(internal))
* [OBJECT METHODS](#OBJECT-METHODS)
+ [name()](#name())
+ [version($package)](#version(%24package))
+ [filename()](#filename())
+ [packages\_inside()](#packages_inside())
+ [pod\_inside()](#pod_inside())
+ [contains\_pod()](#contains_pod())
+ [pod($section)](#pod(%24section))
+ [is\_indexable($package) or is\_indexable()](#is_indexable(%24package)-or-is_indexable())
* [SUPPORT](#SUPPORT)
* [AUTHOR](#AUTHOR)
* [CONTRIBUTORS](#CONTRIBUTORS)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
Module::Metadata - Gather package and POD information from perl module files
VERSION
-------
version 1.000037
SYNOPSIS
--------
```
use Module::Metadata;
# information about a .pm file
my $info = Module::Metadata->new_from_file( $file );
my $version = $info->version;
# CPAN META 'provides' field for .pm files in a directory
my $provides = Module::Metadata->provides(
dir => 'lib', version => 2
);
```
DESCRIPTION
-----------
This module provides a standard way to gather metadata about a .pm file through (mostly) static analysis and (some) code execution. When determining the version of a module, the `$VERSION` assignment is `eval`ed, as is traditional in the CPAN toolchain.
CLASS METHODS
--------------
###
`new_from_file($filename, collect_pod => 1, decode_pod => 1)`
Constructs a `Module::Metadata` object given the path to a file. Returns undef if the filename does not exist.
`collect_pod` is a optional boolean argument that determines whether POD data is collected and stored for reference. POD data is not collected by default. POD headings are always collected.
If the file begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then it is skipped before processing, and the content of the file is also decoded appropriately starting from perl 5.8.
Alternatively, if `decode_pod` is set, it will decode the collected pod sections according to the `=encoding` declaration.
###
`new_from_handle($handle, $filename, collect_pod => 1, decode_pod => 1)`
This works just like `new_from_file`, except that a handle can be provided as the first argument.
Note that there is no validation to confirm that the handle is a handle or something that can act like one. Passing something that isn't a handle will cause a exception when trying to read from it. The `filename` argument is mandatory or undef will be returned.
You are responsible for setting the decoding layers on `$handle` if required.
###
`new_from_module($module, collect_pod => 1, inc => \@dirs, decode_pod => 1)`
Constructs a `Module::Metadata` object given a module or package name. Returns undef if the module cannot be found.
In addition to accepting the `collect_pod` and `decode_pod` arguments as described above, this method accepts a `inc` argument which is a reference to an array of directories to search for the module. If none are given, the default is @INC.
If the file that contains the module begins by an UTF-8, UTF-16BE or UTF-16LE byte-order mark, then it is skipped before processing, and the content of the file is also decoded appropriately starting from perl 5.8.
###
`find_module_by_name($module, \@dirs)`
Returns the path to a module given the module or package name. A list of directories can be passed in as an optional parameter, otherwise @INC is searched.
Can be called as either an object or a class method.
###
`find_module_dir_by_name($module, \@dirs)`
Returns the entry in `@dirs` (or `@INC` by default) that contains the module `$module`. A list of directories can be passed in as an optional parameter, otherwise @INC is searched.
Can be called as either an object or a class method.
###
`provides( %options )`
This is a convenience wrapper around `package_versions_from_directory` to generate a CPAN META `provides` data structure. It takes key/value pairs. Valid option keys include:
version **(required)**
Specifies which version of the <CPAN::Meta::Spec> should be used as the format of the `provides` output. Currently only '1.4' and '2' are supported (and their format is identical). This may change in the future as the definition of `provides` changes.
The `version` option is required. If it is omitted or if an unsupported version is given, then `provides` will throw an error.
dir Directory to search recursively for *.pm* files. May not be specified with `files`.
files Array reference of files to examine. May not be specified with `dir`.
prefix String to prepend to the `file` field of the resulting output. This defaults to *lib*, which is the common case for most CPAN distributions with their *.pm* files in *lib*. This option ensures the META information has the correct relative path even when the `dir` or `files` arguments are absolute or have relative paths from a location other than the distribution root.
For example, given `dir` of 'lib' and `prefix` of 'lib', the return value is a hashref of the form:
```
{
'Package::Name' => {
version => '0.123',
file => 'lib/Package/Name.pm'
},
'OtherPackage::Name' => ...
}
```
###
`package_versions_from_directory($dir, \@files?)`
Scans `$dir` for .pm files (unless `@files` is given, in which case looks for those files in `$dir` - and reads each file for packages and versions, returning a hashref of the form:
```
{
'Package::Name' => {
version => '0.123',
file => 'Package/Name.pm'
},
'OtherPackage::Name' => ...
}
```
The `DB` and `main` packages are always omitted, as are any "private" packages that have leading underscores in the namespace (e.g. `Foo::_private`)
Note that the file path is relative to `$dir` if that is specified. This **must not** be used directly for CPAN META `provides`. See the `provides` method instead.
###
`log_info (internal)`
Used internally to perform logging; imported from Log::Contextual if Log::Contextual has already been loaded, otherwise simply calls warn.
OBJECT METHODS
---------------
###
`name()`
Returns the name of the package represented by this module. If there is more than one package, it makes a best guess based on the filename. If it's a script (i.e. not a \*.pm) the package name is 'main'.
###
`version($package)`
Returns the version as defined by the $VERSION variable for the package as returned by the `name` method if no arguments are given. If given the name of a package it will attempt to return the version of that package if it is specified in the file.
###
`filename()`
Returns the absolute path to the file. Note that this file may not actually exist on disk yet, e.g. if the module was read from an in-memory filehandle.
###
`packages_inside()`
Returns a list of packages. Note: this is a raw list of packages discovered (or assumed, in the case of `main`). It is not filtered for `DB`, `main` or private packages the way the `provides` method does. Invalid package names are not returned, for example "Foo:Bar". Strange but valid package names are returned, for example "Foo::Bar::", and are left up to the caller on how to handle.
###
`pod_inside()`
Returns a list of POD sections.
###
`contains_pod()`
Returns true if there is any POD in the file.
###
`pod($section)`
Returns the POD data in the given section.
###
`is_indexable($package)` or `is_indexable()`
Available since version 1.000020.
Returns a boolean indicating whether the package (if provided) or any package (otherwise) is eligible for indexing by PAUSE, the Perl Authors Upload Server. Note This only checks for valid `package` declarations, and does not take any ownership information into account.
SUPPORT
-------
Bugs may be submitted through [the RT bug tracker](https://rt.cpan.org/Public/Dist/Display.html?Name=Module-Metadata) (or [[email protected]](mailto:[email protected])).
There is also a mailing list available for users of this distribution, at <http://lists.perl.org/list/cpan-workers.html>.
There is also an irc channel available for users of this distribution, at [`#toolchain` on `irc.perl.org`](irc://irc.perl.org/#toolchain).
AUTHOR
------
Original code from Module::Build::ModuleInfo by Ken Williams <[email protected]>, Randy W. Sims <[email protected]>
Released as Module::Metadata by Matt S Trout (mst) <[email protected]> with assistance from David Golden (xdg) <[email protected]>.
CONTRIBUTORS
------------
* Karen Etheridge <[email protected]>
* David Golden <[email protected]>
* Vincent Pit <[email protected]>
* Matt S Trout <[email protected]>
* Chris Nehren <[email protected]>
* Tomas Doran <[email protected]>
* Olivier Mengué <[email protected]>
* Graham Knop <[email protected]>
* tokuhirom <[email protected]>
* Tatsuhiko Miyagawa <[email protected]>
* Christian Walde <[email protected]>
* Leon Timmermans <[email protected]>
* Peter Rabbitson <[email protected]>
* Steve Hay <[email protected]>
* Jerry D. Hedden <[email protected]>
* Craig A. Berry <[email protected]>
* Craig A. Berry <[email protected]>
* David Mitchell <[email protected]>
* David Steinbrunner <[email protected]>
* Edward Zborowski <[email protected]>
* Gareth Harper <[email protected]>
* James Raspass <[email protected]>
* Chris 'BinGOs' Williams <[email protected]>
* Josh Jore <[email protected]>
* Kent Fredric <[email protected]>
COPYRIGHT & LICENSE
--------------------
Original code Copyright (c) 2001-2011 Ken Williams. Additional code Copyright (c) 2010-2011 Matt Trout and David Golden. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl CPAN::Meta::History::Meta_1_2 CPAN::Meta::History::Meta\_1\_2
===============================
CONTENTS
--------
* [NAME](#NAME)
* [PREFACE](#PREFACE)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FORMAT](#FORMAT)
* [TERMINOLOGY](#TERMINOLOGY)
* [VERSION SPECIFICATIONS](#VERSION-SPECIFICATIONS)
* [HEADER](#HEADER)
* [FIELDS](#FIELDS)
+ [meta-spec](#meta-spec)
+ [name](#name)
+ [version](#version)
+ [abstract](#abstract)
+ [author](#author)
+ [license](#license)
+ [distribution\_type](#distribution_type)
+ [requires](#requires)
+ [recommends](#recommends)
+ [build\_requires](#build_requires)
+ [conflicts](#conflicts)
+ [dynamic\_config](#dynamic_config)
+ [private](#private)
+ [provides](#provides)
+ [no\_index](#no_index)
- [file](#file)
- [dir](#dir)
- [package](#package)
- [namespace](#namespace)
+ [keywords](#keywords)
+ [resources](#resources)
+ [generated\_by](#generated_by)
* [SEE ALSO](#SEE-ALSO)
* [HISTORY](#HISTORY)
NAME
----
CPAN::Meta::History::Meta\_1\_2 - Version 1.2 metadata specification for META.yml
PREFACE
-------
This is a historical copy of the version 1.2 specification for *META.yml* files, copyright by Ken Williams and licensed under the same terms as Perl itself.
Modifications from the original:
* Various spelling corrections
* Include list of valid licenses from <Module::Build> 0.2611 rather than linking to the module, with minor updates to text and links to reflect versions at the time of publication.
* Fixed some dead links to point to active resources.
SYNOPSIS
--------
```
--- #YAML:1.0
name: Module-Build
abstract: Build and install Perl modules
version: 0.20
author:
- Ken Williams <[email protected]>
license: perl
distribution_type: module
requires:
Config: 0
Cwd: 0
Data::Dumper: 0
ExtUtils::Install: 0
File::Basename: 0
File::Compare: 0
File::Copy: 0
File::Find: 0
File::Path: 0
File::Spec: 0
IO::File: 0
perl: 5.005_03
recommends:
Archive::Tar: 1.00
ExtUtils::Install: 0.3
ExtUtils::ParseXS: 2.02
Pod::Text: 0
YAML: 0.35
build_requires:
Test: 0
urls:
license: http://dev.perl.org/licenses/
meta-spec:
version: 1.2
url: http://module-build.sourceforge.net/META-spec-v1.2.html
generated_by: Module::Build version 0.20
```
DESCRIPTION
-----------
This document describes version 1.2 of the *META.yml* specification.
The *META.yml* file describes important properties of contributed Perl distributions such as the ones found on CPAN. It is typically created by tools like Module::Build, Module::Install, and ExtUtils::MakeMaker.
The fields in the *META.yml* file are meant to be helpful for people maintaining module collections (like CPAN), for people writing installation tools (like CPAN.pm or CPANPLUS), or just for people who want to know some stuff about a distribution before downloading it and starting to install it.
*Note: The latest stable version of this specification can always be found at <http://module-build.sourceforge.net/META-spec-current.html>, and the latest development version (which may include things that won't make it into the stable version can always be found at <http://module-build.sourceforge.net/META-spec-blead.html>.*
FORMAT
------
*META.yml* files are written in the YAML format (see <http://www.yaml.org/>).
See the following links to learn why we chose YAML instead of, say, XML or Data::Dumper:
* [Module::Build design plans](http://www.nntp.perl.org/group/perl.makemaker/2002/04/msg407.html)
* [Not keen on YAML](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1353.html)
* [META Concerns](http://www.nntp.perl.org/group/perl.module-authors/2003/11/msg1385.html)
TERMINOLOGY
-----------
distribution This is the primary object described by the *META.yml* specification. In the context of this document it usually refers to a collection of modules, scripts, and/or documents that are distributed for other developers to use.
module This refers to a reusable library of code typically contained in a single file. Currently, we primarily talk of perl modules, but this specification should be open enough to apply to other languages as well (ex. python, ruby).
VERSION SPECIFICATIONS
-----------------------
Some fields require a version specification (ex. ["requires"](#requires), ["recommends"](#recommends), ["build\_requires"](#build_requires), etc.). This section details the version specifications that are currently supported.
If a single version is listed, then that version is considered to be the minimum version supported.
If 0 is given as the version number, then any version is supported.
Additionally, for more complicated requirements, the specification supports a list of versions, each of which may be optionally preceded by a relational operator.
Supported operators include < (less than), <= (less than or equal), > (greater than), >= (greater than or equal), == (equal), and != (not equal).
If a list is given then it is evaluated from left to right so that any specifications in the list that conflict with a previous specification are overridden by the later.
Examples:
```
>= 1.2, != 1.5, < 2.0
```
Any version from version 1.2 onward, except version 1.5, that also precedes version 2.0.
HEADER
------
The first line of a *META.yml* file should be a valid YAML document header like `"--- #YAML:1.0"`.
FIELDS
------
The rest of the *META.yml* file is one big YAML mapping whose keys are described here.
###
meta-spec
Example:
```
meta-spec:
version: 1.2
url: http://module-build.sourceforge.net/META-spec-v1.2.html
```
(Spec 1.1) [required] {URL} This field indicates the location of the version of the META.yml specification used.
### name
Example:
```
name: Module-Build
```
(Spec 1.0) [required] {string} The name of the distribution which is often created by taking the "main module" in the distribution and changing "::" to "-". Sometimes it's completely different, however, as in the case of the libwww-perl distribution (see <http://search.cpan.org/author/GAAS/libwww-perl/>).
### version
Example:
```
version: 0.20
```
(Spec 1.0) [required] {version} The version of the distribution to which the *META.yml* file refers.
### abstract
Example:
```
abstract: Build and install Perl modules.
```
(Spec 1.1) [required] {string} A short description of the purpose of the distribution.
### author
Example:
```
author:
- Ken Williams <[email protected]>
```
(Spec 1.1) [required] {list of strings} A YAML sequence indicating the author(s) of the distribution. The preferred form is author-name <email-address>.
### license
Example:
```
license: perl
```
(Spec 1.0) [required] {string} The license under which this distribution may be used and redistributed.
Must be one of the following licenses:
perl The distribution may be copied and redistributed under the same terms as perl itself (this is by far the most common licensing option for modules on CPAN). This is a dual license, in which the user may choose between either the GPL version 1 or the Artistic version 1 license.
gpl The distribution is distributed under the terms of the GNU General Public License version 2 (<http://opensource.org/licenses/GPL-2.0>).
lgpl The distribution is distributed under the terms of the GNU Lesser General Public License version 2 (<http://opensource.org/licenses/LGPL-2.1>).
artistic The distribution is licensed under the Artistic License version 1, as specified by the Artistic file in the standard perl distribution (<http://opensource.org/licenses/Artistic-Perl-1.0>).
bsd The distribution is licensed under the BSD 3-Clause License (<http://opensource.org/licenses/BSD-3-Clause>).
open\_source The distribution is licensed under some other Open Source Initiative-approved license listed at <http://www.opensource.org/licenses/>.
unrestricted The distribution is licensed under a license that is **not** approved by [www.opensource.org](http://www.opensource.org/) but that allows distribution without restrictions.
restrictive The distribution may not be redistributed without special permission from the author and/or copyright holder.
### distribution\_type
Example:
```
distribution_type: module
```
(Spec 1.0) [optional] {string} What kind of stuff is contained in this distribution. Most things on CPAN are `module`s (which can also mean a collection of modules), but some things are `script`s.
Unfortunately this field is basically meaningless, since many distributions are hybrids of several kinds of things, or some new thing, or subjectively different in focus depending on who's using them. Tools like Module::Build and MakeMaker will likely stop generating this field.
### requires
Example:
```
requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules this distribution requires for proper operation. The keys are the module names, and the values are version specifications as described in <Module::Build> for the "requires" parameter.
### recommends
Example:
```
recommends:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules this distribution recommends for enhanced operation.
*ALTERNATIVE: It may be desirable to present to the user which features depend on which modules so they can make an informed decision about which recommended modules to install.*
Example:
```
optional_features:
- foo:
description: Provides the ability to blah.
requires:
Data::Dumper: 0
File::Find: 1.03
- bar:
description: This feature is not available on this platform.
excludes_os: MSWin32
```
*(Spec 1.1) [optional] {map} A YAML sequence of names for optional features which are made available when its requirements are met. For each feature a description is provided along with any of ["requires"](#requires), ["build\_requires"](#build_requires), ["conflicts"](#conflicts), `requires_packages`, `requires_os`, and `excludes_os` which have the same meaning in this subcontext as described elsewhere in this document.*
### build\_requires
Example:
```
build_requires:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules required for building and/or testing of this distribution. These dependencies are not required after the module is installed.
### conflicts
Example:
```
conflicts:
Data::Dumper: 0
File::Find: 1.03
```
(Spec 1.0) [optional] {map} A YAML mapping indicating the Perl modules that cannot be installed while this distribution is installed. This is a pretty uncommon situation.
### dynamic\_config
Example:
```
dynamic_config: 0
```
(Spec 1.0) [optional] {boolean} A boolean flag indicating whether a *Build.PL* or *Makefile.PL* (or similar) must be executed when building this distribution, or whether it can be built, tested and installed solely from consulting its metadata file. The main reason to set this to a true value if that your module performs some dynamic configuration (asking questions, sensing the environment, etc.) as part of its build/install process.
Currently Module::Build doesn't actually do anything with this flag - it's probably going to be up to higher-level tools like CPAN to do something useful with it. It can potentially bring lots of security, packaging, and convenience improvements.
If this field is omitted, it defaults to 1 (true).
### private
*(Deprecated)* (Spec 1.0) [optional] {map} This field has been renamed to ["no\_index"](#no_index). See below.
### provides
Example:
```
provides:
Foo::Bar:
file: lib/Foo/Bar.pm
version: 0.27_02
Foo::Bar::Blah:
file: lib/Foo/Bar/Blah.pm
Foo::Bar::Baz:
file: lib/Foo/Bar/Baz.pm
version: 0.3
```
(Spec 1.1) [optional] {map} A YAML mapping that describes all packages provided by this distribution. This information can be (and, in some cases, is) used by distribution and automation mechanisms like PAUSE, CPAN, and search.cpan.org to build indexes saying in which distribution various packages can be found.
When using tools like <Module::Build> that can generate the `provides` mapping for your distribution automatically, make sure you examine what it generates to make sure it makes sense - indexers will usually trust the `provides` field if it's present, rather than scanning through the distribution files themselves to figure out packages and versions. This is a good thing, because it means you can use the `provides` field to tell the indexers precisely what you want indexed about your distribution, rather than relying on them to essentially guess what you want indexed.
### no\_index
Example:
```
no_index:
file:
- My/Module.pm
dir:
- My/Private
package:
- My::Module::Stuff
namespace:
- My::Module::Stuff
```
(Spec 1.1) [optional] {map} A YAML mapping that describes any files, directories, packages, and namespaces that are private (i.e. implementation artifacts) that are not of interest to searching and indexing tools. This is useful when no `provides` field is present.
*(Note: I'm not actually sure who looks at this field, or exactly what they do with it. This spec could be off in some way from actual usage.)*
#### file
(Spec 1.1) [optional] Exclude any listed file(s).
#### dir
(Spec 1.1) [optional] Exclude anything below the listed directory(ies).
#### package
(Spec 1.1) [optional] Exclude the listed package(s).
#### namespace
(Spec 1.1) [optional] Excludes anything below the listed namespace(s), but *not* the listed namespace(s) its self.
### keywords
Example:
```
keywords:
- make
- build
- install
```
(Spec 1.1) [optional] {list} A sequence of keywords/phrases that describe this distribution.
### resources
Example:
```
resources:
license: http://dev.perl.org/licenses/
homepage: http://sourceforge.net/projects/module-build
bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=Module-Build
MailingList: http://lists.sourceforge.net/lists/listinfo/module-build-general
```
(Spec 1.1) [optional] {map} A mapping of any URL resources related to this distribution. All-lower-case keys, such as `homepage`, `license`, and `bugtracker`, are reserved by this specification, as they have "official" meanings defined here in this specification. If you'd like to add your own "special" entries (like the "MailingList" entry above), use at least one upper-case letter.
The current set of official keys is:
homepage The official home of this project on the web.
license An URL for an official statement of this distribution's license.
bugtracker An URL for a bug tracker (e.g. Bugzilla or RT queue) for this project.
### generated\_by
Example:
```
generated_by: Module::Build version 0.20
```
(Spec 1.0) [required] {string} Indicates the tool that was used to create this *META.yml* file. It's good form to include both the name of the tool and its version, but this field is essentially opaque, at least for the moment. If *META.yml* was generated by hand, it is suggested that the author be specified here.
[Note: My *meta\_stats.pl* script which I use to gather statistics regarding *META.yml* usage prefers the form listed above, i.e. it splits on /\s+version\s+/ taking the first field as the name of the tool that generated the file and the second field as version of that tool. RWS]
SEE ALSO
---------
[CPAN](http://www.cpan.org/)
[CPAN.pm](cpan)
[CPANPLUS](cpanplus)
<Data::Dumper>
<ExtUtils::MakeMaker>
<Module::Build>
<Module::Install>
[XML](http://www.w3.org/XML/)
[YAML](http://www.yaml.org/)
HISTORY
-------
March 14, 2003 (Pi day) * Created version 1.0 of this document.
May 8, 2003 * Added the ["dynamic\_config"](#dynamic_config) field, which was missing from the initial version.
November 13, 2003 * Added more YAML rationale articles.
* Fixed existing link to YAML discussion thread to point to new <http://nntp.x.perl.org/group/> site.
* Added and deprecated the ["private"](#private) field.
* Added ["abstract"](#abstract), `configure`, `requires_packages`, `requires_os`, `excludes_os`, and ["no\_index"](#no_index) fields.
* Bumped version.
November 16, 2003 * Added `generation`, `authored_by` fields.
* Add alternative proposal to the ["recommends"](#recommends) field.
* Add proposal for a `requires_build_tools` field.
December 9, 2003 * Added link to latest version of this specification on CPAN.
* Added section ["VERSION SPECIFICATIONS"](#VERSION-SPECIFICATIONS).
* Chang name from Module::Build::META-spec to CPAN::META::Specification.
* Add proposal for `auto_regenerate` field.
December 15, 2003 * Add `index` field as a compliment to ["no\_index"](#no_index)
* Add ["keywords"](#keywords) field as a means to aid searching distributions.
* Add ["TERMINOLOGY"](#TERMINOLOGY) section to explain certain terms that may be ambiguous.
July 26, 2005 * Removed a bunch of items (generation, requires\_build\_tools, requires\_packages, configure, requires\_os, excludes\_os, auto\_regenerate) that have never actually been supported, but were more like records of brainstorming.
* Changed `authored_by` to ["author"](#author), since that's always been what it's actually called in actual *META.yml* files.
* Added the "==" operator to the list of supported version-checking operators.
* Noted that the ["distribution\_type"](#distribution_type) field is basically meaningless, and shouldn't really be used.
* Clarified ["dynamic\_config"](#dynamic_config) a bit.
August 23, 2005 * Removed the name `CPAN::META::Specification`, since that implies a module that doesn't actually exist.
| programming_docs |
perl ExtUtils::Liblist ExtUtils::Liblist
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [EXTRALIBS](#EXTRALIBS)
+ [LDLOADLIBS and LD\_RUN\_PATH](#LDLOADLIBS-and-LD_RUN_PATH)
+ [BSLOADLIBS](#BSLOADLIBS)
* [PORTABILITY](#PORTABILITY)
+ [VMS implementation](#VMS-implementation)
+ [Win32 implementation](#Win32-implementation)
* [SEE ALSO](#SEE-ALSO)
NAME
----
ExtUtils::Liblist - determine libraries to use and how to use them
SYNOPSIS
--------
```
require ExtUtils::Liblist;
$MM->ext($potential_libs, $verbose, $need_names);
# Usually you can get away with:
ExtUtils::Liblist->ext($potential_libs, $verbose, $need_names)
```
DESCRIPTION
-----------
This utility takes a list of libraries in the form `-llib1 -llib2 -llib3` and returns lines suitable for inclusion in an extension Makefile. Extra library paths may be included with the form `-L/another/path` this will affect the searches for all subsequent libraries.
It returns an array of four or five scalar values: EXTRALIBS, BSLOADLIBS, LDLOADLIBS, LD\_RUN\_PATH, and, optionally, a reference to the array of the filenames of actual libraries. Some of these don't mean anything unless on Unix. See the details about those platform specifics below. The list of the filenames is returned only if $need\_names argument is true.
Dependent libraries can be linked in one of three ways:
* For static extensions
by the ld command when the perl binary is linked with the extension library. See EXTRALIBS below.
* For dynamic extensions at build/link time
by the ld command when the shared object is built/linked. See LDLOADLIBS below.
* For dynamic extensions at load time
by the DynaLoader when the shared object is loaded. See BSLOADLIBS below.
### EXTRALIBS
List of libraries that need to be linked with when linking a perl binary which includes this extension. Only those libraries that actually exist are included. These are written to a file and used when linking perl.
###
LDLOADLIBS and LD\_RUN\_PATH
List of those libraries which can or must be linked into the shared library when created using ld. These may be static or dynamic libraries. LD\_RUN\_PATH is a colon separated list of the directories in LDLOADLIBS. It is passed as an environment variable to the process that links the shared library.
### BSLOADLIBS
List of those libraries that are needed but can be linked in dynamically at run time on this platform. SunOS/Solaris does not need this because ld records the information (from LDLOADLIBS) into the object file. This list is used to create a .bs (bootstrap) file.
PORTABILITY
-----------
This module deals with a lot of system dependencies and has quite a few architecture specific `if`s in the code.
###
VMS implementation
The version of ext() which is executed under VMS differs from the Unix-OS/2 version in several respects:
* Input library and path specifications are accepted with or without the `-l` and `-L` prefixes used by Unix linkers. If neither prefix is present, a token is considered a directory to search if it is in fact a directory, and a library to search for otherwise. Authors who wish their extensions to be portable to Unix or OS/2 should use the Unix prefixes, since the Unix-OS/2 version of ext() requires them.
* Wherever possible, shareable images are preferred to object libraries, and object libraries to plain object files. In accordance with VMS naming conventions, ext() looks for files named *lib*shr and *lib*rtl; it also looks for *lib*lib and lib*lib* to accommodate Unix conventions used in some ported software.
* For each library that is found, an appropriate directive for a linker options file is generated. The return values are space-separated strings of these directives, rather than elements used on the linker command line.
* LDLOADLIBS contains both the libraries found based on `$potential_libs` and the CRTLs, if any, specified in Config.pm. EXTRALIBS contains just those libraries found based on `$potential_libs`. BSLOADLIBS and LD\_RUN\_PATH are always empty.
In addition, an attempt is made to recognize several common Unix library names, and filter them out or convert them to their VMS equivalents, as appropriate.
In general, the VMS version of ext() should properly handle input from extensions originally designed for a Unix or VMS environment. If you encounter problems, or discover cases where the search could be improved, please let us know.
###
Win32 implementation
The version of ext() which is executed under Win32 differs from the Unix-OS/2 version in several respects:
* If `$potential_libs` is empty, the return value will be empty. Otherwise, the libraries specified by `$Config{perllibs}` (see Config.pm) will be appended to the list of `$potential_libs`. The libraries will be searched for in the directories specified in `$potential_libs`, `$Config{libpth}`, and in `$Config{installarchlib}/CORE`. For each library that is found, a space-separated list of fully qualified library pathnames is generated.
* Input library and path specifications are accepted with or without the `-l` and `-L` prefixes used by Unix linkers.
An entry of the form `-La:\foo` specifies the `a:\foo` directory to look for the libraries that follow.
An entry of the form `-lfoo` specifies the library `foo`, which may be spelled differently depending on what kind of compiler you are using. If you are using GCC, it gets translated to `libfoo.a`, but for other win32 compilers, it becomes `foo.lib`. If no files are found by those translated names, one more attempt is made to find them using either `foo.a` or `libfoo.lib`, depending on whether GCC or some other win32 compiler is being used, respectively.
If neither the `-L` or `-l` prefix is present in an entry, the entry is considered a directory to search if it is in fact a directory, and a library to search for otherwise. The `$Config{lib_ext}` suffix will be appended to any entries that are not directories and don't already have the suffix.
Note that the `-L` and `-l` prefixes are **not required**, but authors who wish their extensions to be portable to Unix or OS/2 should use the prefixes, since the Unix-OS/2 version of ext() requires them.
* Entries cannot be plain object files, as many Win32 compilers will not handle object files in the place of libraries.
* Entries in `$potential_libs` beginning with a colon and followed by alphanumeric characters are treated as flags. Unknown flags will be ignored.
An entry that matches `/:nodefault/i` disables the appending of default libraries found in `$Config{perllibs}` (this should be only needed very rarely).
An entry that matches `/:nosearch/i` disables all searching for the libraries specified after it. Translation of `-Lfoo` and `-lfoo` still happens as appropriate (depending on compiler being used, as reflected by `$Config{cc}`), but the entries are not verified to be valid files or directories.
An entry that matches `/:search/i` reenables searching for the libraries specified after it. You can put it at the end to enable searching for default libraries specified by `$Config{perllibs}`.
* The libraries specified may be a mixture of static libraries and import libraries (to link with DLLs). Since both kinds are used pretty transparently on the Win32 platform, we do not attempt to distinguish between them.
* LDLOADLIBS and EXTRALIBS are always identical under Win32, and BSLOADLIBS and LD\_RUN\_PATH are always empty (this may change in future).
* You must make sure that any paths and path components are properly surrounded with double-quotes if they contain spaces. For example, `$potential_libs` could be (literally):
```
"-Lc:\Program Files\vc\lib" msvcrt.lib "la test\foo bar.lib"
```
Note how the first and last entries are protected by quotes in order to protect the spaces.
* Since this module is most often used only indirectly from extension `Makefile.PL` files, here is an example `Makefile.PL` entry to add a library to the build process for an extension:
```
LIBS => ['-lgl']
```
When using GCC, that entry specifies that MakeMaker should first look for `libgl.a` (followed by `gl.a`) in all the locations specified by `$Config{libpth}`.
When using a compiler other than GCC, the above entry will search for `gl.lib` (followed by `libgl.lib`).
If the library happens to be in a location not in `$Config{libpth}`, you need:
```
LIBS => ['-Lc:\gllibs -lgl']
```
Here is a less often used example:
```
LIBS => ['-lgl', ':nosearch -Ld:\mesalibs -lmesa -luser32']
```
This specifies a search for library `gl` as before. If that search fails to find the library, it looks at the next item in the list. The `:nosearch` flag will prevent searching for the libraries that follow, so it simply returns the value as `-Ld:\mesalibs -lmesa -luser32`, since GCC can use that value as is with its linker.
When using the Visual C compiler, the second item is returned as `-libpath:d:\mesalibs mesa.lib user32.lib`.
When using the Borland compiler, the second item is returned as `-Ld:\mesalibs mesa.lib user32.lib`, and MakeMaker takes care of moving the `-Ld:\mesalibs` to the correct place in the linker command line.
SEE ALSO
---------
<ExtUtils::MakeMaker>
perl Encode::Supported Encode::Supported
=================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Encoding Names](#Encoding-Names)
* [Supported Encodings](#Supported-Encodings)
+ [Built-in Encodings](#Built-in-Encodings)
+ [Encode::Unicode -- other Unicode encodings](#Encode::Unicode-other-Unicode-encodings)
+ [Encode::Byte -- Extended ASCII](#Encode::Byte-Extended-ASCII)
+ [gsm0338 - Hentai Latin 1](#gsm0338-Hentai-Latin-1)
+ [CJK: Chinese, Japanese, Korean (Multibyte)](#CJK:-Chinese,-Japanese,-Korean-(Multibyte))
+ [Miscellaneous encodings](#Miscellaneous-encodings)
* [Unsupported encodings](#Unsupported-encodings)
* [Encoding vs. Charset -- terminology](#Encoding-vs.-Charset-terminology)
* [Encoding Classification (by Anton Tagunov and Dan Kogai)](#Encoding-Classification-(by-Anton-Tagunov-and-Dan-Kogai))
+ [Microsoft-related naming mess](#Microsoft-related-naming-mess)
* [Glossary](#Glossary)
* [See Also](#See-Also)
* [References](#References)
+ [Other Notable Sites](#Other-Notable-Sites)
+ [Offline sources](#Offline-sources)
NAME
----
Encode::Supported -- Encodings supported by Encode
DESCRIPTION
-----------
###
Encoding Names
Encoding names are case insensitive. White space in names is ignored. In addition, an encoding may have aliases. Each encoding has one "canonical" name. The "canonical" name is chosen from the names of the encoding by picking the first in the following sequence (with a few exceptions).
* The name used by the Perl community. That includes 'utf8' and 'ascii'. Unlike aliases, canonical names directly reach the method so such frequently used words like 'utf8' don't need to do alias lookups.
* The MIME name as defined in IETF RFCs. This includes all "iso-"s.
* The name in the IANA registry.
* The name used by the organization that defined it.
In case *de jure* canonical names differ from that of the Encode module, they are always aliased if it ever be implemented. So you can safely tell if a given encoding is implemented or not just by passing the canonical name.
Because of all the alias issues, and because in the general case encodings have state, "Encode" uses an encoding object internally once an operation is in progress.
Supported Encodings
--------------------
As of Perl 5.8.0, at least the following encodings are recognized. Note that unless otherwise specified, they are all case insensitive (via alias) and all occurrence of spaces are replaced with '-'. In other words, "ISO 8859 1" and "iso-8859-1" are identical.
Encodings are categorized and implemented in several different modules but you don't have to `use Encode::XX` to make them available for most cases. Encode.pm will automatically load those modules on demand.
###
Built-in Encodings
The following encodings are always available.
```
Canonical Aliases Comments & References
----------------------------------------------------------------
ascii US-ascii ISO-646-US [ECMA]
ascii-ctrl Special Encoding
iso-8859-1 latin1 [ISO]
null Special Encoding
utf8 UTF-8 [RFC2279]
----------------------------------------------------------------
```
*null* and *ascii-ctrl* are special. "null" fails for all character so when you set fallback mode to PERLQQ, HTMLCREF or XMLCREF, ALL CHARACTERS will fall back to character references. Ditto for "ascii-ctrl" except for control characters. For fallback modes, see [Encode](encode).
###
Encode::Unicode -- other Unicode encodings
Unicode coding schemes other than native utf8 are supported by Encode::Unicode, which will be autoloaded on demand.
```
----------------------------------------------------------------
UCS-2BE UCS-2, iso-10646-1 [IANA, UC]
UCS-2LE [UC]
UTF-16 [UC]
UTF-16BE [UC]
UTF-16LE [UC]
UTF-32 [UC]
UTF-32BE UCS-4 [UC]
UTF-32LE [UC]
UTF-7 [RFC2152]
----------------------------------------------------------------
```
To find how (UCS-2|UTF-(16|32))(LE|BE)? differ from one another, see <Encode::Unicode>.
UTF-7 is a special encoding which "re-encodes" UTF-16BE into a 7-bit encoding. It is implemented separately by Encode::Unicode::UTF7.
###
Encode::Byte -- Extended ASCII
Encode::Byte implements most single-byte encodings except for Symbols and EBCDIC. The following encodings are based on single-byte encodings implemented as extended ASCII. Most of them map \x80-\xff (upper half) to non-ASCII characters.
ISO-8859 and corresponding vendor mappings Since there are so many, they are presented in table format with languages and corresponding encoding names by vendors. Note that the table is sorted in order of ISO-8859 and the corresponding vendor mappings are slightly different from that of ISO. See <http://czyborra.com/charsets/iso8859.html> for details.
```
Lang/Regions ISO/Other Std. DOS Windows Macintosh Others
----------------------------------------------------------------
N. America (ASCII) cp437 AdobeStandardEncoding
cp863 (DOSCanadaF)
W. Europe iso-8859-1 cp850 cp1252 MacRoman nextstep
hp-roman8
cp860 (DOSPortuguese)
Cntrl. Europe iso-8859-2 cp852 cp1250 MacCentralEurRoman
MacCroatian
MacRomanian
MacRumanian
Latin3[1] iso-8859-3
Latin4[2] iso-8859-4
Cyrillics iso-8859-5 cp855 cp1251 MacCyrillic
(See also next section) cp866 MacUkrainian
Arabic iso-8859-6 cp864 cp1256 MacArabic
cp1006 MacFarsi
Greek iso-8859-7 cp737 cp1253 MacGreek
cp869 (DOSGreek2)
Hebrew iso-8859-8 cp862 cp1255 MacHebrew
Turkish iso-8859-9 cp857 cp1254 MacTurkish
Nordics iso-8859-10 cp865
cp861 MacIcelandic
MacSami
Thai iso-8859-11[3] cp874 MacThai
(iso-8859-12 is nonexistent. Reserved for Indics?)
Baltics iso-8859-13 cp775 cp1257
Celtics iso-8859-14
Latin9 [4] iso-8859-15
Latin10 iso-8859-16
Vietnamese viscii cp1258 MacVietnamese
----------------------------------------------------------------
[1] Esperanto, Maltese, and Turkish. Turkish is now on 8859-9.
[2] Baltics. Now on 8859-10, except for Latvian.
[3] TIS 620 + Non-Breaking Space (0xA0 / U+00A0)
[4] Nicknamed Latin0; the Euro sign as well as French and Finnish
letters that are missing from 8859-1 were added.
```
All cp\* are also available as ibm-\*, ms-\*, and windows-\* . See also <http://czyborra.com/charsets/codepages.html>.
Macintosh encodings don't seem to be registered in such entities as IANA. "Canonical" names in Encode are based upon Apple's Tech Note 1150. See <http://developer.apple.com/technotes/tn/tn1150.html> for details.
KOI8 - De Facto Standard for the Cyrillic world Though ISO-8859 does have ISO-8859-5, the KOI8 series is far more popular in the Net. [Encode](encode) comes with the following KOI charsets. For gory details, see <http://czyborra.com/charsets/cyrillic.html>
```
----------------------------------------------------------------
koi8-f
koi8-r cp878 [RFC1489]
koi8-u [RFC2319]
----------------------------------------------------------------
```
###
gsm0338 - Hentai Latin 1
GSM0338 is for GSM handsets. Though it shares alphanumerals with ASCII, control character ranges and other parts are mapped very differently, mainly to store Greek characters. There are also escape sequences (starting with 0x1B) to cover e.g. the Euro sign.
This was once handled by <Encode::Bytes> but because of all those unusual specifications, Encode 2.20 has relocated the support to <Encode::GSM0338>. See <Encode::GSM0338> for details.
gsm0338 support before 2.19 Some special cases like a trailing 0x00 byte or a lone 0x1B byte are not well-defined and decode() will return an empty string for them. One possible workaround is
```
$gsm =~ s/\x00\z/\x00\x00/;
$uni = decode("gsm0338", $gsm);
$uni .= "\xA0" if $gsm =~ /\x1B\z/;
```
Note that the Encode implementation of GSM0338 does not implement the reuse of Latin capital letters as Greek capital letters (for example, the 0x5A is U+005A (LATIN CAPITAL LETTER Z), not U+0396 (GREEK CAPITAL LETTER ZETA).
The GSM0338 is also covered in Encode::Byte even though it is not an "extended ASCII" encoding.
###
CJK: Chinese, Japanese, Korean (Multibyte)
Note that Vietnamese is listed above. Also read "Encoding vs Charset" below. Also note that these are implemented in distinct modules by countries, due to the size concerns (simplified Chinese is mapped to 'CN', continental China, while traditional Chinese is mapped to 'TW', Taiwan). Please refer to their respective documentation pages.
Encode::CN -- Continental China
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
euc-cn [1] MacChineseSimp
(gbk) cp936 [2]
gb12345-raw { GB12345 without CES }
gb2312-raw { GB2312 without CES }
hz
iso-ir-165
----------------------------------------------------------------
[1] GB2312 is aliased to this. See L<Microsoft-related naming mess>
[2] gbk is aliased to this. See L<Microsoft-related naming mess>
```
Encode::JP -- Japan
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
euc-jp
shiftjis cp932 macJapanese
7bit-jis
iso-2022-jp [RFC1468]
iso-2022-jp-1 [RFC2237]
jis0201-raw { JIS X 0201 (roman + halfwidth kana) without CES }
jis0208-raw { JIS X 0208 (Kanji + fullwidth kana) without CES }
jis0212-raw { JIS X 0212 (Extended Kanji) without CES }
----------------------------------------------------------------
```
Encode::KR -- Korea
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
euc-kr MacKorean [RFC1557]
cp949 [1]
iso-2022-kr [RFC1557]
johab [KS X 1001:1998, Annex 3]
ksc5601-raw { KSC5601 without CES }
----------------------------------------------------------------
[1] ks_c_5601-1987, (x-)?windows-949, and uhc are aliased to this.
See below.
```
Encode::TW -- Taiwan
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
big5-eten cp950 MacChineseTrad {big5 aliased to big5-eten}
big5-hkscs
----------------------------------------------------------------
```
Encode::HanExtra -- More Chinese via CPAN Due to the size concerns, additional Chinese encodings below are distributed separately on CPAN, under the name Encode::HanExtra.
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
big5ext CMEX's Big5e Extension
big5plus CMEX's Big5+ Extension
cccii Chinese Character Code for Information Interchange
euc-tw EUC (Extended Unix Character)
gb18030 GBK with Traditional Characters
----------------------------------------------------------------
```
Encode::JIS2K -- JIS X 0213 encodings via CPAN Due to size concerns, additional Japanese encodings below are distributed separately on CPAN, under the name Encode::JIS2K.
```
Standard DOS/Win Macintosh Comment/Reference
----------------------------------------------------------------
euc-jisx0213
shiftjisx0123
iso-2022-jp-3
jis0213-1-raw
jis0213-2-raw
----------------------------------------------------------------
```
###
Miscellaneous encodings
Encode::EBCDIC See <perlebcdic> for details.
```
----------------------------------------------------------------
cp37
cp500
cp875
cp1026
cp1047
posix-bc
----------------------------------------------------------------
```
Encode::Symbols For symbols and dingbats.
```
----------------------------------------------------------------
symbol
dingbats
MacDingbats
AdobeZdingbat
AdobeSymbol
----------------------------------------------------------------
```
Encode::MIME::Header Strictly speaking, MIME header encoding documented in RFC 2047 is more of encapsulation than encoding. However, their support in modern world is imperative so they are supported.
```
----------------------------------------------------------------
MIME-Header [RFC2047]
MIME-B [RFC2047]
MIME-Q [RFC2047]
----------------------------------------------------------------
```
Encode::Guess This one is not a name of encoding but a utility that lets you pick up the most appropriate encoding for a data out of given *suspects*. See <Encode::Guess> for details.
Unsupported encodings
----------------------
The following encodings are not supported as yet; some because they are rarely used, some because of technical difficulties. They may be supported by external modules via CPAN in the future, however.
ISO-2022-JP-2 [RFC1554] Not very popular yet. Needs Unicode Database or equivalent to implement encode() (because it includes JIS X 0208/0212, KSC5601, and GB2312 simultaneously, whose code points in Unicode overlap. So you need to lookup the database to determine to what character set a given Unicode character should belong).
ISO-2022-CN [RFC1922] Not very popular. Needs CNS 11643-1 and -2 which are not available in this module. CNS 11643 is supported (via euc-tw) in Encode::HanExtra. Audrey Tang may add support for this encoding in her module in future.
Various HP-UX encodings The following are unsupported due to the lack of mapping data.
```
'8' - arabic8, greek8, hebrew8, kana8, thai8, and turkish8
'15' - japanese15, korean15, and roi15
```
Cyrillic encoding ISO-IR-111 Anton Tagunov doubts its usefulness.
ISO-8859-8-1 [Hebrew] None of the Encode team knows Hebrew enough (ISO-8859-8, cp1255 and MacHebrew are supported because and just because there were mappings available at <http://www.unicode.org/>). Contributions welcome.
ISIRI 3342, Iran System, ISIRI 2900 [Farsi] Ditto.
Thai encoding TCVN Ditto.
Vietnamese encodings VPS Though Jungshik Shin has reported that Mozilla supports this encoding, it was too late before 5.8.0 for us to add it. In the future, it may be available via a separate module. See <http://lxr.mozilla.org/seamonkey/source/intl/uconv/ucvlatin/vps.uf> and <http://lxr.mozilla.org/seamonkey/source/intl/uconv/ucvlatin/vps.ut> if you are interested in helping us.
Various Mac encodings The following are unsupported due to the lack of mapping data.
```
MacArmenian, MacBengali, MacBurmese, MacEthiopic
MacExtArabic, MacGeorgian, MacKannada, MacKhmer
MacLaotian, MacMalayalam, MacMongolian, MacOriya
MacSinhalese, MacTamil, MacTelugu, MacTibetan
MacVietnamese
```
The rest which are already available are based upon the vendor mappings at <http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/> .
(Mac) Indic encodings The maps for the following are available at <http://www.unicode.org/> but remain unsupported because those encodings need an algorithmical approach, currently unsupported by *enc2xs*:
```
MacDevanagari
MacGurmukhi
MacGujarati
```
For details, please see `Unicode mapping issues and notes:` at <http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/DEVANAGA.TXT> .
I believe this issue is prevalent not only for Mac Indics but also in other Indic encodings, but the above were the only Indic encodings maps that I could find at <http://www.unicode.org/> .
Encoding vs. Charset -- terminology
------------------------------------
We are used to using the term (character) *encoding* and *character set* interchangeably. But just as confusing the terms byte and character is dangerous and the terms should be differentiated when needed, we need to differentiate *encoding* and *character set*.
To understand that, here is a description of how we make computers grok our characters.
* First we start with which characters to include. We call this collection of characters *character repertoire*.
* Then we have to give each character a unique ID so your computer can tell the difference between 'a' and 'A'. This itemized character repertoire is now a *character set*.
* If your computer can grow the character set without further processing, you can go ahead and use it. This is called a *coded character set* (CCS) or *raw character encoding*. ASCII is used this way for most cases.
* But in many cases, especially multi-byte CJK encodings, you have to tweak a little more. Your network connection may not accept any data with the Most Significant Bit set, and your computer may not be able to tell if a given byte is a whole character or just half of it. So you have to *encode* the character set to use it.
A *character encoding scheme* (CES) determines how to encode a given character set, or a set of multiple character sets. 7bit ISO-2022 is an example of a CES. You switch between character sets via *escape sequences*.
Technically, or mathematically, speaking, a character set encoded in such a CES that maps character by character may form a CCS. EUC is such an example. The CES of EUC is as follows:
* Map ASCII unchanged.
* Map such a character set that consists of 94 or 96 powered by N members by adding 0x80 to each byte.
* You can also use 0x8e and 0x8f to indicate that the following sequence of characters belongs to yet another character set. To each following byte is added the value 0x80.
By carefully looking at the encoded byte sequence, you can find that the byte sequence conforms a unique number. In that sense, EUC is a CCS generated by a CES above from up to four CCS (complicated?). UTF-8 falls into this category. See ["UTF-8" in perlUnicode](perlunicode#UTF-8) to find out how UTF-8 maps Unicode to a byte sequence.
You may also have found out by now why 7bit ISO-2022 cannot comprise a CCS. If you look at a byte sequence \x21\x21, you can't tell if it is two !'s or IDEOGRAPHIC SPACE. EUC maps the latter to \xA1\xA1 so you have no trouble differentiating between "!!". and " ".
Encoding Classification (by Anton Tagunov and Dan Kogai)
---------------------------------------------------------
This section tries to classify the supported encodings by their applicability for information exchange over the Internet and to choose the most suitable aliases to name them in the context of such communication.
* To (en|de)code encodings marked by `(**)`, you need `Encode::HanExtra`, available from CPAN.
Encoding names
```
US-ASCII UTF-8 ISO-8859-* KOI8-R
Shift_JIS EUC-JP ISO-2022-JP ISO-2022-JP-1
EUC-KR Big5 GB2312
```
are registered with IANA as preferred MIME names and may be used over the Internet.
`Shift_JIS` has been officialized by JIS X 0208:1997. ["Microsoft-related naming mess"](#Microsoft-related-naming-mess) gives details.
`GB2312` is the IANA name for `EUC-CN`. See ["Microsoft-related naming mess"](#Microsoft-related-naming-mess) for details.
`GB_2312-80` *raw* encoding is available as `gb2312-raw` with Encode. See <Encode::CN> for details.
```
EUC-CN
KOI8-U [RFC2319]
```
have not been registered with IANA (as of March 2002) but seem to be supported by major web browsers. The IANA name for `EUC-CN` is `GB2312`.
```
KS_C_5601-1987
```
is heavily misused. See ["Microsoft-related naming mess"](#Microsoft-related-naming-mess) for details.
`KS_C_5601-1987` *raw* encoding is available as `kcs5601-raw` with Encode. See <Encode::KR> for details.
```
UTF-16 UTF-16BE UTF-16LE
```
are IANA-registered `charset`s. See [RFC 2781] for details. Jungshik Shin reports that UTF-16 with a BOM is well accepted by MS IE 5/6 and NS 4/6. Beware however that
* `UTF-16` support in any software you're going to be using/interoperating with has probably been less tested then `UTF-8` support
* `UTF-8` coded data seamlessly passes traditional command piping (`cat`, `more`, etc.) while `UTF-16` coded data is likely to cause confusion (with its zero bytes, for example)
* it is beyond the power of words to describe the way HTML browsers encode non-`ASCII` form data. To get a general impression, visit <http://www.alanflavell.org.uk/charset/form-i18n.html>. While encoding of form data has stabilized for `UTF-8` encoded pages (at least IE 5/6, NS 6, and Opera 6 behave consistently), be sure to expect fun (and cross-browser discrepancies) with `UTF-16` encoded pages!
The rule of thumb is to use `UTF-8` unless you know what you're doing and unless you really benefit from using `UTF-16`.
```
ISO-IR-165 [RFC1345]
VISCII
GB 12345
GB 18030 (**) (see links below)
EUC-TW (**)
```
are totally valid encodings but not registered at IANA. The names under which they are listed here are probably the most widely-known names for these encodings and are recommended names.
```
BIG5PLUS (**)
```
is a proprietary name.
###
Microsoft-related naming mess
Microsoft products misuse the following names:
KS\_C\_5601-1987 Microsoft extension to `EUC-KR`.
Proper names: `CP949`, `UHC`, `x-windows-949` (as used by Mozilla).
See <http://lists.w3.org/Archives/Public/ietf-charsets/2001AprJun/0033.html> for details.
Encode aliases `KS_C_5601-1987` to `cp949` to reflect this common misusage. *Raw* `KS_C_5601-1987` encoding is available as `kcs5601-raw`.
See <Encode::KR> for details.
GB2312 Microsoft extension to `EUC-CN`.
Proper names: `CP936`, `GBK`.
`GB2312` has been registered in the `EUC-CN` meaning at IANA. This has partially repaired the situation: Microsoft's `GB2312` has become a superset of the official `GB2312`.
Encode aliases `GB2312` to `euc-cn` in full agreement with IANA registration. `cp936` is supported separately. *Raw* `GB_2312-80` encoding is available as `gb2312-raw`.
See <Encode::CN> for details.
Big5 Microsoft extension to `Big5`.
Proper name: `CP950`.
Encode separately supports `Big5` and `cp950`.
Shift\_JIS Microsoft's understanding of `Shift_JIS`.
JIS has not endorsed the full Microsoft standard however. The official `Shift_JIS` includes only JIS X 0201 and JIS X 0208 character sets, while Microsoft has always used `Shift_JIS` to encode a wider character repertoire. See `IANA` registration for `Windows-31J`.
As a historical predecessor, Microsoft's variant probably has more rights for the name, though it may be objected that Microsoft shouldn't have used JIS as part of the name in the first place.
Unambiguous name: `CP932`. `IANA` name (also used by Mozilla, and provided as an alias by Encode): `Windows-31J`.
Encode separately supports `Shift_JIS` and `cp932`.
Glossary
--------
character repertoire A collection of unique characters. A *character* set in the strictest sense. At this stage, characters are not numbered.
coded character set (CCS) A character set that is mapped in a way computers can use directly. Many character encodings, including EUC, fall in this category.
character encoding scheme (CES) An algorithm to map a character set to a byte sequence. You don't have to be able to tell which character set a given byte sequence belongs. 7-bit ISO-2022 is a CES but it cannot be a CCS. EUC is an example of being both a CCS and CES.
charset (in MIME context) has long been used in the meaning of `encoding`, CES.
While the word combination `character set` has lost this meaning in MIME context since [RFC 2130], the `charset` abbreviation has retained it. This is how [RFC 2277] and [RFC 2278] bless `charset`:
```
This document uses the term "charset" to mean a set of rules for
mapping from a sequence of octets to a sequence of characters, such
as the combination of a coded character set and a character encoding
scheme; this is also what is used as an identifier in MIME "charset="
parameters, and registered in the IANA charset registry ... (Note
that this is NOT a term used by other standards bodies, such as ISO).
[RFC 2277]
```
EUC Extended Unix Character. See ISO-2022.
ISO-2022 A CES that was carefully designed to coexist with ASCII. There are a 7 bit version and an 8 bit version.
The 7 bit version switches character set via escape sequence so it cannot form a CCS. Since this is more difficult to handle in programs than the 8 bit version, the 7 bit version is not very popular except for iso-2022-jp, the *de facto* standard CES for e-mails.
The 8 bit version can form a CCS. EUC and ISO-8859 are two examples thereof. Pre-5.6 perl could use them as string literals.
UCS Short for *Universal Character Set*. When you say just UCS, it means *Unicode*.
UCS-2 ISO/IEC 10646 encoding form: Universal Character Set coded in two octets.
Unicode A character set that aims to include all character repertoires of the world. Many character sets in various national as well as industrial standards have become, in a way, just subsets of Unicode.
UTF Short for *Unicode Transformation Format*. Determines how to map a Unicode character into a byte sequence.
UTF-16 A UTF in 16-bit encoding. Can either be in big endian or little endian. The big endian version is called UTF-16BE (equal to UCS-2 + surrogate support) and the little endian version is called UTF-16LE.
See Also
---------
[Encode](encode), <Encode::Byte>, <Encode::CN>, <Encode::JP>, <Encode::KR>, <Encode::TW>, <Encode::EBCDIC>, <Encode::Symbol> <Encode::MIME::Header>, <Encode::Guess>
References
----------
ECMA European Computer Manufacturers Association <http://www.ecma.ch>
ECMA-035 (eq `ISO-2022`) <http://www.ecma.ch/ecma1/STAND/ECMA-035.HTM>
The specification of ISO-2022 is available from the link above.
IANA Internet Assigned Numbers Authority <http://www.iana.org/>
Assigned Charset Names by IANA <http://www.iana.org/assignments/character-sets>
Most of the `canonical names` in Encode derive from this list so you can directly apply the string you have extracted from MIME header of mails and web pages.
ISO International Organization for Standardization <http://www.iso.ch/>
RFC Request For Comments -- need I say more? <http://www.rfc-editor.org/>, <http://www.ietf.org/rfc.html>, <http://www.faqs.org/rfcs/>
UC Unicode Consortium <http://www.unicode.org/>
Unicode Glossary <http://www.unicode.org/glossary/>
The glossary of this document is based upon this site.
###
Other Notable Sites
czyborra.com <http://czyborra.com/>
Contains a lot of useful information, especially gory details of ISO vs. vendor mappings.
CJK.inf <http://examples.oreilly.com/cjkvinfo/doc/cjk.inf>
Somewhat obsolete (last update in 1996), but still useful. Also try
<ftp://ftp.oreilly.com/pub/examples/nutshell/cjkv/pdf/GB18030_Summary.pdf>
You will find brief info on `EUC-CN`, `GBK` and mostly on `GB 18030`.
Jungshik Shin's Hangul FAQ <http://jshin.net/faq>
And especially its subject 8.
<http://jshin.net/faq/qa8.html>
A comprehensive overview of the Korean (`KS *`) standards.
debian.org: "Introduction to i18n" A brief description for most of the mentioned CJK encodings is contained in <http://www.debian.org/doc/manuals/intro-i18n/ch-codes.en.html>
###
Offline sources
`CJKV Information Processing` by Ken Lunde CJKV Information Processing 1999 O'Reilly & Associates, ISBN : 1-56592-224-7
The modern successor of `CJK.inf`.
Features a comprehensive coverage of CJKV character sets and encodings along with many other issues faced by anyone trying to better support CJKV languages/scripts in all the areas of information processing.
To purchase this book, visit <http://oreilly.com/catalog/9780596514471/> or your favourite bookstore.
| programming_docs |
perl B::Deparse B::Deparse
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OPTIONS](#OPTIONS)
* [USING B::Deparse AS A MODULE](#USING-B::Deparse-AS-A-MODULE)
+ [Synopsis](#Synopsis)
+ [Description](#Description)
+ [new](#new)
+ [ambient\_pragmas](#ambient_pragmas)
+ [coderef2text](#coderef2text)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
B::Deparse - Perl compiler backend to produce perl code
SYNOPSIS
--------
**perl** **-MO=Deparse**[**,-d**][**,-f***FILE*][**,-p**][**,-q**][**,-l**] [**,-s***LETTERS*][**,-x***LEVEL*] *prog.pl*
DESCRIPTION
-----------
B::Deparse is a backend module for the Perl compiler that generates perl source code, based on the internal compiled structure that perl itself creates after parsing a program. The output of B::Deparse won't be exactly the same as the original source, since perl doesn't keep track of comments or whitespace, and there isn't a one-to-one correspondence between perl's syntactical constructions and their compiled form, but it will often be close. When you use the **-p** option, the output also includes parentheses even when they are not required by precedence, which can make it easy to see if perl is parsing your expressions the way you intended.
While B::Deparse goes to some lengths to try to figure out what your original program was doing, some parts of the language can still trip it up; it still fails even on some parts of Perl's own test suite. If you encounter a failure other than the most common ones described in the BUGS section below, you can help contribute to B::Deparse's ongoing development by submitting a bug report with a small example.
OPTIONS
-------
As with all compiler backend options, these must follow directly after the '-MO=Deparse', separated by a comma but not any white space.
**-d**
Output data values (when they appear as constants) using Data::Dumper. Without this option, B::Deparse will use some simple routines of its own for the same purpose. Currently, Data::Dumper is better for some kinds of data (such as complex structures with sharing and self-reference) while the built-in routines are better for others (such as odd floating-point values).
**-f***FILE*
Normally, B::Deparse deparses the main code of a program, and all the subs defined in the same file. To include subs defined in other files, pass the **-f** option with the filename. You can pass the **-f** option several times, to include more than one secondary file. (Most of the time you don't want to use it at all.) You can also use this option to include subs which are defined in the scope of a **#line** directive with two parameters.
**-l**
Add '#line' declarations to the output based on the line and file locations of the original code.
**-p**
Print extra parentheses. Without this option, B::Deparse includes parentheses in its output only when they are needed, based on the structure of your program. With **-p**, it uses parentheses (almost) whenever they would be legal. This can be useful if you are used to LISP, or if you want to see how perl parses your input. If you say
```
if ($var & 0x7f == 65) {print "Gimme an A!"}
print ($which ? $a : $b), "\n";
$name = $ENV{USER} or "Bob";
```
`B::Deparse,-p` will print
```
if (($var & 0)) {
print('Gimme an A!')
};
(print(($which ? $a : $b)), '???');
(($name = $ENV{'USER'}) or '???')
```
which probably isn't what you intended (the `'???'` is a sign that perl optimized away a constant value).
**-P**
Disable prototype checking. With this option, all function calls are deparsed as if no prototype was defined for them. In other words,
```
perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'
```
will print
```
sub foo (\@) {
1;
}
&foo(\@x);
```
making clear how the parameters are actually passed to `foo`.
**-q**
Expand double-quoted strings into the corresponding combinations of concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For instance, print
```
print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
```
as
```
print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
. ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
```
Note that the expanded form represents the way perl handles such constructions internally -- this option actually turns off the reverse translation that B::Deparse usually does. On the other hand, note that `$x = "$y"` is not the same as `$x = $y`: the former makes the value of $y into a string before doing the assignment.
**-s***LETTERS*
Tweak the style of B::Deparse's output. The letters should follow directly after the 's', with no space or punctuation. The following options are available:
**C** Cuddle `elsif`, `else`, and `continue` blocks. For example, print
```
if (...) {
...
} else {
...
}
```
instead of
```
if (...) {
...
}
else {
...
}
```
The default is not to cuddle.
**i***NUMBER*
Indent lines by multiples of *NUMBER* columns. The default is 4 columns.
**T** Use tabs for each 8 columns of indent. The default is to use only spaces. For instance, if the style options are **-si4T**, a line that's indented 3 times will be preceded by one tab and four spaces; if the options were **-si8T**, the same line would be preceded by three tabs.
**v***STRING***.**
Print *STRING* for the value of a constant that can't be determined because it was optimized away (mnemonic: this happens when a constant is used in **v**oid context). The end of the string is marked by a period. The string should be a valid perl expression, generally a constant. Note that unless it's a number, it probably needs to be quoted, and on a command line quotes need to be protected from the shell. Some conventional values include 0, 1, 42, '', 'foo', and 'Useless use of constant omitted' (which may need to be **-sv"'Useless use of constant omitted'."** or something similar depending on your shell). The default is '???'. If you're using B::Deparse on a module or other file that's require'd, you shouldn't use a value that evaluates to false, since the customary true constant at the end of a module will be in void context when the file is compiled as a main program.
**-x***LEVEL*
Expand conventional syntax constructions into equivalent ones that expose their internal operation. *LEVEL* should be a digit, with higher values meaning more expansion. As with **-q**, this actually involves turning off special cases in B::Deparse's normal operations.
If *LEVEL* is at least 3, `for` loops will be translated into equivalent while loops with continue blocks; for instance
```
for ($i = 0; $i < 10; ++$i) {
print $i;
}
```
turns into
```
$i = 0;
while ($i < 10) {
print $i;
} continue {
++$i
}
```
Note that in a few cases this translation can't be perfectly carried back into the source code -- if the loop's initializer declares a my variable, for instance, it won't have the correct scope outside of the loop.
If *LEVEL* is at least 5, `use` declarations will be translated into `BEGIN` blocks containing calls to `require` and `import`; for instance,
```
use strict 'refs';
```
turns into
```
sub BEGIN {
require strict;
do {
'strict'->import('refs')
};
}
```
If *LEVEL* is at least 7, `if` statements will be translated into equivalent expressions using `&&`, `?:` and `do {}`; for instance
```
print 'hi' if $nice;
if ($nice) {
print 'hi';
}
if ($nice) {
print 'hi';
} else {
print 'bye';
}
```
turns into
```
$nice and print 'hi';
$nice and do { print 'hi' };
$nice ? do { print 'hi' } : do { print 'bye' };
```
Long sequences of elsifs will turn into nested ternary operators, which B::Deparse doesn't know how to indent nicely.
USING B::Deparse AS A MODULE
-----------------------------
### Synopsis
```
use B::Deparse;
$deparse = B::Deparse->new("-p", "-sC");
$body = $deparse->coderef2text(\&func);
eval "sub func $body"; # the inverse operation
```
### Description
B::Deparse can also be used on a sub-by-sub basis from other perl programs.
### new
```
$deparse = B::Deparse->new(OPTIONS)
```
Create an object to store the state of a deparsing operation and any options. The options are the same as those that can be given on the command line (see ["OPTIONS"](#OPTIONS)); options that are separated by commas after **-MO=Deparse** should be given as separate strings.
### ambient\_pragmas
```
$deparse->ambient_pragmas(strict => 'all', '$[' => $[);
```
The compilation of a subroutine can be affected by a few compiler directives, **pragmas**. These are:
* use strict;
* use warnings;
* Assigning to the special variable $[
* use integer;
* use bytes;
* use utf8;
* use re;
Ordinarily, if you use B::Deparse on a subroutine which has been compiled in the presence of one or more of these pragmas, the output will include statements to turn on the appropriate directives. So if you then compile the code returned by coderef2text, it will behave the same way as the subroutine which you deparsed.
However, you may know that you intend to use the results in a particular context, where some pragmas are already in scope. In this case, you use the **ambient\_pragmas** method to describe the assumptions you wish to make.
Not all of the options currently have any useful effect. See ["BUGS"](#BUGS) for more details.
The parameters it accepts are:
strict Takes a string, possibly containing several values separated by whitespace. The special values "all" and "none" mean what you'd expect.
```
$deparse->ambient_pragmas(strict => 'subs refs');
```
$[ Takes a number, the value of the array base $[. Obsolete: cannot be non-zero.
bytes utf8 integer If the value is true, then the appropriate pragma is assumed to be in the ambient scope, otherwise not.
re Takes a string, possibly containing a whitespace-separated list of values. The values "all" and "none" are special. It's also permissible to pass an array reference here.
```
$deparser->ambient_pragmas(re => 'eval');
```
warnings Takes a string, possibly containing a whitespace-separated list of values. The values "all" and "none" are special, again. It's also permissible to pass an array reference here.
```
$deparser->ambient_pragmas(warnings => [qw[void io]]);
```
If one of the values is the string "FATAL", then all the warnings in that list will be considered fatal, just as with the **warnings** pragma itself. Should you need to specify that some warnings are fatal, and others are merely enabled, you can pass the **warnings** parameter twice:
```
$deparser->ambient_pragmas(
warnings => 'all',
warnings => [FATAL => qw/void io/],
);
```
See <warnings> for more information about lexical warnings.
hint\_bits warning\_bits These two parameters are used to specify the ambient pragmas in the format used by the special variables $^H and ${^WARNING\_BITS}.
They exist principally so that you can write code like:
```
{ my ($hint_bits, $warning_bits);
BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
$deparser->ambient_pragmas (
hint_bits => $hint_bits,
warning_bits => $warning_bits,
'$[' => 0 + $[
); }
```
which specifies that the ambient pragmas are exactly those which are in scope at the point of calling.
%^H This parameter is used to specify the ambient pragmas which are stored in the special hash %^H.
### coderef2text
```
$body = $deparse->coderef2text(\&func)
$body = $deparse->coderef2text(sub ($$) { ... })
```
Return source code for the body of a subroutine (a block, optionally preceded by a prototype in parens), given a reference to the sub. Because a subroutine can have no names, or more than one name, this method doesn't return a complete subroutine definition -- if you want to eval the result, you should prepend "sub subname ", or "sub " for an anonymous function constructor. Unless the sub was defined in the main:: package, the code will include a package declaration.
BUGS
----
* The only pragmas to be completely supported are: `use warnings`, `use strict`, `use bytes`, `use integer` and `use feature`.
Excepting those listed above, we're currently unable to guarantee that B::Deparse will produce a pragma at the correct point in the program. (Specifically, pragmas at the beginning of a block often appear right before the start of the block instead.) Since the effects of pragmas are often lexically scoped, this can mean that the pragma holds sway over a different portion of the program than in the input file.
* In fact, the above is a specific instance of a more general problem: we can't guarantee to produce BEGIN blocks or `use` declarations in exactly the right place. So if you use a module which affects compilation (such as by over-riding keywords, overloading constants or whatever) then the output code might not work as intended.
* Some constants don't print correctly either with or without **-d**. For instance, neither B::Deparse nor Data::Dumper know how to print dual-valued scalars correctly, as in:
```
use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;
use constant H => { "#" => 1 }; H->{"#"};
```
* An input file that uses source filtering probably won't be deparsed into runnable code, because it will still include the **use** declaration for the source filtering module, even though the code that is produced is already ordinary Perl which shouldn't be filtered again.
* Optimized-away statements are rendered as '???'. This includes statements that have a compile-time side-effect, such as the obscure
```
my $x if 0;
```
which is not, consequently, deparsed correctly.
```
foreach my $i (@_) { 0 }
=>
foreach my $i (@_) { '???' }
```
* Lexical (my) variables declared in scopes external to a subroutine appear in coderef2text output text as package variables. This is a tricky problem, as perl has no native facility for referring to a lexical variable defined within a different scope, although [PadWalker](padwalker) is a good start.
See also <Data::Dump::Streamer>, which combines B::Deparse and [PadWalker](padwalker) to serialize closures properly.
* There are probably many more bugs on non-ASCII platforms (EBCDIC).
AUTHOR
------
Stephen McCamant <[email protected]>, based on an earlier version by Malcolm Beattie <[email protected]>, with contributions from Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell, Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael Garcia-Suarez.
perl Pod::Simple Pod::Simple
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [MAIN METHODS](#MAIN-METHODS)
* [SECONDARY METHODS](#SECONDARY-METHODS)
* [TERTIARY METHODS](#TERTIARY-METHODS)
* [ENCODING](#ENCODING)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple - framework for parsing Pod
SYNOPSIS
--------
```
TODO
```
DESCRIPTION
-----------
Pod::Simple is a Perl library for parsing text in the Pod ("plain old documentation") markup language that is typically used for writing documentation for Perl and for Perl modules. The Pod format is explained in <perlpod>; the most common formatter is called `perldoc`.
Be sure to read ["ENCODING"](#ENCODING) if your Pod contains non-ASCII characters.
Pod formatters can use Pod::Simple to parse Pod documents and render them into plain text, HTML, or any number of other formats. Typically, such formatters will be subclasses of Pod::Simple, and so they will inherit its methods, like `parse_file`. But note that Pod::Simple doesn't understand and properly parse Perl itself, so if you have a file which contains a Perl program that has a multi-line quoted string which has lines that look like pod, Pod::Simple will treat them as pod. This can be avoided if the file makes these into indented here documents instead.
If you're reading this document just because you have a Pod-processing subclass that you want to use, this document (plus the documentation for the subclass) is probably all you need to read.
If you're reading this document because you want to write a formatter subclass, continue reading it and then read <Pod::Simple::Subclassing>, and then possibly even read <perlpodspec> (some of which is for parser-writers, but much of which is notes to formatter-writers).
MAIN METHODS
-------------
`$parser = *SomeClass*->new();`
This returns a new parser object, where *`SomeClass`* is a subclass of Pod::Simple.
`$parser->output_fh( *OUT );`
This sets the filehandle that `$parser`'s output will be written to. You can pass `*STDOUT` or `*STDERR`, otherwise you should probably do something like this:
```
my $outfile = "output.txt";
open TXTOUT, ">$outfile" or die "Can't write to $outfile: $!";
$parser->output_fh(*TXTOUT);
```
...before you call one of the `$parser->parse_*whatever*` methods.
`$parser->output_string( \$somestring );`
This sets the string that `$parser`'s output will be sent to, instead of any filehandle.
`$parser->parse_file( *$some\_filename* );`
`$parser->parse_file( *INPUT_FH );`
This reads the Pod content of the file (or filehandle) that you specify, and processes it with that `$parser` object, according to however `$parser`'s class works, and according to whatever parser options you have set up for this `$parser` object.
`$parser->parse_string_document( *$all\_content* );`
This works just like `parse_file` except that it reads the Pod content not from a file, but from a string that you have already in memory.
`$parser->parse_lines( *...@lines...*, undef );`
This processes the lines in `@lines` (where each list item must be a defined value, and must contain exactly one line of content -- so no items like `"foo\nbar"` are allowed). The final `undef` is used to indicate the end of document being parsed.
The other `parser_*whatever*` methods are meant to be called only once per `$parser` object; but `parse_lines` can be called as many times per `$parser` object as you want, as long as the last call (and only the last call) ends with an `undef` value.
`$parser->content_seen`
This returns true only if there has been any real content seen for this document. Returns false in cases where the document contains content, but does not make use of any Pod markup.
`*SomeClass*->filter( *$filename* );`
`*SomeClass*->filter( *\*INPUT\_FH* );`
`*SomeClass*->filter( *\$document\_content* );`
This is a shortcut method for creating a new parser object, setting the output handle to STDOUT, and then processing the specified file (or filehandle, or in-memory document). This is handy for one-liners like this:
```
perl -MPod::Simple::Text -e "Pod::Simple::Text->filter('thingy.pod')"
```
SECONDARY METHODS
------------------
Some of these methods might be of interest to general users, as well as of interest to formatter-writers.
Note that the general pattern here is that the accessor-methods read the attribute's value with `$value = $parser->*attribute*` and set the attribute's value with `$parser->*attribute*(*newvalue*)`. For each accessor, I typically only mention one syntax or another, based on which I think you are actually most likely to use.
`$parser->parse_characters( *SOMEVALUE* )`
The Pod parser normally expects to read octets and to convert those octets to characters based on the `=encoding` declaration in the Pod source. Set this option to a true value to indicate that the Pod source is already a Perl character stream. This tells the parser to ignore any `=encoding` command and to skip all the code paths involving decoding octets.
`$parser->no_whining( *SOMEVALUE* )`
If you set this attribute to a true value, you will suppress the parser's complaints about irregularities in the Pod coding. By default, this attribute's value is false, meaning that irregularities will be reported.
Note that turning this attribute to true won't suppress one or two kinds of complaints about rarely occurring unrecoverable errors.
`$parser->no_errata_section( *SOMEVALUE* )`
If you set this attribute to a true value, you will stop the parser from generating a "POD ERRORS" section at the end of the document. By default, this attribute's value is false, meaning that an errata section will be generated, as necessary.
`$parser->complain_stderr( *SOMEVALUE* )`
If you set this attribute to a true value, it will send reports of parsing errors to STDERR. By default, this attribute's value is false, meaning that no output is sent to STDERR.
Setting `complain_stderr` also sets `no_errata_section`.
`$parser->source_filename`
This returns the filename that this parser object was set to read from.
`$parser->doc_has_started`
This returns true if `$parser` has read from a source, and has seen Pod content in it.
`$parser->source_dead`
This returns true if `$parser` has read from a source, and come to the end of that source.
`$parser->strip_verbatim_indent( *SOMEVALUE* )`
The perlpod spec for a Verbatim paragraph is "It should be reproduced exactly...", which means that the whitespace you've used to indent your verbatim blocks will be preserved in the output. This can be annoying for outputs such as HTML, where that whitespace will remain in front of every line. It's an unfortunate case where syntax is turned into semantics.
If the POD you're parsing adheres to a consistent indentation policy, you can have such indentation stripped from the beginning of every line of your verbatim blocks. This method tells Pod::Simple what to strip. For two-space indents, you'd use:
```
$parser->strip_verbatim_indent(' ');
```
For tab indents, you'd use a tab character:
```
$parser->strip_verbatim_indent("\t");
```
If the POD is inconsistent about the indentation of verbatim blocks, but you have figured out a heuristic to determine how much a particular verbatim block is indented, you can pass a code reference instead. The code reference will be executed with one argument, an array reference of all the lines in the verbatim block, and should return the value to be stripped from each line. For example, if you decide that you're fine to use the first line of the verbatim block to set the standard for indentation of the rest of the block, you can look at the first line and return the appropriate value, like so:
```
$new->strip_verbatim_indent(sub {
my $lines = shift;
(my $indent = $lines->[0]) =~ s/\S.*//;
return $indent;
});
```
If you'd rather treat each line individually, you can do that, too, by just transforming them in-place in the code reference and returning `undef`. Say that you don't want *any* lines indented. You can do something like this:
```
$new->strip_verbatim_indent(sub {
my $lines = shift;
sub { s/^\s+// for @{ $lines },
return undef;
});
```
`$parser->expand_verbatim_tabs( *n* )`
Default: 8
If after any stripping of indentation in verbatim blocks, there remain tabs, this method call indicates what to do with them. `0` means leave them as tabs, any other number indicates that each tab is to be translated so as to have tab stops every `n` columns.
This is independent of other methods (except that it operates after any verbatim input stripping is done).
Like the other methods, the input parameter is not checked for validity. `undef` or containing non-digits has the same effect as 8.
TERTIARY METHODS
-----------------
`$parser->abandon_output_fh()`
Cancel output to the file handle. Any POD read by the `$parser` is not effected.
`$parser->abandon_output_string()`
Cancel output to the output string. Any POD read by the `$parser` is not effected.
`$parser->accept_code( @codes )`
Alias for <accept_codes>.
`$parser->accept_codes( @codes )`
Allows `$parser` to accept a list of ["Formatting Codes" in perlpod](perlpod#Formatting-Codes). This can be used to implement user-defined codes.
`$parser->accept_directive_as_data( @directives )`
Allows `$parser` to accept a list of directives for data paragraphs. A directive is the label of a ["Command Paragraph" in perlpod](perlpod#Command-Paragraph). A data paragraph is one delimited by `=begin/=for/=end` directives. This can be used to implement user-defined directives.
`$parser->accept_directive_as_processed( @directives )`
Allows `$parser` to accept a list of directives for processed paragraphs. A directive is the label of a ["Command Paragraph" in perlpod](perlpod#Command-Paragraph). A processed paragraph is also known as ["Ordinary Paragraph" in perlpod](perlpod#Ordinary-Paragraph). This can be used to implement user-defined directives.
`$parser->accept_directive_as_verbatim( @directives )`
Allows `$parser` to accept a list of directives for ["Verbatim Paragraph" in perlpod](perlpod#Verbatim-Paragraph). A directive is the label of a ["Command Paragraph" in perlpod](perlpod#Command-Paragraph). This can be used to implement user-defined directives.
`$parser->accept_target( @targets )`
Alias for <accept_targets>.
`$parser->accept_target_as_text( @targets )`
Alias for <accept_targets_as_text>.
`$parser->accept_targets( @targets )`
Accepts targets for `=begin/=for/=end` sections of the POD.
`$parser->accept_targets_as_text( @targets )`
Accepts targets for `=begin/=for/=end` sections that should be parsed as POD. For details, see ["About Data Paragraphs" in perlpodspec](perlpodspec#About-Data-Paragraphs).
`$parser->any_errata_seen()`
Used to check if any errata was seen.
*Example:*
```
die "too many errors\n" if $parser->any_errata_seen();
```
`$parser->errata_seen()`
Returns a hash reference of all errata seen, both whines and screams. The hash reference's keys are the line number and the value is an array reference of the errors for that line.
*Example:*
```
if ( $parser->any_errata_seen() ) {
$logger->log( $parser->errata_seen() );
}
```
`$parser->detected_encoding()`
Return the encoding corresponding to `=encoding`, but only if the encoding was recognized and handled.
`$parser->encoding()`
Return encoding of the document, even if the encoding is not correctly handled.
`$parser->parse_from_file( $source, $to )`
Parses from `$source` file to `$to` file. Similar to ["parse\_from\_file" in Pod::Parser](Pod::Parser#parse_from_file).
`$parser->scream( @error_messages )`
Log an error that can't be ignored.
`$parser->unaccept_code( @codes )`
Alias for <unaccept_codes>.
`$parser->unaccept_codes( @codes )`
Removes `@codes` as valid codes for the parse.
`$parser->unaccept_directive( @directives )`
Alias for <unaccept_directives>.
`$parser->unaccept_directives( @directives )`
Removes `@directives` as valid directives for the parse.
`$parser->unaccept_target( @targets )`
Alias for <unaccept_targets>.
`$parser->unaccept_targets( @targets )`
Removes `@targets` as valid targets for the parse.
`$parser->version_report()`
Returns a string describing the version.
`$parser->whine( @error_messages )`
Log an error unless `$parser->no_whining( TRUE );`.
ENCODING
--------
The Pod::Simple parser expects to read **octets**. The parser will decode the octets into Perl's internal character string representation using the value of the `=encoding` declaration in the POD source.
If the POD source does not include an `=encoding` declaration, the parser will attempt to guess the encoding (selecting one of UTF-8 or CP 1252) by examining the first non-ASCII bytes and applying the heuristic described in <perlpodspec>. (If the POD source contains only ASCII bytes, the encoding is assumed to be ASCII.)
If you set the `parse_characters` option to a true value the parser will expect characters rather than octets; will ignore any `=encoding`; and will make no attempt to decode the input.
SEE ALSO
---------
<Pod::Simple::Subclassing>
<perlpod>
<perlpodspec>
<Pod::Escapes>
<perldoc>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Please use <https://github.com/perl-pod/pod-simple/issues/new> to file a bug report.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
* Karl Williamson `[email protected]`
Documentation has been contributed by:
* Gabor Szabo `[email protected]`
* Shawn H Corey `SHCOREY at cpan.org`
| programming_docs |
perl TAP::Formatter::File::Session TAP::Formatter::File::Session
=============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [result](#result)
+ [close\_test](#close_test)
NAME
----
TAP::Formatter::File::Session - Harness output delegate for file output
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides file orientated output formatting for <TAP::Harness>. It is particularly important when running with parallel tests, as it ensures that test results are not interleaved, even when run verbosely.
METHODS
-------
### result
Stores results for later output, all together.
### close\_test
When the test file finishes, outputs the summary, together.
perl Pod::Simple::DumpAsText Pod::Simple::DumpAsText
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::DumpAsText -- dump Pod-parsing events as text
SYNOPSIS
--------
```
perl -MPod::Simple::DumpAsText -e \
"exit Pod::Simple::DumpAsText->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
This class is for dumping, as text, the events gotten from parsing a Pod document. This class is of interest to people writing Pod formatters based on Pod::Simple. It is useful for seeing exactly what events you get out of some Pod that you feed in.
This is a subclass of <Pod::Simple> and inherits all its methods.
SEE ALSO
---------
<Pod::Simple::DumpAsXML>
<Pod::Simple>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl constant constant
========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [NOTES](#NOTES)
+ [List constants](#List-constants)
+ [Defining multiple constants at once](#Defining-multiple-constants-at-once)
+ [Magic constants](#Magic-constants)
* [TECHNICAL NOTES](#TECHNICAL-NOTES)
* [CAVEATS](#CAVEATS)
* [SEE ALSO](#SEE-ALSO)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT & LICENSE](#COPYRIGHT-&-LICENSE)
NAME
----
constant - Perl pragma to declare constants
SYNOPSIS
--------
```
use constant PI => 4 * atan2(1, 1);
use constant DEBUG => 0;
print "Pi equals ", PI, "...\n" if DEBUG;
use constant {
SEC => 0,
MIN => 1,
HOUR => 2,
MDAY => 3,
MON => 4,
YEAR => 5,
WDAY => 6,
YDAY => 7,
ISDST => 8,
};
use constant WEEKDAYS => qw(
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
);
print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";
```
DESCRIPTION
-----------
This pragma allows you to declare constants at compile-time.
When you declare a constant such as `PI` using the method shown above, each machine your script runs upon can have as many digits of accuracy as it can use. Also, your program will be easier to read, more likely to be maintained (and maintained correctly), and far less likely to send a space probe to the wrong planet because nobody noticed the one equation in which you wrote `3.14195`.
When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an `if (CONSTANT)` block will be optimized away if the constant is false.
NOTES
-----
As with all `use` directives, defining a constant happens at compile time. Thus, it's probably not correct to put a constant declaration inside of a conditional statement (like `if ($foo) { use constant ... }`).
Constants defined using this module cannot be interpolated into strings like variables. However, concatenation works just fine:
```
print "Pi equals PI...\n"; # WRONG: does not expand "PI"
print "Pi equals ".PI."...\n"; # right
```
Even though a reference may be declared as a constant, the reference may point to data which may be changed, as this code shows.
```
use constant ARRAY => [ 1,2,3,4 ];
print ARRAY->[1];
ARRAY->[1] = " be changed";
print ARRAY->[1];
```
Constants belong to the package they are defined in. To refer to a constant defined in another package, specify the full package name, as in `Some::Package::CONSTANT`. Constants may be exported by modules, and may also be called as either class or instance methods, that is, as `Some::Package->CONSTANT` or as `$obj->CONSTANT` where `$obj` is an instance of `Some::Package`. Subclasses may define their own constants to override those in their base class.
As of version 1.32 of this module, constants can be defined in packages other than the caller, by including the package name in the name of the constant:
```
use constant "OtherPackage::FWIBBLE" => 7865;
constant->import("Other::FWOBBLE",$value); # dynamically at run time
```
The use of all caps for constant names is merely a convention, although it is recommended in order to make constants stand out and to help avoid collisions with other barewords, keywords, and subroutine names. Constant names must begin with a letter or underscore. Names beginning with a double underscore are reserved. Some poor choices for names will generate warnings, if warnings are enabled at compile time.
###
List constants
Constants may be lists of more (or less) than one value. A constant with no values evaluates to `undef` in scalar context. Note that constants with more than one value do *not* return their last value in scalar context as one might expect. They currently return the number of values, but **this may change in the future**. Do not use constants with multiple values in scalar context.
**NOTE:** This implies that the expression defining the value of a constant is evaluated in list context. This may produce surprises:
```
use constant TIMESTAMP => localtime; # WRONG!
use constant TIMESTAMP => scalar localtime; # right
```
The first line above defines `TIMESTAMP` as a 9-element list, as returned by `localtime()` in list context. To set it to the string returned by `localtime()` in scalar context, an explicit `scalar` keyword is required.
List constants are lists, not arrays. To index or slice them, they must be placed in parentheses.
```
my @workdays = WEEKDAYS[1 .. 5]; # WRONG!
my @workdays = (WEEKDAYS)[1 .. 5]; # right
```
###
Defining multiple constants at once
Instead of writing multiple `use constant` statements, you may define multiple constants in a single statement by giving, instead of the constant name, a reference to a hash where the keys are the names of the constants to be defined. Obviously, all constants defined using this method must have a single value.
```
use constant {
FOO => "A single value",
BAR => "This", "won't", "work!", # Error!
};
```
This is a fundamental limitation of the way hashes are constructed in Perl. The error messages produced when this happens will often be quite cryptic -- in the worst case there may be none at all, and you'll only later find that something is broken.
When defining multiple constants, you cannot use the values of other constants defined in the same declaration. This is because the calling package doesn't know about any constant within that group until *after* the `use` statement is finished.
```
use constant {
BITMASK => 0xAFBAEBA8,
NEGMASK => ~BITMASK, # Error!
};
```
###
Magic constants
Magical values and references can be made into constants at compile time, allowing for way cool stuff like this. (These error numbers aren't totally portable, alas.)
```
use constant E2BIG => ($! = 7);
print E2BIG, "\n"; # something like "Arg list too long"
print 0+E2BIG, "\n"; # "7"
```
You can't produce a tied constant by giving a tied scalar as the value. References to tied variables, however, can be used as constants without any problems.
TECHNICAL NOTES
----------------
In the current implementation, scalar constants are actually inlinable subroutines. As of version 5.004 of Perl, the appropriate scalar constant is inserted directly in place of some subroutine calls, thereby saving the overhead of a subroutine call. See ["Constant Functions" in perlsub](perlsub#Constant-Functions) for details about how and when this happens.
In the rare case in which you need to discover at run time whether a particular constant has been declared via this module, you may use this function to examine the hash `%constant::declared`. If the given constant name does not include a package name, the current package is used.
```
sub declared ($) {
use constant 1.01; # don't omit this!
my $name = shift;
$name =~ s/^::/main::/;
my $pkg = caller;
my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
$constant::declared{$full_name};
}
```
CAVEATS
-------
List constants are not inlined unless you are using Perl v5.20 or higher. In v5.20 or higher, they are still not read-only, but that may change in future versions.
It is not possible to have a subroutine or a keyword with the same name as a constant in the same package. This is probably a Good Thing.
A constant with a name in the list `STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG` is not allowed anywhere but in package `main::`, for technical reasons.
Unlike constants in some languages, these cannot be overridden on the command line or via environment variables.
You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example, you can't say `$hash{CONSTANT}` because `CONSTANT` will be interpreted as a string. Use `$hash{CONSTANT()}` or `$hash{+CONSTANT}` to prevent the bareword quoting mechanism from kicking in. Similarly, since the `=>` operator quotes a bareword immediately to its left, you have to say `CONSTANT() => 'value'` (or simply use a comma in place of the big arrow) instead of `CONSTANT => 'value'`.
SEE ALSO
---------
[Readonly](readonly) - Facility for creating read-only scalars, arrays, hashes.
<Attribute::Constant> - Make read-only variables via attribute
<Scalar::Readonly> - Perl extension to the `SvREADONLY` scalar flag
<Hash::Util> - A selection of general-utility hash subroutines (mostly to lock/unlock keys and values)
BUGS
----
Please report any bugs or feature requests via the perlbug(1) utility.
AUTHORS
-------
Tom Phoenix, <*[email protected]*>, with help from many other folks.
Multiple constant declarations at once added by Casey West, <*[email protected]*>.
Documentation mostly rewritten by Ilmari Karonen, <*[email protected]*>.
This program is maintained by the Perl 5 Porters. The CPAN distribution is maintained by Sébastien Aperghis-Tramoni <*[email protected]*>.
COPYRIGHT & LICENSE
--------------------
Copyright (C) 1997, 1999 Tom Phoenix
This module is free software; you can redistribute it or modify it under the same terms as Perl itself.
perl ExtUtils::Install ExtUtils::Install
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [Functions](#Functions)
+ [install](#install)
+ [install\_default](#install_default)
+ [uninstall](#uninstall)
+ [pm\_to\_blib](#pm_to_blib)
* [ENVIRONMENT](#ENVIRONMENT)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
NAME
----
ExtUtils::Install - install files from here to there
SYNOPSIS
--------
```
use ExtUtils::Install;
install({ 'blib/lib' => 'some/install/dir' } );
uninstall($packlist);
pm_to_blib({ 'lib/Foo/Bar.pm' => 'blib/lib/Foo/Bar.pm' });
```
VERSION
-------
2.20
DESCRIPTION
-----------
Handles the installing and uninstalling of perl modules, scripts, man pages, etc...
Both install() and uninstall() are specific to the way ExtUtils::MakeMaker handles the installation and deinstallation of perl modules. They are not designed as general purpose tools.
On some operating systems such as Win32 installation may not be possible until after a reboot has occurred. This can have varying consequences: removing an old DLL does not impact programs using the new one, but if a new DLL cannot be installed properly until reboot then anything depending on it must wait. The package variable
```
$ExtUtils::Install::MUST_REBOOT
```
is used to store this status.
If this variable is true then such an operation has occurred and anything depending on this module cannot proceed until a reboot has occurred.
If this value is defined but false then such an operation has occurred, but should not impact later operations.
Functions
---------
### install
```
# deprecated forms
install(\%from_to);
install(\%from_to, $verbose, $dry_run, $uninstall_shadows,
$skip, $always_copy, \%result);
# recommended form as of 1.47
install([
from_to => \%from_to,
verbose => 1,
dry_run => 0,
uninstall_shadows => 1,
skip => undef,
always_copy => 1,
result => \%install_results,
]);
```
Copies each directory tree of %from\_to to its corresponding value preserving timestamps and permissions.
There are two keys with a special meaning in the hash: "read" and "write". These contain packlist files. After the copying is done, install() will write the list of target files to $from\_to{write}. If $from\_to{read} is given the contents of this file will be merged into the written file. The read and the written file may be identical, but on AFS it is quite likely that people are installing to a different directory than the one where the files later appear.
If $verbose is true, will print out each file removed. Default is false. This is "make install VERBINST=1". $verbose values going up to 5 show increasingly more diagnostics output.
If $dry\_run is true it will only print what it was going to do without actually doing it. Default is false.
If $uninstall\_shadows is true any differing versions throughout @INC will be uninstalled. This is "make install UNINST=1"
As of 1.37\_02 install() supports the use of a list of patterns to filter out files that shouldn't be installed. If $skip is omitted or undefined then install will try to read the list from INSTALL.SKIP in the CWD. This file is a list of regular expressions and is just like the MANIFEST.SKIP file used by <ExtUtils::Manifest>.
A default site INSTALL.SKIP may be provided by setting then environment variable EU\_INSTALL\_SITE\_SKIPFILE, this will only be used when there isn't a distribution specific INSTALL.SKIP. If the environment variable EU\_INSTALL\_IGNORE\_SKIP is true then no install file filtering will be performed.
If $skip is undefined then the skip file will be autodetected and used if it is found. If $skip is a reference to an array then it is assumed the array contains the list of patterns, if $skip is a true non reference it is assumed to be the filename holding the list of patterns, any other value of $skip is taken to mean that no install filtering should occur.
**Changes As of Version 1.47**
As of version 1.47 the following additions were made to the install interface. Note that the new argument style and use of the %result hash is recommended.
The $always\_copy parameter which when true causes files to be updated regardless as to whether they have changed, if it is defined but false then copies are made only if the files have changed, if it is undefined then the value of the environment variable EU\_INSTALL\_ALWAYS\_COPY is used as default.
The %result hash will be populated with the various keys/subhashes reflecting the install. Currently these keys and their structure are:
```
install => { $target => $source },
install_fail => { $target => $source },
install_unchanged => { $target => $source },
install_filtered => { $source => $pattern },
uninstall => { $uninstalled => $source },
uninstall_fail => { $uninstalled => $source },
```
where `$source` is the filespec of the file being installed. `$target` is where it is being installed to, and `$uninstalled` is any shadow file that is in `@INC` or `$ENV{PERL5LIB}` or other standard locations, and `$pattern` is the pattern that caused a source file to be skipped. In future more keys will be added, such as to show created directories, however this requires changes in other modules and must therefore wait.
These keys will be populated before any exceptions are thrown should there be an error.
Note that all updates of the %result are additive, the hash will not be cleared before use, thus allowing status results of many installs to be easily aggregated.
**NEW ARGUMENT STYLE**
If there is only one argument and it is a reference to an array then the array is assumed to contain a list of key-value pairs specifying the options. In this case the option "from\_to" is mandatory. This style means that you do not have to supply a cryptic list of arguments and can use a self documenting argument list that is easier to understand.
This is now the recommended interface to install().
**RETURN**
If all actions were successful install will return a hashref of the results as described above for the $result parameter. If any action is a failure then install will die, therefore it is recommended to pass in the $result parameter instead of using the return value. If the result parameter is provided then the returned hashref will be the passed in hashref.
### install\_default
*DISCOURAGED*
```
install_default();
install_default($fullext);
```
Calls install() with arguments to copy a module from blib/ to the default site installation location.
$fullext is the name of the module converted to a directory (ie. Foo::Bar would be Foo/Bar). If $fullext is not specified, it will attempt to read it from @ARGV.
This is primarily useful for install scripts.
**NOTE** This function is not really useful because of the hard-coded install location with no way to control site vs core vs vendor directories and the strange way in which the module name is given. Consider its use discouraged.
### uninstall
```
uninstall($packlist_file);
uninstall($packlist_file, $verbose, $dont_execute);
```
Removes the files listed in a $packlist\_file.
If $verbose is true, will print out each file removed. Default is false.
If $dont\_execute is true it will only print what it was going to do without actually doing it. Default is false.
### pm\_to\_blib
```
pm_to_blib(\%from_to);
pm_to_blib(\%from_to, $autosplit_dir);
pm_to_blib(\%from_to, $autosplit_dir, $filter_cmd);
```
Copies each key of %from\_to to its corresponding value efficiently. If an $autosplit\_dir is provided, all .pm files will be autosplit into it. Any destination directories are created.
$filter\_cmd is an optional shell command to run each .pm file through prior to splitting and copying. Input is the contents of the module, output the new module contents.
You can have an environment variable PERL\_INSTALL\_ROOT set which will be prepended as a directory to each installed file (and directory).
By default verbose output is generated, setting the PERL\_INSTALL\_QUIET environment variable will silence this output.
ENVIRONMENT
-----------
**PERL\_INSTALL\_ROOT** Will be prepended to each install path.
**EU\_INSTALL\_IGNORE\_SKIP** Will prevent the automatic use of INSTALL.SKIP as the install skip file.
**EU\_INSTALL\_SITE\_SKIPFILE** If there is no INSTALL.SKIP file in the make directory then this value can be used to provide a default.
**EU\_INSTALL\_ALWAYS\_COPY** If this environment variable is true then normal install processes will always overwrite older identical files during the install process.
Note that the alias EU\_ALWAYS\_COPY will be supported if EU\_INSTALL\_ALWAYS\_COPY is not defined until at least the 1.50 release. Please ensure you use the correct EU\_INSTALL\_ALWAYS\_COPY.
AUTHOR
------
Original author lost in the mists of time. Probably the same as Makemaker.
Production release currently maintained by demerphq `yves at cpan.org`, extensive changes by Michael G. Schwern.
Send bug reports via http://rt.cpan.org/. Please send your generated Makefile along with your report.
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See <http://www.perl.com/perl/misc/Artistic.html>
| programming_docs |
perl Pod::Usage Pod::Usage
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [ARGUMENTS](#ARGUMENTS)
+ [Formatting base class](#Formatting-base-class)
+ [Pass-through options](#Pass-through-options)
* [DESCRIPTION](#DESCRIPTION)
+ [Scripts](#Scripts)
* [EXAMPLES](#EXAMPLES)
+ [Recommended Use](#Recommended-Use)
* [CAVEATS](#CAVEATS)
* [SUPPORT](#SUPPORT)
* [AUTHOR](#AUTHOR)
* [LICENSE](#LICENSE)
* [ACKNOWLEDGMENTS](#ACKNOWLEDGMENTS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Usage - extracts POD documentation and shows usage information
SYNOPSIS
--------
```
use Pod::Usage;
my $message_text = "This text precedes the usage message.";
my $exit_status = 2; ## The exit status to use
my $verbose_level = 0; ## The verbose level to use
my $filehandle = \*STDERR; ## The filehandle to write to
pod2usage($message_text);
pod2usage($exit_status);
pod2usage( { -message => $message_text ,
-exitval => $exit_status ,
-verbose => $verbose_level,
-output => $filehandle } );
pod2usage( -msg => $message_text ,
-exitval => $exit_status ,
-verbose => $verbose_level,
-output => $filehandle );
pod2usage( -verbose => 2,
-noperldoc => 1 );
pod2usage( -verbose => 2,
-perlcmd => $path_to_perl,
-perldoc => $path_to_perldoc,
-perldocopt => $perldoc_options );
```
ARGUMENTS
---------
**pod2usage** should be given either a single argument, or a list of arguments corresponding to an associative array (a "hash"). When a single argument is given, it should correspond to exactly one of the following:
* A string containing the text of a message to print *before* printing the usage message
* A numeric value corresponding to the desired exit status
* A reference to a hash
If more than one argument is given then the entire argument list is assumed to be a hash. If a hash is supplied (either as a reference or as a list) it should contain one or more elements with the following keys:
`-message` *string*
`-msg` *string*
The text of a message to print immediately prior to printing the program's usage message.
`-exitval` *value*
The desired exit status to pass to the **exit()** function. This should be an integer, or else the string `NOEXIT` to indicate that control should simply be returned without terminating the invoking process.
`-verbose` *value*
The desired level of "verboseness" to use when printing the usage message. If the value is 0, then only the "SYNOPSIS" and/or "USAGE" sections of the pod documentation are printed. If the value is 1, then the "SYNOPSIS" and/or "USAGE" sections, along with any section entitled "OPTIONS", "ARGUMENTS", or "OPTIONS AND ARGUMENTS" is printed. If the corresponding value is 2 or more then the entire manpage is printed, using <perldoc> if available; otherwise <Pod::Text> is used for the formatting. For better readability, the all-capital headings are downcased, e.g. `SYNOPSIS` => `Synopsis`.
The special verbosity level 99 requires to also specify the -sections parameter; then these sections are extracted and printed.
`-sections` *spec*
There are two ways to specify the selection. Either a string (scalar) representing a selection regexp for sections to be printed when -verbose is set to 99, e.g.
```
"NAME|SYNOPSIS|DESCRIPTION|VERSION"
```
With the above regexp all content following (and including) any of the given `=head1` headings will be shown. It is possible to restrict the output to particular subsections only, e.g.:
```
"DESCRIPTION/Algorithm"
```
This will output only the `=head2 Algorithm` heading and content within the `=head1 DESCRIPTION` section. The regexp binding is stronger than the section separator, such that e.g.:
```
"DESCRIPTION|OPTIONS|ENVIRONMENT/Caveats"
```
will print any `=head2 Caveats` section (only) within any of the three `=head1` sections.
Alternatively, an array reference of section specifications can be used:
```
pod2usage(-verbose => 99, -sections => [
qw(DESCRIPTION DESCRIPTION/Introduction) ] );
```
This will print only the content of `=head1 DESCRIPTION` and the `=head2 Introduction` sections, but no other `=head2`, and no other `=head1` either.
`-output` *handle*
A reference to a filehandle, or the pathname of a file to which the usage message should be written. The default is `\*STDERR` unless the exit value is less than 2 (in which case the default is `\*STDOUT`).
`-input` *handle*
A reference to a filehandle, or the pathname of a file from which the invoking script's pod documentation should be read. It defaults to the file indicated by `$0` (`$PROGRAM_NAME` for users of *English.pm*).
If you are calling **pod2usage()** from a module and want to display that module's POD, you can use this:
```
use Pod::Find qw(pod_where);
pod2usage( -input => pod_where({-inc => 1}, __PACKAGE__) );
```
`-pathlist` *string*
A list of directory paths. If the input file does not exist, then it will be searched for in the given directory list (in the order the directories appear in the list). It defaults to the list of directories implied by `$ENV{PATH}`. The list may be specified either by a reference to an array, or by a string of directory paths which use the same path separator as `$ENV{PATH}` on your system (e.g., `:` for Unix, `;` for MSWin32 and DOS).
`-noperldoc`
By default, Pod::Usage will call <perldoc> when -verbose >= 2 is specified. This does not work well e.g. if the script was packed with [PAR](par). This option suppresses the external call to <perldoc> and uses the simple text formatter (<Pod::Text>) to output the POD.
`-perlcmd`
By default, Pod::Usage will call <perldoc> when -verbose >= 2 is specified. In case of special or unusual Perl installations, this option may be used to supply the path to a <perl> executable which should run <perldoc>.
`-perldoc` *path-to-perldoc*
By default, Pod::Usage will call <perldoc> when -verbose >= 2 is specified. In case <perldoc> is not installed where the <perl> interpreter thinks it is (see [Config](config)), the -perldoc option may be used to supply the correct path to <perldoc>.
`-perldocopt` *string*
By default, Pod::Usage will call <perldoc> when -verbose >= 2 is specified. This option may be used to supply options to <perldoc>. The string may contain several, space-separated options.
###
Formatting base class
The default text formatter is <Pod::Text>. The base class for Pod::Usage can be defined by pre-setting `$Pod::Usage::Formatter` *before* loading Pod::Usage, e.g.:
```
BEGIN { $Pod::Usage::Formatter = 'Pod::Text::Termcap'; }
use Pod::Usage qw(pod2usage);
```
Pod::Usage uses <Pod::Simple>'s \_handle\_element\_end() method to implement the section selection, and in case of verbosity < 2 it down-cases the all-caps headings to first capital letter and rest lowercase, and adds a colon/newline at the end of the headings, for better readability. Same for verbosity = 99.
###
Pass-through options
The following options are passed through to the underlying text formatter. See the manual pages of these modules for more information.
```
alt code indent loose margin quotes sentence stderr utf8 width
```
DESCRIPTION
-----------
**pod2usage** will print a usage message for the invoking script (using its embedded pod documentation) and then exit the script with the desired exit status. The usage message printed may have any one of three levels of "verboseness": If the verbose level is 0, then only a synopsis is printed. If the verbose level is 1, then the synopsis is printed along with a description (if present) of the command line options and arguments. If the verbose level is 2, then the entire manual page is printed.
Unless they are explicitly specified, the default values for the exit status, verbose level, and output stream to use are determined as follows:
* If neither the exit status nor the verbose level is specified, then the default is to use an exit status of 2 with a verbose level of 0.
* If an exit status *is* specified but the verbose level is *not*, then the verbose level will default to 1 if the exit status is less than 2 and will default to 0 otherwise.
* If an exit status is *not* specified but verbose level *is* given, then the exit status will default to 2 if the verbose level is 0 and will default to 1 otherwise.
* If the exit status used is less than 2, then output is printed on `STDOUT`. Otherwise output is printed on `STDERR`.
Although the above may seem a bit confusing at first, it generally does "the right thing" in most situations. This determination of the default values to use is based upon the following typical Unix conventions:
* An exit status of 0 implies "success". For example, **diff(1)** exits with a status of 0 if the two files have the same contents.
* An exit status of 1 implies possibly abnormal, but non-defective, program termination. For example, **grep(1)** exits with a status of 1 if it did *not* find a matching line for the given regular expression.
* An exit status of 2 or more implies a fatal error. For example, **ls(1)** exits with a status of 2 if you specify an illegal (unknown) option on the command line.
* Usage messages issued as a result of bad command-line syntax should go to `STDERR`. However, usage messages issued due to an explicit request to print usage (like specifying **-help** on the command line) should go to `STDOUT`, just in case the user wants to pipe the output to a pager (such as **more(1)**).
* If program usage has been explicitly requested by the user, it is often desirable to exit with a status of 1 (as opposed to 0) after issuing the user-requested usage message. It is also desirable to give a more verbose description of program usage in this case.
**pod2usage** does not force the above conventions upon you, but it will use them by default if you don't expressly tell it to do otherwise. The ability of **pod2usage()** to accept a single number or a string makes it convenient to use as an innocent looking error message handling function:
```
use strict;
use Pod::Usage;
use Getopt::Long;
## Parse options
my %opt;
GetOptions(\%opt, "help|?", "man", "flag1") || pod2usage(2);
pod2usage(1) if ($opt{help});
pod2usage(-exitval => 0, -verbose => 2) if ($opt{man});
## Check for too many filenames
pod2usage("$0: Too many files given.\n") if (@ARGV > 1);
```
Some user's however may feel that the above "economy of expression" is not particularly readable nor consistent and may instead choose to do something more like the following:
```
use strict;
use Pod::Usage qw(pod2usage);
use Getopt::Long qw(GetOptions);
## Parse options
my %opt;
GetOptions(\%opt, "help|?", "man", "flag1") ||
pod2usage(-verbose => 0);
pod2usage(-verbose => 1) if ($opt{help});
pod2usage(-verbose => 2) if ($opt{man});
## Check for too many filenames
pod2usage(-verbose => 2, -message => "$0: Too many files given.\n")
if (@ARGV > 1);
```
As with all things in Perl, *there's more than one way to do it*, and **pod2usage()** adheres to this philosophy. If you are interested in seeing a number of different ways to invoke **pod2usage** (although by no means exhaustive), please refer to ["EXAMPLES"](#EXAMPLES).
### Scripts
The Pod::Usage distribution comes with a script pod2usage which offers a command line interface to the functionality of Pod::Usage. See <pod2usage>.
EXAMPLES
--------
Each of the following invocations of `pod2usage()` will print just the "SYNOPSIS" section to `STDERR` and will exit with a status of 2:
```
pod2usage();
pod2usage(2);
pod2usage(-verbose => 0);
pod2usage(-exitval => 2);
pod2usage({-exitval => 2, -output => \*STDERR});
pod2usage({-verbose => 0, -output => \*STDERR});
pod2usage(-exitval => 2, -verbose => 0);
pod2usage(-exitval => 2, -verbose => 0, -output => \*STDERR);
```
Each of the following invocations of `pod2usage()` will print a message of "Syntax error." (followed by a newline) to `STDERR`, immediately followed by just the "SYNOPSIS" section (also printed to `STDERR`) and will exit with a status of 2:
```
pod2usage("Syntax error.");
pod2usage(-message => "Syntax error.", -verbose => 0);
pod2usage(-msg => "Syntax error.", -exitval => 2);
pod2usage({-msg => "Syntax error.", -exitval => 2, -output => \*STDERR});
pod2usage({-msg => "Syntax error.", -verbose => 0, -output => \*STDERR});
pod2usage(-msg => "Syntax error.", -exitval => 2, -verbose => 0);
pod2usage(-message => "Syntax error.",
-exitval => 2,
-verbose => 0,
-output => \*STDERR);
```
Each of the following invocations of `pod2usage()` will print the "SYNOPSIS" section and any "OPTIONS" and/or "ARGUMENTS" sections to `STDOUT` and will exit with a status of 1:
```
pod2usage(1);
pod2usage(-verbose => 1);
pod2usage(-exitval => 1);
pod2usage({-exitval => 1, -output => \*STDOUT});
pod2usage({-verbose => 1, -output => \*STDOUT});
pod2usage(-exitval => 1, -verbose => 1);
pod2usage(-exitval => 1, -verbose => 1, -output => \*STDOUT});
```
Each of the following invocations of `pod2usage()` will print the entire manual page to `STDOUT` and will exit with a status of 1:
```
pod2usage(-verbose => 2);
pod2usage({-verbose => 2, -output => \*STDOUT});
pod2usage(-exitval => 1, -verbose => 2);
pod2usage({-exitval => 1, -verbose => 2, -output => \*STDOUT});
```
###
Recommended Use
Most scripts should print some type of usage message to `STDERR` when a command line syntax error is detected. They should also provide an option (usually `-H` or `-help`) to print a (possibly more verbose) usage message to `STDOUT`. Some scripts may even wish to go so far as to provide a means of printing their complete documentation to `STDOUT` (perhaps by allowing a `-man` option). The following complete example uses **Pod::Usage** in combination with **Getopt::Long** to do all of these things:
```
use strict;
use Getopt::Long qw(GetOptions);
use Pod::Usage qw(pod2usage);
my $man = 0;
my $help = 0;
## Parse options and print usage if there is a syntax error,
## or if usage was explicitly requested.
GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-verbose => 2) if $man;
## If no arguments were given, then allow STDIN to be used only
## if it's not connected to a terminal (otherwise print usage)
pod2usage("$0: No files given.") if ((@ARGV == 0) && (-t STDIN));
__END__
=head1 NAME
sample - Using GetOpt::Long and Pod::Usage
=head1 SYNOPSIS
sample [options] [file ...]
Options:
-help brief help message
-man full documentation
=head1 OPTIONS
=over 4
=item B<-help>
Print a brief help message and exits.
=item B<-man>
Prints the manual page and exits.
=back
=head1 DESCRIPTION
B<This program> will read the given input file(s) and do something
useful with the contents thereof.
=cut
```
CAVEATS
-------
By default, **pod2usage()** will use `$0` as the path to the pod input file. Unfortunately, not all systems on which Perl runs will set `$0` properly (although if `$0` is not found, **pod2usage()** will search `$ENV{PATH}` or else the list specified by the `-pathlist` option). If this is the case for your system, you may need to explicitly specify the path to the pod docs for the invoking script using something similar to the following:
```
pod2usage(-exitval => 2, -input => "/path/to/your/pod/docs");
```
In the pathological case that a script is called via a relative path *and* the script itself changes the current working directory (see ["chdir" in perlfunc](perlfunc#chdir)) *before* calling pod2usage, Pod::Usage will fail even on robust platforms. Don't do that. Or use [FindBin](findbin) to locate the script:
```
use FindBin;
pod2usage(-input => $FindBin::Bin . "/" . $FindBin::Script);
```
SUPPORT
-------
This module is managed in a GitHub repository, <https://github.com/Dual-Life/Pod-Usage> Feel free to fork and contribute, or to clone and send patches!
Please use <https://github.com/Dual-Life/Pod-Usage/issues/new> to file a bug report. The previous ticketing system, <https://rt.cpan.org/Dist/Display.html?Queue=Pod-Usage>, is deprecated for this package.
More general questions or discussion about POD should be sent to the `[email protected]` mail list. Send an empty email to `[email protected]` to subscribe.
AUTHOR
------
Marek Rouchal <[email protected]>
Nicolas R <[email protected]>
Brad Appleton <[email protected]>
Based on code for **Pod::Text::pod2text()** written by Tom Christiansen <[email protected]>
LICENSE
-------
Pod::Usage (the distribution) is licensed under the same terms as Perl.
ACKNOWLEDGMENTS
---------------
Nicolas R (ATOOMIC) for setting up the Github repo and modernizing this package.
rjbs for refactoring Pod::Usage to not use Pod::Parser any more.
Steven McDougall <[email protected]> for his help and patience with re-writing this manpage.
SEE ALSO
---------
**Pod::Usage** is now a standalone distribution, depending on <Pod::Text> which in turn depends on <Pod::Simple>.
<Pod::Perldoc>, <Getopt::Long>, <Pod::Find>, [FindBin](findbin), <Pod::Text>, <Pod::Text::Termcap>, <Pod::Simple>
perl perlform perlform
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Text Fields](#Text-Fields)
+ [Numeric Fields](#Numeric-Fields)
+ [The Field @\* for Variable-Width Multi-Line Text](#The-Field-@*-for-Variable-Width-Multi-Line-Text)
+ [The Field ^\* for Variable-Width One-line-at-a-time Text](#The-Field-%5E*-for-Variable-Width-One-line-at-a-time-Text)
+ [Specifying Values](#Specifying-Values)
+ [Using Fill Mode](#Using-Fill-Mode)
+ [Suppressing Lines Where All Fields Are Void](#Suppressing-Lines-Where-All-Fields-Are-Void)
+ [Repeating Format Lines](#Repeating-Format-Lines)
+ [Top of Form Processing](#Top-of-Form-Processing)
+ [Format Variables](#Format-Variables)
* [NOTES](#NOTES)
+ [Footers](#Footers)
+ [Accessing Formatting Internals](#Accessing-Formatting-Internals)
* [WARNINGS](#WARNINGS)
NAME
----
perlform - Perl formats
DESCRIPTION
-----------
Perl has a mechanism to help you generate simple reports and charts. To facilitate this, Perl helps you code up your output page close to how it will look when it's printed. It can keep track of things like how many lines are on a page, what page you're on, when to print page headers, etc. Keywords are borrowed from FORTRAN: format() to declare and write() to execute; see their entries in <perlfunc>. Fortunately, the layout is much more legible, more like BASIC's PRINT USING statement. Think of it as a poor man's nroff(1).
Formats, like packages and subroutines, are declared rather than executed, so they may occur at any point in your program. (Usually it's best to keep them all together though.) They have their own namespace apart from all the other "types" in Perl. This means that if you have a function named "Foo", it is not the same thing as having a format named "Foo". However, the default name for the format associated with a given filehandle is the same as the name of the filehandle. Thus, the default format for STDOUT is named "STDOUT", and the default format for filehandle TEMP is named "TEMP". They just look the same. They aren't.
Output record formats are declared as follows:
```
format NAME =
FORMLIST
.
```
If the name is omitted, format "STDOUT" is defined. A single "." in column 1 is used to terminate a format. FORMLIST consists of a sequence of lines, each of which may be one of three types:
1. A comment, indicated by putting a '#' in the first column.
2. A "picture" line giving the format for one output line.
3. An argument line supplying values to plug into the previous picture line.
Picture lines contain output field definitions, intermingled with literal text. These lines do not undergo any kind of variable interpolation. Field definitions are made up from a set of characters, for starting and extending a field to its desired width. This is the complete set of characters for field definitions:
```
@ start of regular field
^ start of special field
< pad character for left justification
| pad character for centering
> pad character for right justification
# pad character for a right-justified numeric field
0 instead of first #: pad number with leading zeroes
. decimal point within a numeric field
... terminate a text field, show "..." as truncation evidence
@* variable width field for a multi-line value
^* variable width field for next line of a multi-line value
~ suppress line with all fields empty
~~ repeat line until all fields are exhausted
```
Each field in a picture line starts with either "@" (at) or "^" (caret), indicating what we'll call, respectively, a "regular" or "special" field. The choice of pad characters determines whether a field is textual or numeric. The tilde operators are not part of a field. Let's look at the various possibilities in detail.
###
Text Fields
The length of the field is supplied by padding out the field with multiple "<", ">", or "|" characters to specify a non-numeric field with, respectively, left justification, right justification, or centering. For a regular field, the value (up to the first newline) is taken and printed according to the selected justification, truncating excess characters. If you terminate a text field with "...", three dots will be shown if the value is truncated. A special text field may be used to do rudimentary multi-line text block filling; see ["Using Fill Mode"](#Using-Fill-Mode) for details.
```
Example:
format STDOUT =
@<<<<<< @|||||| @>>>>>>
"left", "middle", "right"
.
Output:
left middle right
```
###
Numeric Fields
Using "#" as a padding character specifies a numeric field, with right justification. An optional "." defines the position of the decimal point. With a "0" (zero) instead of the first "#", the formatted number will be padded with leading zeroes if necessary. A special numeric field is blanked out if the value is undefined. If the resulting value would exceed the width specified the field is filled with "#" as overflow evidence.
```
Example:
format STDOUT =
@### @.### @##.### @### @### ^####
42, 3.1415, undef, 0, 10000, undef
.
Output:
42 3.142 0.000 0 ####
```
###
The Field @\* for Variable-Width Multi-Line Text
The field "@\*" can be used for printing multi-line, nontruncated values; it should (but need not) appear by itself on a line. A final line feed is chomped off, but all other characters are emitted verbatim.
###
The Field ^\* for Variable-Width One-line-at-a-time Text
Like "@\*", this is a variable-width field. The value supplied must be a scalar variable. Perl puts the first line (up to the first "\n") of the text into the field, and then chops off the front of the string so that the next time the variable is referenced, more of the text can be printed. The variable will *not* be restored.
```
Example:
$text = "line 1\nline 2\nline 3";
format STDOUT =
Text: ^*
$text
~~ ^*
$text
.
Output:
Text: line 1
line 2
line 3
```
###
Specifying Values
The values are specified on the following format line in the same order as the picture fields. The expressions providing the values must be separated by commas. They are all evaluated in a list context before the line is processed, so a single list expression could produce multiple list elements. The expressions may be spread out to more than one line if enclosed in braces. If so, the opening brace must be the first token on the first line. If an expression evaluates to a number with a decimal part, and if the corresponding picture specifies that the decimal part should appear in the output (that is, any picture except multiple "#" characters **without** an embedded "."), the character used for the decimal point is determined by the current LC\_NUMERIC locale if `use locale` is in effect. This means that, if, for example, the run-time environment happens to specify a German locale, "," will be used instead of the default ".". See <perllocale> and ["WARNINGS"](#WARNINGS) for more information.
###
Using Fill Mode
On text fields the caret enables a kind of fill mode. Instead of an arbitrary expression, the value supplied must be a scalar variable that contains a text string. Perl puts the next portion of the text into the field, and then chops off the front of the string so that the next time the variable is referenced, more of the text can be printed. (Yes, this means that the variable itself is altered during execution of the write() call, and is not restored.) The next portion of text is determined by a crude line-breaking algorithm. You may use the carriage return character (`\r`) to force a line break. You can change which characters are legal to break on by changing the variable `$:` (that's $FORMAT\_LINE\_BREAK\_CHARACTERS if you're using the English module) to a list of the desired characters.
Normally you would use a sequence of fields in a vertical stack associated with the same scalar variable to print out a block of text. You might wish to end the final field with the text "...", which will appear in the output if the text was too long to appear in its entirety.
###
Suppressing Lines Where All Fields Are Void
Using caret fields can produce lines where all fields are blank. You can suppress such lines by putting a "~" (tilde) character anywhere in the line. The tilde will be translated to a space upon output.
###
Repeating Format Lines
If you put two contiguous tilde characters "~~" anywhere into a line, the line will be repeated until all the fields on the line are exhausted, i.e. undefined. For special (caret) text fields this will occur sooner or later, but if you use a text field of the at variety, the expression you supply had better not give the same value every time forever! (`shift(@f)` is a simple example that would work.) Don't use a regular (at) numeric field in such lines, because it will never go blank.
###
Top of Form Processing
Top-of-form processing is by default handled by a format with the same name as the current filehandle with "\_TOP" concatenated to it. It's triggered at the top of each page. See ["write" in perlfunc](perlfunc#write).
Examples:
```
# a report on the /etc/passwd file
format STDOUT_TOP =
Passwd File
Name Login Office Uid Gid Home
------------------------------------------------------------------
.
format STDOUT =
@<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
$name, $login, $office,$uid,$gid, $home
.
# a report from a bug report form
format STDOUT_TOP =
Bug Reports
@<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
$system, $%, $date
------------------------------------------------------------------
.
format STDOUT =
Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$subject
Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$index, $description
Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$priority, $date, $description
From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$from, $description
Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$programmer, $description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$description
~ ^<<<<<<<<<<<<<<<<<<<<<<<...
$description
.
```
It is possible to intermix print()s with write()s on the same output channel, but you'll have to handle `$-` (`$FORMAT_LINES_LEFT`) yourself.
###
Format Variables
The current format name is stored in the variable `$~` (`$FORMAT_NAME`), and the current top of form format name is in `$^` (`$FORMAT_TOP_NAME`). The current output page number is stored in `$%` (`$FORMAT_PAGE_NUMBER`), and the number of lines on the page is in `$=` (`$FORMAT_LINES_PER_PAGE`). Whether to autoflush output on this handle is stored in `$|` (`$OUTPUT_AUTOFLUSH`). The string output before each top of page (except the first) is stored in `$^L` (`$FORMAT_FORMFEED`). These variables are set on a per-filehandle basis, so you'll need to select() into a different one to affect them:
```
select((select(OUTF),
$~ = "My_Other_Format",
$^ = "My_Top_Format"
)[0]);
```
Pretty ugly, eh? It's a common idiom though, so don't be too surprised when you see it. You can at least use a temporary variable to hold the previous filehandle: (this is a much better approach in general, because not only does legibility improve, you now have an intermediary stage in the expression to single-step the debugger through):
```
$ofh = select(OUTF);
$~ = "My_Other_Format";
$^ = "My_Top_Format";
select($ofh);
```
If you use the English module, you can even read the variable names:
```
use English;
$ofh = select(OUTF);
$FORMAT_NAME = "My_Other_Format";
$FORMAT_TOP_NAME = "My_Top_Format";
select($ofh);
```
But you still have those funny select()s. So just use the FileHandle module. Now, you can access these special variables using lowercase method names instead:
```
use FileHandle;
format_name OUTF "My_Other_Format";
format_top_name OUTF "My_Top_Format";
```
Much better!
NOTES
-----
Because the values line may contain arbitrary expressions (for at fields, not caret fields), you can farm out more sophisticated processing to other functions, like sprintf() or one of your own. For example:
```
format Ident =
@<<<<<<<<<<<<<<<
&commify($n)
.
```
To get a real at or caret into the field, do this:
```
format Ident =
I have an @ here.
"@"
.
```
To center a whole line of text, do something like this:
```
format Ident =
@|||||||||||||||||||||||||||||||||||||||||||||||
"Some text line"
.
```
There is no builtin way to say "float this to the right hand side of the page, however wide it is." You have to specify where it goes. The truly desperate can generate their own format on the fly, based on the current number of columns, and then eval() it:
```
$format = "format STDOUT = \n"
. '^' . '<' x $cols . "\n"
. '$entry' . "\n"
. "\t^" . "<" x ($cols-8) . "~~\n"
. '$entry' . "\n"
. ".\n";
print $format if $Debugging;
eval $format;
die $@ if $@;
```
Which would generate a format looking something like this:
```
format STDOUT =
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$entry
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
$entry
.
```
Here's a little program that's somewhat like fmt(1):
```
format =
^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
$_
.
$/ = '';
while (<>) {
s/\s*\n\s*/ /g;
write;
}
```
### Footers
While $FORMAT\_TOP\_NAME contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. Not knowing how big a format is going to be until you evaluate it is one of the major problems. It's on the TODO list.
Here's one strategy: If you have a fixed-size footer, you can get footers by checking $FORMAT\_LINES\_LEFT before each write() and print the footer yourself if necessary.
Here's another strategy: Open a pipe to yourself, using `open(MYSELF, "|-")` (see ["open" in perlfunc](perlfunc#open)) and always write() to MYSELF instead of STDOUT. Have your child process massage its STDIN to rearrange headers and footers however you like. Not very convenient, but doable.
###
Accessing Formatting Internals
For low-level access to the formatting mechanism, you may use formline() and access `$^A` (the $ACCUMULATOR variable) directly.
For example:
```
$str = formline <<'END', 1,2,3;
@<<< @||| @>>>
END
print "Wow, I just stored '$^A' in the accumulator!\n";
```
Or to make an swrite() subroutine, which is to write() what sprintf() is to printf(), do this:
```
use Carp;
sub swrite {
croak "usage: swrite PICTURE ARGS" unless @_;
my $format = shift;
$^A = "";
formline($format,@_);
return $^A;
}
$string = swrite(<<'END', 1, 2, 3);
Check me out
@<<< @||| @>>>
END
print $string;
```
WARNINGS
--------
The lone dot that ends a format can also prematurely end a mail message passing through a misconfigured Internet mailer (and based on experience, such misconfiguration is the rule, not the exception). So when sending format code through mail, you should indent it so that the format-ending dot is not on the left margin; this will prevent SMTP cutoff.
Lexical variables (declared with "my") are not visible within a format unless the format is declared within the scope of the lexical variable.
If a program's environment specifies an LC\_NUMERIC locale and `use locale` is in effect when the format is declared, the locale is used to specify the decimal point character in formatted output. Formatted output cannot be controlled by `use locale` at the time when write() is called. See <perllocale> for further discussion of locale handling.
Within strings that are to be displayed in a fixed-length text field, each control character is substituted by a space. (But remember the special meaning of `\r` when using fill mode.) This is done to avoid misalignment when control characters "disappear" on some output media.
| programming_docs |
perl Pod::Text::Termcap Pod::Text::Termcap
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Pod::Text::Termcap - Convert POD data to ASCII text with format escapes
SYNOPSIS
--------
```
use Pod::Text::Termcap;
my $parser = Pod::Text::Termcap->new (sentence => 0, width => 78);
# Read POD from STDIN and write to STDOUT.
$parser->parse_from_filehandle;
# Read POD from file.pod and write to file.txt.
$parser->parse_from_file ('file.pod', 'file.txt');
```
DESCRIPTION
-----------
Pod::Text::Termcap is a simple subclass of Pod::Text that highlights output text using the correct termcap escape sequences for the current terminal. Apart from the format codes, it in all ways functions like Pod::Text. See <Pod::Text> for details and available options.
This module uses <Term::Cap> to find the correct terminal settings. See the documentation of that module for how it finds terminal database information and how to override that behavior if necessary. If unable to find control strings for bold and underscore formatting, that formatting is skipped, resulting in the same output as Pod::Text.
AUTHOR
------
Russ Allbery <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright 1999, 2001-2002, 2004, 2006, 2008-2009, 2014-2015, 2018-2019 Russ Allbery <[email protected]>
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
<Pod::Text>, <Pod::Simple>, <Term::Cap>
The current version of this module is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>. It is also part of the Perl core distribution as of 5.6.0.
perl Thread::Queue Thread::Queue
=============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [QUEUE CREATION](#QUEUE-CREATION)
* [BASIC METHODS](#BASIC-METHODS)
* [ADVANCED METHODS](#ADVANCED-METHODS)
* [NOTES](#NOTES)
* [LIMITATIONS](#LIMITATIONS)
* [SEE ALSO](#SEE-ALSO)
* [MAINTAINER](#MAINTAINER)
* [LICENSE](#LICENSE)
NAME
----
Thread::Queue - Thread-safe queues
VERSION
-------
This document describes Thread::Queue version 3.14
SYNOPSIS
--------
```
use strict;
use warnings;
use threads;
use Thread::Queue;
my $q = Thread::Queue->new(); # A new empty queue
# Worker thread
my $thr = threads->create(
sub {
# Thread will loop until no more work
while (defined(my $item = $q->dequeue())) {
# Do work on $item
...
}
}
);
# Send work to the thread
$q->enqueue($item1, ...);
# Signal that there is no more work to be sent
$q->end();
# Join up with the thread when it finishes
$thr->join();
...
# Count of items in the queue
my $left = $q->pending();
# Non-blocking dequeue
if (defined(my $item = $q->dequeue_nb())) {
# Work on $item
}
# Blocking dequeue with 5-second timeout
if (defined(my $item = $q->dequeue_timed(5))) {
# Work on $item
}
# Set a size for a queue
$q->limit = 5;
# Get the second item in the queue without dequeuing anything
my $item = $q->peek(1);
# Insert two items into the queue just behind the head
$q->insert(1, $item1, $item2);
# Extract the last two items on the queue
my ($item1, $item2) = $q->extract(-2, 2);
```
DESCRIPTION
-----------
This module provides thread-safe FIFO queues that can be accessed safely by any number of threads.
Any data types supported by <threads::shared> can be passed via queues:
Ordinary scalars
Array refs
Hash refs
Scalar refs
Objects based on the above Ordinary scalars are added to queues as they are.
If not already thread-shared, the other complex data types will be cloned (recursively, if needed, and including any `bless`ings and read-only settings) into thread-shared structures before being placed onto a queue.
For example, the following would cause <Thread::Queue> to create a empty, shared array reference via `&shared([])`, copy the elements 'foo', 'bar' and 'baz' from `@ary` into it, and then place that shared reference onto the queue:
```
my @ary = qw/foo bar baz/;
$q->enqueue(\@ary);
```
However, for the following, the items are already shared, so their references are added directly to the queue, and no cloning takes place:
```
my @ary :shared = qw/foo bar baz/;
$q->enqueue(\@ary);
my $obj = &shared({});
$$obj{'foo'} = 'bar';
$$obj{'qux'} = 99;
bless($obj, 'My::Class');
$q->enqueue($obj);
```
See ["LIMITATIONS"](#LIMITATIONS) for caveats related to passing objects via queues.
QUEUE CREATION
---------------
->new() Creates a new empty queue.
->new(LIST) Creates a new queue pre-populated with the provided list of items.
BASIC METHODS
--------------
The following methods deal with queues on a FIFO basis.
->enqueue(LIST) Adds a list of items onto the end of the queue.
->dequeue()
->dequeue(COUNT) Removes the requested number of items (default is 1) from the head of the queue, and returns them. If the queue contains fewer than the requested number of items, then the thread will be blocked until the requisite number of items are available (i.e., until other threads `enqueue` more items).
->dequeue\_nb()
->dequeue\_nb(COUNT) Removes the requested number of items (default is 1) from the head of the queue, and returns them. If the queue contains fewer than the requested number of items, then it immediately (i.e., non-blocking) returns whatever items there are on the queue. If the queue is empty, then `undef` is returned.
->dequeue\_timed(TIMEOUT)
->dequeue\_timed(TIMEOUT, COUNT) Removes the requested number of items (default is 1) from the head of the queue, and returns them. If the queue contains fewer than the requested number of items, then the thread will be blocked until the requisite number of items are available, or until the timeout is reached. If the timeout is reached, it returns whatever items there are on the queue, or `undef` if the queue is empty.
The timeout may be a number of seconds relative to the current time (e.g., 5 seconds from when the call is made), or may be an absolute timeout in *epoch* seconds the same as would be used with [cond\_timedwait()](threads::shared#cond_timedwait-VARIABLE%2C-ABS_TIMEOUT). Fractional seconds (e.g., 2.5 seconds) are also supported (to the extent of the underlying implementation).
If `TIMEOUT` is missing, `undef`, or less than or equal to 0, then this call behaves the same as `dequeue_nb`.
->pending() Returns the number of items still in the queue. Returns `undef` if the queue has been ended (see below), and there are no more items in the queue.
->limit Sets the size of the queue. If set, calls to `enqueue()` will block until the number of pending items in the queue drops below the `limit`. The `limit` does not prevent enqueuing items beyond that count:
```
my $q = Thread::Queue->new(1, 2);
$q->limit = 4;
$q->enqueue(3, 4, 5); # Does not block
$q->enqueue(6); # Blocks until at least 2 items are
# dequeued
my $size = $q->limit; # Returns the current limit (may return
# 'undef')
$q->limit = 0; # Queue size is now unlimited
```
Calling any of the dequeue methods with `COUNT` greater than a queue's `limit` will generate an error.
->end() Declares that no more items will be added to the queue.
All threads blocking on `dequeue()` calls will be unblocked with any remaining items in the queue and/or `undef` being returned. Any subsequent calls to `dequeue()` will behave like `dequeue_nb()`.
Once ended, no more items may be placed in the queue.
ADVANCED METHODS
-----------------
The following methods can be used to manipulate items anywhere in a queue.
To prevent the contents of a queue from being modified by another thread while it is being examined and/or changed, [lock](threads::shared#lock-VARIABLE) the queue inside a local block:
```
{
lock($q); # Keep other threads from changing the queue's contents
my $item = $q->peek();
if ($item ...) {
...
}
}
# Queue is now unlocked
```
->peek()
->peek(INDEX) Returns an item from the queue without dequeuing anything. Defaults to the head of queue (at index position 0) if no index is specified. Negative index values are supported as with [arrays](perldata#Subscripts) (i.e., -1 is the end of the queue, -2 is next to last, and so on).
If no items exists at the specified index (i.e., the queue is empty, or the index is beyond the number of items on the queue), then `undef` is returned.
Remember, the returned item is not removed from the queue, so manipulating a `peek`ed at reference affects the item on the queue.
->insert(INDEX, LIST) Adds the list of items to the queue at the specified index position (0 is the head of the list). Any existing items at and beyond that position are pushed back past the newly added items:
```
$q->enqueue(1, 2, 3, 4);
$q->insert(1, qw/foo bar/);
# Queue now contains: 1, foo, bar, 2, 3, 4
```
Specifying an index position greater than the number of items in the queue just adds the list to the end.
Negative index positions are supported:
```
$q->enqueue(1, 2, 3, 4);
$q->insert(-2, qw/foo bar/);
# Queue now contains: 1, 2, foo, bar, 3, 4
```
Specifying a negative index position greater than the number of items in the queue adds the list to the head of the queue.
->extract()
->extract(INDEX)
->extract(INDEX, COUNT) Removes and returns the specified number of items (defaults to 1) from the specified index position in the queue (0 is the head of the queue). When called with no arguments, `extract` operates the same as `dequeue_nb`.
This method is non-blocking, and will return only as many items as are available to fulfill the request:
```
$q->enqueue(1, 2, 3, 4);
my $item = $q->extract(2) # Returns 3
# Queue now contains: 1, 2, 4
my @items = $q->extract(1, 3) # Returns (2, 4)
# Queue now contains: 1
```
Specifying an index position greater than the number of items in the queue results in `undef` or an empty list being returned.
```
$q->enqueue('foo');
my $nada = $q->extract(3) # Returns undef
my @nada = $q->extract(1, 3) # Returns ()
```
Negative index positions are supported. Specifying a negative index position greater than the number of items in the queue may return items from the head of the queue (similar to `dequeue_nb`) if the count overlaps the head of the queue from the specified position (i.e. if queue size + index + count is greater than zero):
```
$q->enqueue(qw/foo bar baz/);
my @nada = $q->extract(-6, 2); # Returns () - (3+(-6)+2) <= 0
my @some = $q->extract(-6, 4); # Returns (foo) - (3+(-6)+4) > 0
# Queue now contains: bar, baz
my @rest = $q->extract(-3, 4); # Returns (bar, baz) -
# (2+(-3)+4) > 0
```
NOTES
-----
Queues created by <Thread::Queue> can be used in both threaded and non-threaded applications.
LIMITATIONS
-----------
Passing objects on queues may not work if the objects' classes do not support sharing. See ["BUGS AND LIMITATIONS" in threads::shared](threads::shared#BUGS-AND-LIMITATIONS) for more.
Passing array/hash refs that contain objects may not work for Perl prior to 5.10.0.
SEE ALSO
---------
Thread::Queue on MetaCPAN: <https://metacpan.org/release/Thread-Queue>
Code repository for CPAN distribution: <https://github.com/Dual-Life/Thread-Queue>
<threads>, <threads::shared>
Sample code in the *examples* directory of this distribution on CPAN.
MAINTAINER
----------
Jerry D. Hedden, <jdhedden AT cpan DOT org>
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl TAP::Harness TAP::Harness
============
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [runtests](#runtests)
- [summary](#summary)
- [aggregate\_tests](#aggregate_tests)
- [make\_scheduler](#make_scheduler)
- [jobs](#jobs)
- [make\_parser](#make_parser)
- [finish\_parser](#finish_parser)
* [CONFIGURING](#CONFIGURING)
+ [Plugins](#Plugins)
+ [Module::Build](#Module::Build)
+ [ExtUtils::MakeMaker](#ExtUtils::MakeMaker)
+ [prove](#prove)
* [WRITING PLUGINS](#WRITING-PLUGINS)
* [SUBCLASSING](#SUBCLASSING)
+ [Methods](#Methods)
* [REPLACING](#REPLACING)
* [SEE ALSO](#SEE-ALSO)
NAME
----
TAP::Harness - Run test scripts with statistics
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This is a simple test harness which allows tests to be run and results automatically aggregated and output to STDOUT.
SYNOPSIS
--------
```
use TAP::Harness;
my $harness = TAP::Harness->new( \%args );
$harness->runtests(@tests);
```
METHODS
-------
###
Class Methods
#### `new`
```
my %args = (
verbosity => 1,
lib => [ 'lib', 'blib/lib', 'blib/arch' ],
)
my $harness = TAP::Harness->new( \%args );
```
The constructor returns a new `TAP::Harness` object. It accepts an optional hashref whose allowed keys are:
* `verbosity`
Set the verbosity level:
```
1 verbose Print individual test results to STDOUT.
0 normal
-1 quiet Suppress some test output (mostly failures
while tests are running).
-2 really quiet Suppress everything but the tests summary.
-3 silent Suppress everything.
```
* `timer`
Append run time for each test to output. Uses <Time::HiRes> if available.
* `failures`
Show test failures (this is a no-op if `verbose` is selected).
* `comments`
Show test comments (this is a no-op if `verbose` is selected).
* `show_count`
Update the running test count during testing.
* `normalize`
Set to a true value to normalize the TAP that is emitted in verbose modes.
* `lib`
Accepts a scalar value or array ref of scalar values indicating which paths to allowed libraries should be included if Perl tests are executed. Naturally, this only makes sense in the context of tests written in Perl.
* `switches`
Accepts a scalar value or array ref of scalar values indicating which switches should be included if Perl tests are executed. Naturally, this only makes sense in the context of tests written in Perl.
* `test_args`
A reference to an `@INC` style array of arguments to be passed to each test program.
```
test_args => ['foo', 'bar'],
```
if you want to pass different arguments to each test then you should pass a hash of arrays, keyed by the alias for each test:
```
test_args => {
my_test => ['foo', 'bar'],
other_test => ['baz'],
}
```
* `color`
Attempt to produce color output.
* `exec`
Typically, Perl tests are run through this. However, anything which spits out TAP is fine. You can use this argument to specify the name of the program (and optional switches) to run your tests with:
```
exec => ['/usr/bin/ruby', '-w']
```
You can also pass a subroutine reference in order to determine and return the proper program to run based on a given test script. The subroutine reference should expect the TAP::Harness object itself as the first argument, and the file name as the second argument. It should return an array reference containing the command to be run and including the test file name. It can also simply return `undef`, in which case TAP::Harness will fall back on executing the test script in Perl:
```
exec => sub {
my ( $harness, $test_file ) = @_;
# Let Perl tests run.
return undef if $test_file =~ /[.]t$/;
return [ qw( /usr/bin/ruby -w ), $test_file ]
if $test_file =~ /[.]rb$/;
}
```
If the subroutine returns a scalar with a newline or a filehandle, it will be interpreted as raw TAP or as a TAP stream, respectively.
* `merge`
If `merge` is true the harness will create parsers that merge STDOUT and STDERR together for any processes they start.
* `sources`
*NEW to 3.18*.
If set, `sources` must be a hashref containing the names of the <TAP::Parser::SourceHandler>s to load and/or configure. The values are a hash of configuration that will be accessible to the source handlers via ["config\_for" in TAP::Parser::Source](TAP::Parser::Source#config_for).
For example:
```
sources => {
Perl => { exec => '/path/to/custom/perl' },
File => { extensions => [ '.tap', '.txt' ] },
MyCustom => { some => 'config' },
}
```
The `sources` parameter affects how `source`, `tap` and `exec` parameters are handled.
For more details, see the `sources` parameter in ["new" in TAP::Parser](TAP::Parser#new), <TAP::Parser::Source>, and <TAP::Parser::IteratorFactory>.
* `aggregator_class`
The name of the class to use to aggregate test results. The default is <TAP::Parser::Aggregator>.
* `version`
*NEW to 3.22*.
Assume this TAP version for <TAP::Parser> instead of default TAP version 12.
* `formatter_class`
The name of the class to use to format output. The default is <TAP::Formatter::Console>, or <TAP::Formatter::File> if the output isn't a TTY.
* `multiplexer_class`
The name of the class to use to multiplex tests during parallel testing. The default is <TAP::Parser::Multiplexer>.
* `parser_class`
The name of the class to use to parse TAP. The default is <TAP::Parser>.
* `scheduler_class`
The name of the class to use to schedule test execution. The default is <TAP::Parser::Scheduler>.
* `formatter`
If set `formatter` must be an object that is capable of formatting the TAP output. See <TAP::Formatter::Console> for an example.
* `errors`
If parse errors are found in the TAP output, a note of this will be made in the summary report. To see all of the parse errors, set this argument to true:
```
errors => 1
```
* `directives`
If set to a true value, only test results with directives will be displayed. This overrides other settings such as `verbose` or `failures`.
* `ignore_exit`
If set to a true value instruct `TAP::Parser` to ignore exit and wait status from test scripts.
* `jobs`
The maximum number of parallel tests to run at any time. Which tests can be run in parallel is controlled by `rules`. The default is to run only one test at a time.
* `rules`
A reference to a hash of rules that control which tests may be executed in parallel. If no rules are declared and <CPAN::Meta::YAML> is available, `TAP::Harness` attempts to load rules from a YAML file specified by the `rulesfile` parameter. If no rules file exists, the default is for all tests to be eligible to be run in parallel.
Here some simple examples. For the full details of the data structure and the related glob-style pattern matching, see ["Rules data structure" in TAP::Parser::Scheduler](TAP::Parser::Scheduler#Rules-data-structure).
```
# Run all tests in sequence, except those starting with "p"
$harness->rules({
par => 't/p*.t'
});
# Equivalent YAML file
---
par: t/p*.t
# Run all tests in parallel, except those starting with "p"
$harness->rules({
seq => [
{ seq => 't/p*.t' },
{ par => '**' },
],
});
# Equivalent YAML file
---
seq:
- seq: t/p*.t
- par: **
# Run some startup tests in sequence, then some parallel tests than some
# teardown tests in sequence.
$harness->rules({
seq => [
{ seq => 't/startup/*.t' },
{ par => ['t/a/*.t','t/b/*.t','t/c/*.t'], }
{ seq => 't/shutdown/*.t' },
],
});
# Equivalent YAML file
---
seq:
- seq: t/startup/*.t
- par:
- t/a/*.t
- t/b/*.t
- t/c/*.t
- seq: t/shutdown/*.t
```
This is an experimental feature and the interface may change.
* `rulesfiles`
This specifies where to find a YAML file of test scheduling rules. If not provided, it looks for a default file to use. It first checks for a file given in the `HARNESS_RULESFILE` environment variable, then it checks for *testrules.yml* and then *t/testrules.yml*.
* `stdout`
A filehandle for catching standard output.
* `trap`
Attempt to print summary information if run is interrupted by SIGINT (Ctrl-C).
Any keys for which the value is `undef` will be ignored.
###
Instance Methods
#### `runtests`
```
$harness->runtests(@tests);
```
Accepts an array of `@tests` to be run. This should generally be the names of test files, but this is not required. Each element in `@tests` will be passed to `TAP::Parser::new()` as a `source`. See <TAP::Parser> for more information.
It is possible to provide aliases that will be displayed in place of the test name by supplying the test as a reference to an array containing `[ $test, $alias ]`:
```
$harness->runtests( [ 't/foo.t', 'Foo Once' ],
[ 't/foo.t', 'Foo Twice' ] );
```
Normally it is an error to attempt to run the same test twice. Aliases allow you to overcome this limitation by giving each run of the test a unique name.
Tests will be run in the order found.
If the environment variable `PERL_TEST_HARNESS_DUMP_TAP` is defined it should name a directory into which a copy of the raw TAP for each test will be written. TAP is written to files named for each test. Subdirectories will be created as needed.
Returns a <TAP::Parser::Aggregator> containing the test results.
#### `summary`
```
$harness->summary( $aggregator );
```
Output the summary for a <TAP::Parser::Aggregator>.
#### `aggregate_tests`
```
$harness->aggregate_tests( $aggregate, @tests );
```
Run the named tests and display a summary of result. Tests will be run in the order found.
Test results will be added to the supplied <TAP::Parser::Aggregator>. `aggregate_tests` may be called multiple times to run several sets of tests. Multiple `Test::Harness` instances may be used to pass results to a single aggregator so that different parts of a complex test suite may be run using different `TAP::Harness` settings. This is useful, for example, in the case where some tests should run in parallel but others are unsuitable for parallel execution.
```
my $formatter = TAP::Formatter::Console->new;
my $ser_harness = TAP::Harness->new( { formatter => $formatter } );
my $par_harness = TAP::Harness->new(
{ formatter => $formatter,
jobs => 9
}
);
my $aggregator = TAP::Parser::Aggregator->new;
$aggregator->start();
$ser_harness->aggregate_tests( $aggregator, @ser_tests );
$par_harness->aggregate_tests( $aggregator, @par_tests );
$aggregator->stop();
$formatter->summary($aggregator);
```
Note that for simpler testing requirements it will often be possible to replace the above code with a single call to `runtests`.
Each element of the `@tests` array is either:
* the source name of a test to run
* a reference to a [ source name, display name ] array
In the case of a perl test suite, typically *source names* are simply the file names of the test scripts to run.
When you supply a separate display name it becomes possible to run a test more than once; the display name is effectively the alias by which the test is known inside the harness. The harness doesn't care if it runs the same test more than once when each invocation uses a different name.
#### `make_scheduler`
Called by the harness when it needs to create a <TAP::Parser::Scheduler>. Override in a subclass to provide an alternative scheduler. `make_scheduler` is passed the list of tests that was passed to `aggregate_tests`.
#### `jobs`
Gets or sets the number of concurrent test runs the harness is handling. By default, this value is 1 -- for parallel testing, this should be set higher.
#### `make_parser`
Make a new parser and display formatter session. Typically used and/or overridden in subclasses.
```
my ( $parser, $session ) = $harness->make_parser;
```
#### `finish_parser`
Terminate use of a parser. Typically used and/or overridden in subclasses. The parser isn't destroyed as a result of this.
CONFIGURING
-----------
`TAP::Harness` is designed to be easy to configure.
### Plugins
`TAP::Parser` plugins let you change the way TAP is *input* to and *output* from the parser.
<TAP::Parser::SourceHandler>s handle TAP *input*. You can configure them and load custom handlers using the `sources` parameter to ["new"](#new).
<TAP::Formatter>s handle TAP *output*. You can load custom formatters by using the `formatter_class` parameter to ["new"](#new). To configure a formatter, you currently need to instantiate it outside of <TAP::Harness> and pass it in with the `formatter` parameter to ["new"](#new). This *may* be addressed by adding a *formatters* parameter to ["new"](#new) in the future.
###
`Module::Build`
<Module::Build> version `0.30` supports `TAP::Harness`.
To load `TAP::Harness` plugins, you'll need to use the `tap_harness_args` parameter to `new`, typically from your `Build.PL`. For example:
```
Module::Build->new(
module_name => 'MyApp',
test_file_exts => [qw(.t .tap .txt)],
use_tap_harness => 1,
tap_harness_args => {
sources => {
MyCustom => {},
File => {
extensions => ['.tap', '.txt'],
},
},
formatter_class => 'TAP::Formatter::HTML',
},
build_requires => {
'Module::Build' => '0.30',
'TAP::Harness' => '3.18',
},
)->create_build_script;
```
See ["new"](#new)
###
`ExtUtils::MakeMaker`
<ExtUtils::MakeMaker> does not support <TAP::Harness> out-of-the-box.
### `prove`
<prove> supports `TAP::Harness` plugins, and has a plugin system of its own. See ["FORMATTERS" in prove](prove#FORMATTERS), ["SOURCE HANDLERS" in prove](prove#SOURCE-HANDLERS) and <App::Prove> for more details.
WRITING PLUGINS
----------------
If you can't configure `TAP::Harness` to do what you want, and you can't find an existing plugin, consider writing one.
The two primary use cases supported by <TAP::Harness> for plugins are *input* and *output*:
Customize how TAP gets into the parser To do this, you can either extend an existing <TAP::Parser::SourceHandler>, or write your own. It's a pretty simple API, and they can be loaded and configured using the `sources` parameter to ["new"](#new).
Customize how TAP results are output from the parser To do this, you can either extend an existing <TAP::Formatter>, or write your own. Writing formatters are a bit more involved than writing a *SourceHandler*, as you'll need to understand the <TAP::Parser> API. A good place to start is by understanding how ["aggregate\_tests"](#aggregate_tests) works.
Custom formatters can be loaded configured using the `formatter_class` parameter to ["new"](#new).
SUBCLASSING
-----------
If you can't configure `TAP::Harness` to do exactly what you want, and writing a plugin isn't an option, consider extending it. It is designed to be (mostly) easy to subclass, though the cases when sub-classing is necessary should be few and far between.
### Methods
The following methods are ones you may wish to override if you want to subclass `TAP::Harness`.
["new"](#new)
["runtests"](#runtests)
["summary"](#summary)
REPLACING
---------
If you like the `prove` utility and <TAP::Parser> but you want your own harness, all you need to do is write one and provide `new` and `runtests` methods. Then you can use the `prove` utility like so:
```
prove --harness My::Test::Harness
```
Note that while `prove` accepts a list of tests (or things to be tested), `new` has a fairly rich set of arguments. You'll probably want to read over this code carefully to see how all of them are being used.
SEE ALSO
---------
<Test::Harness>
| programming_docs |
perl IPC::Open2 IPC::Open2
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [WARNING](#WARNING)
* [SEE ALSO](#SEE-ALSO)
NAME
----
IPC::Open2 - open a process for both reading and writing using open2()
SYNOPSIS
--------
```
use IPC::Open2;
my $pid = open2(my $chld_out, my $chld_in,
'some', 'cmd', 'and', 'args');
# or passing the command through the shell
my $pid = open2(my $chld_out, my $chld_in, 'some cmd and args');
# read from parent STDIN and write to already open handle
open my $outfile, '>', 'outfile.txt' or die "open failed: $!";
my $pid = open2($outfile, '<&STDIN', 'some', 'cmd', 'and', 'args');
# read from already open handle and write to parent STDOUT
open my $infile, '<', 'infile.txt' or die "open failed: $!";
my $pid = open2('>&STDOUT', $infile, 'some', 'cmd', 'and', 'args');
# reap zombie and retrieve exit status
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
```
DESCRIPTION
-----------
The open2() function runs the given command and connects $chld\_out for reading and $chld\_in for writing. It's what you think should work when you try
```
my $pid = open(my $fh, "|cmd args|");
```
The $chld\_in filehandle will have autoflush turned on.
If $chld\_out is a string (that is, a bareword filehandle rather than a glob or a reference) and it begins with `>&`, then the child will send output directly to that file handle. If $chld\_in is a string that begins with `<&`, then $chld\_in will be closed in the parent, and the child will read from it directly. In both cases, there will be a [dup(2)](http://man.he.net/man2/dup) instead of a [pipe(2)](http://man.he.net/man2/pipe) made.
If either reader or writer is the empty string or undefined, this will be replaced by an autogenerated filehandle. If so, you must pass a valid lvalue in the parameter slot so it can be overwritten in the caller, or an exception will be raised.
open2() returns the process ID of the child process. It doesn't return on failure: it just raises an exception matching `/^open2:/`. However, `exec` failures in the child are not detected. You'll have to trap SIGPIPE yourself.
open2() does not wait for and reap the child process after it exits. Except for short programs where it's acceptable to let the operating system take care of this, you need to do this yourself. This is normally as simple as calling `waitpid $pid, 0` when you're done with the process. Failing to do this can result in an accumulation of defunct or "zombie" processes. See ["waitpid" in perlfunc](perlfunc#waitpid) for more information.
This whole affair is quite dangerous, as you may block forever. It assumes it's going to talk to something like [bc(1)](http://man.he.net/man1/bc), both writing to it and reading from it. This is presumably safe because you "know" that commands like [bc(1)](http://man.he.net/man1/bc) will read a line at a time and output a line at a time. Programs like [sort(1)](http://man.he.net/man1/sort) that read their entire input stream first, however, are quite apt to cause deadlock.
The big problem with this approach is that if you don't have control over source code being run in the child process, you can't control what it does with pipe buffering. Thus you can't just open a pipe to `cat -v` and continually read and write a line from it.
The <IO::Pty> and [Expect](expect) modules from CPAN can help with this, as they provide a real tty (well, a pseudo-tty, actually), which gets you back to line buffering in the invoked command again.
WARNING
-------
The order of arguments differs from that of open3().
SEE ALSO
---------
See <IPC::Open3> for an alternative that handles STDERR as well. This function is really just a wrapper around open3().
perl streamzip streamzip
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [OPTIONS](#OPTIONS)
+ [Examples](#Examples)
+ [When to write a Streamed Zip File](#When-to-write-a-Streamed-Zip-File)
* [SUPPORT](#SUPPORT)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
streamzip - create a zip file from stdin
SYNOPSIS
--------
```
producer | streamzip [opts] | consumer
producer | streamzip [opts] -zipfile=output.zip
```
DESCRIPTION
-----------
This program will read data from `stdin`, compress it into a zip container and, by default, write a *streamed* zip file to `stdout`. No temporary files are created.
The zip container written to `stdout` is, by necessity, written in streaming format. Most programs that read Zip files can cope with a streamed zip file, but if interoperability is important, and your workflow allows you to write the zip file directly to disk you can create a non-streamed zip file using the `zipfile` option.
### OPTIONS
-zip64 Create a Zip64-compliant zip container. Use this option if the input is greater than 4Gig.
Default is disabled.
-zipfile=F Write zip container to the filename `F`.
Use the `Stream` option to force the creation of a streamed zip file.
-member-name=M This option is used to name the "file" in the zip container.
Default is '-'.
-stream Ignored when writing to `stdout`.
If the `zipfile` option is specified, including this option will trigger the creation of a streamed zip file.
Default: Always enabled when writing to `stdout`, otherwise disabled.
-method=M Compress using method `M`.
Valid method names are
```
* store Store without compression
* deflate Use Deflate compression [Deflault]
* bzip2 Use Bzip2 compression
* lzma Use LZMA compression
* xz Use xz compression
* zstd Use Zstandard compression
```
Note that Lzma compress needs `IO::Compress::Lzma` to be installed.
Note that Zstd compress needs `IO::Compress::Zstd` to be installed.
Default is `deflate`.
-0, -1, -2, -3, -4, -5, -6, -7, -8, -9 Sets the compression level for `deflate`. Ignored for all other compression methods.
`-0` means no compression and `-9` for maximum compression.
Default is 6
-version Display version number
-help Display help
### Examples
Create a zip file bt reading daa from stdin
```
$ echo Lorem ipsum dolor sit | perl ./bin/streamzip >abcd.zip
```
Check the contents of `abcd,zip` with the standard `unzip` utility
```
Archive: abcd.zip
Length Date Time Name
--------- ---------- ----- ----
22 2021-01-08 19:45 -
--------- -------
22 1 file
```
Notice how the `Name` is set to `-`. That is the default for a few zip utilities whwre the member name is not given.
If you want to explicitly name the file, use the `-member-name` option as follows
```
$ echo Lorem ipsum dolor sit | perl ./bin/streamzip -member-name latin >abcd.zip
$ unzip -l abcd.zip
Archive: abcd.zip
Length Date Time Name
--------- ---------- ----- ----
22 2021-01-08 19:47 latin
--------- -------
22 1 file
```
###
When to write a Streamed Zip File
A Streamed Zip File is useful in situations where you cannot seek backwards/forwards in the file.
A good examples is when you are serving dynamic content from a Web Server straight into a socket without needing to create a temporary zip file in the filesystsm.
Similarly if your workfow uses a Linux pipelined commands.
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
AUTHOR
------
Paul Marquess *[email protected]*.
COPYRIGHT
---------
Copyright (c) 2019-2021 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlhurd perlhurd
========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Known Problems with Perl on Hurd](#Known-Problems-with-Perl-on-Hurd)
* [AUTHOR](#AUTHOR)
NAME
----
perlhurd - Perl version 5 on Hurd
DESCRIPTION
-----------
If you want to use Perl on the Hurd, I recommend using the Debian GNU/Hurd distribution ( see <https://www.debian.org/> ), even if an official, stable release has not yet been made. The old "gnu-0.2" binary distribution will most certainly have additional problems.
###
Known Problems with Perl on Hurd
The Perl test suite may still report some errors on the Hurd. The "lib/anydbm" and "pragma/warnings" tests will almost certainly fail. Both failures are not really specific to the Hurd, as indicated by the test suite output.
The socket tests may fail if the network is not configured. You have to make "/hurd/pfinet" the translator for "/servers/socket/2", giving it the right arguments. Try "/hurd/pfinet --help" for more information.
Here are the statistics for Perl 5.005\_62 on my system:
```
Failed Test Status Wstat Total Fail Failed List of failed
-----------------------------------------------------------------------
lib/anydbm.t 12 1 8.33% 12
pragma/warnings 333 1 0.30% 215
8 tests and 24 subtests skipped.
Failed 2/229 test scripts, 99.13% okay. 2/10850 subtests failed,
99.98% okay.
```
There are quite a few systems out there that do worse!
However, since I am running a very recent Hurd snapshot, in which a lot of bugs that were exposed by the Perl test suite have been fixed, you may encounter more failures. Likely candidates are: "op/stat", "lib/io\_pipe", "lib/io\_sock", "lib/io\_udp" and "lib/time".
In any way, if you're seeing failures beyond those mentioned in this document, please consider upgrading to the latest Hurd before reporting the failure as a bug.
AUTHOR
------
Mark Kettenis <[email protected]>
Last Updated: Fri, 29 Oct 1999 22:50:30 +0200
perl version::Internals version::Internals
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [WHAT IS A VERSION?](#WHAT-IS-A-VERSION?)
+ [Decimal Versions](#Decimal-Versions)
+ [Dotted-Decimal Versions](#Dotted-Decimal-Versions)
+ [Alpha Versions](#Alpha-Versions)
+ [Regular Expressions for Version Parsing](#Regular-Expressions-for-Version-Parsing)
* [IMPLEMENTATION DETAILS](#IMPLEMENTATION-DETAILS)
+ [Equivalence between Decimal and Dotted-Decimal Versions](#Equivalence-between-Decimal-and-Dotted-Decimal-Versions)
+ [Quoting Rules](#Quoting-Rules)
+ [What about v-strings?](#What-about-v-strings?)
+ [Version Object Internals](#Version-Object-Internals)
+ [Replacement UNIVERSAL::VERSION](#Replacement-UNIVERSAL::VERSION)
* [USAGE DETAILS](#USAGE-DETAILS)
+ [Using modules that use version.pm](#Using-modules-that-use-version.pm)
+ [Object Methods](#Object-Methods)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
version::Internals - Perl extension for Version Objects
DESCRIPTION
-----------
Overloaded version objects for all modern versions of Perl. This documents the internal data representation and underlying code for version.pm. See *version.pod* for daily usage. This document is only useful for users interested in the gory details.
WHAT IS A VERSION?
-------------------
For the purposes of this module, a version "number" is a sequence of positive integer values separated by one or more decimal points and optionally a single underscore. This corresponds to what Perl itself uses for a version, as well as extending the "version as number" that is discussed in the various editions of the Camel book.
There are actually two distinct kinds of version objects:
Decimal versions Any version which "looks like a number", see ["Decimal Versions"](#Decimal-Versions). This also includes versions with a single decimal point and a single embedded underscore, see ["Alpha Versions"](#Alpha-Versions), even though these must be quoted to preserve the underscore formatting.
Dotted-Decimal versions Also referred to as "Dotted-Integer", these contains more than one decimal point and may have an optional embedded underscore, see ["Dotted-Decimal Versions"](#Dotted-Decimal-Versions). This is what is commonly used in most open source software as the "external" version (the one used as part of the tag or tarfile name). A leading 'v' character is now required and will warn if it missing.
Both of these methods will produce similar version objects, in that the default stringification will yield the version ["Normal Form"](#Normal-Form) only if required:
```
$v = version->new(1.002); # 1.002, but compares like 1.2.0
$v = version->new(1.002003); # 1.002003
$v2 = version->new("v1.2.3"); # v1.2.3
```
In specific, version numbers initialized as ["Decimal Versions"](#Decimal-Versions) will stringify as they were originally created (i.e. the same string that was passed to `new()`. Version numbers initialized as ["Dotted-Decimal Versions"](#Dotted-Decimal-Versions) will be stringified as ["Normal Form"](#Normal-Form).
###
Decimal Versions
These correspond to historical versions of Perl itself prior to 5.6.0, as well as all other modules which follow the Camel rules for the $VERSION scalar. A Decimal version is initialized with what looks like a floating point number. Leading zeros **are** significant and trailing zeros are implied so that a minimum of three places is maintained between subversions. What this means is that any subversion (digits to the right of the decimal place) that contains less than three digits will have trailing zeros added to make up the difference, but only for purposes of comparison with other version objects. For example:
```
# Prints Equivalent to
$v = version->new( 1.2); # 1.2 v1.200.0
$v = version->new( 1.02); # 1.02 v1.20.0
$v = version->new( 1.002); # 1.002 v1.2.0
$v = version->new( 1.0023); # 1.0023 v1.2.300
$v = version->new( 1.00203); # 1.00203 v1.2.30
$v = version->new( 1.002003); # 1.002003 v1.2.3
```
All of the preceding examples are true whether or not the input value is quoted. The important feature is that the input value contains only a single decimal. See also ["Alpha Versions"](#Alpha-Versions).
IMPORTANT NOTE: As shown above, if your Decimal version contains more than 3 significant digits after the decimal place, it will be split on each multiple of 3, so 1.0003 is equivalent to v1.0.300, due to the need to remain compatible with Perl's own 5.005\_03 == 5.5.30 interpretation. Any trailing zeros are ignored for mathematical comparison purposes.
###
Dotted-Decimal Versions
These are the newest form of versions, and correspond to Perl's own version style beginning with 5.6.0. Starting with Perl 5.10.0, and most likely Perl 6, this is likely to be the preferred form. This method normally requires that the input parameter be quoted, although Perl's after 5.8.1 can use v-strings as a special form of quoting, but this is highly discouraged.
Unlike ["Decimal Versions"](#Decimal-Versions), Dotted-Decimal Versions have more than a single decimal point, e.g.:
```
# Prints
$v = version->new( "v1.200"); # v1.200.0
$v = version->new("v1.20.0"); # v1.20.0
$v = qv("v1.2.3"); # v1.2.3
$v = qv("1.2.3"); # v1.2.3
$v = qv("1.20"); # v1.20.0
```
In general, Dotted-Decimal Versions permit the greatest amount of freedom to specify a version, whereas Decimal Versions enforce a certain uniformity.
Just like ["Decimal Versions"](#Decimal-Versions), Dotted-Decimal Versions can be used as ["Alpha Versions"](#Alpha-Versions).
###
Alpha Versions
For module authors using CPAN, the convention has been to note unstable releases with an underscore in the version string. (See [CPAN](cpan).) version.pm follows this convention and alpha releases will test as being newer than the more recent stable release, and less than the next stable release. Only the last element may be separated by an underscore:
```
# Declaring
use version 0.77; our $VERSION = version->declare("v1.2_3");
# Parsing
$v1 = version->parse("v1.2_3");
$v1 = version->parse("1.002_003");
```
Note that you **must** quote the version when writing an alpha Decimal version. The stringified form of Decimal versions will always be the same string that was used to initialize the version object.
###
Regular Expressions for Version Parsing
A formalized definition of the legal forms for version strings is included in the `version::regex` class. Primitives are included for common elements, although they are scoped to the file so they are useful for reference purposes only. There are two publicly accessible scalars that can be used in other code (not exported):
`$version::LAX`
This regexp covers all of the legal forms allowed under the current version string parser. This is not to say that all of these forms are recommended, and some of them can only be used when quoted.
For dotted decimals:
```
v1.2
1.2345.6
v1.23_4
```
The leading 'v' is optional if two or more decimals appear. If only a single decimal is included, then the leading 'v' is required to trigger the dotted-decimal parsing. A leading zero is permitted, though not recommended except when quoted, because of the risk that Perl will treat the number as octal. A trailing underscore plus one or more digits denotes an alpha or development release (and must be quoted to be parsed properly).
For decimal versions:
```
1
1.2345
1.2345_01
```
an integer portion, an optional decimal point, and optionally one or more digits to the right of the decimal are all required. A trailing underscore is permitted and a leading zero is permitted. Just like the lax dotted-decimal version, quoting the values is required for alpha/development forms to be parsed correctly.
`$version::STRICT`
This regexp covers a much more limited set of formats and constitutes the best practices for initializing version objects. Whether you choose to employ decimal or dotted-decimal for is a personal preference however.
v1.234.5 For dotted-decimal versions, a leading 'v' is required, with three or more sub-versions of no more than three digits. A leading 0 (zero) before the first sub-version (in the above example, '1') is also prohibited.
2.3456 For decimal versions, an integer portion (no leading 0), a decimal point, and one or more digits to the right of the decimal are all required.
Both of the provided scalars are already compiled as regular expressions and do not contain either anchors or implicit groupings, so they can be included in your own regular expressions freely. For example, consider the following code:
```
($pkg, $ver) =~ /
^[ \t]*
use [ \t]+($PKGNAME)
(?:[ \t]+($version::STRICT))?
[ \t]*;
/x;
```
This would match a line of the form:
```
use Foo::Bar::Baz v1.2.3; # legal only in Perl 5.8.1+
```
where `$PKGNAME` is another regular expression that defines the legal forms for package names.
IMPLEMENTATION DETAILS
-----------------------
###
Equivalence between Decimal and Dotted-Decimal Versions
When Perl 5.6.0 was released, the decision was made to provide a transformation between the old-style decimal versions and new-style dotted-decimal versions:
```
5.6.0 == 5.006000
5.005_04 == 5.5.40
```
The floating point number is taken and split first on the single decimal place, then each group of three digits to the right of the decimal makes up the next digit, and so on until the number of significant digits is exhausted, **plus** enough trailing zeros to reach the next multiple of three.
This was the method that version.pm adopted as well. Some examples may be helpful:
```
equivalent
decimal zero-padded dotted-decimal
------- ----------- --------------
1.2 1.200 v1.200.0
1.02 1.020 v1.20.0
1.002 1.002 v1.2.0
1.0023 1.002300 v1.2.300
1.00203 1.002030 v1.2.30
1.002003 1.002003 v1.2.3
```
###
Quoting Rules
Because of the nature of the Perl parsing and tokenizing routines, certain initialization values **must** be quoted in order to correctly parse as the intended version, especially when using the `declare` or ["qv()"](#qv%28%29) methods. While you do not have to quote decimal numbers when creating version objects, it is always safe to quote **all** initial values when using version.pm methods, as this will ensure that what you type is what is used.
Additionally, if you quote your initializer, then the quoted value that goes **in** will be exactly what comes **out** when your $VERSION is printed (stringified). If you do not quote your value, Perl's normal numeric handling comes into play and you may not get back what you were expecting.
If you use a mathematic formula that resolves to a floating point number, you are dependent on Perl's conversion routines to yield the version you expect. You are pretty safe by dividing by a power of 10, for example, but other operations are not likely to be what you intend. For example:
```
$VERSION = version->new((qw$Revision: 1.4)[1]/10);
print $VERSION; # yields 0.14
$V2 = version->new(100/9); # Integer overflow in decimal number
print $V2; # yields something like 11.111.111.100
```
Perl 5.8.1 and beyond are able to automatically quote v-strings but that is not possible in earlier versions of Perl. In other words:
```
$version = version->new("v2.5.4"); # legal in all versions of Perl
$newvers = version->new(v2.5.4); # legal only in Perl >= 5.8.1
```
###
What about v-strings?
There are two ways to enter v-strings: a bare number with two or more decimal points, or a bare number with one or more decimal points and a leading 'v' character (also bare). For example:
```
$vs1 = 1.2.3; # encoded as \1\2\3
$vs2 = v1.2; # encoded as \1\2
```
However, the use of bare v-strings to initialize version objects is **strongly** discouraged in all circumstances. Also, bare v-strings are not completely supported in any version of Perl prior to 5.8.1.
If you insist on using bare v-strings with Perl > 5.6.0, be aware of the following limitations:
1) For Perl releases 5.6.0 through 5.8.0, the v-string code merely guesses, based on some characteristics of v-strings. You **must** use a three part version, e.g. 1.2.3 or v1.2.3 in order for this heuristic to be successful.
2) For Perl releases 5.8.1 and later, v-strings have changed in the Perl core to be magical, which means that the version.pm code can automatically determine whether the v-string encoding was used.
3) In all cases, a version created using v-strings will have a stringified form that has a leading 'v' character, for the simple reason that sometimes it is impossible to tell whether one was present initially.
###
Version Object Internals
version.pm provides an overloaded version object that is designed to both encapsulate the author's intended $VERSION assignment as well as make it completely natural to use those objects as if they were numbers (e.g. for comparisons). To do this, a version object contains both the original representation as typed by the author, as well as a parsed representation to ease comparisons. Version objects employ <overload> methods to simplify code that needs to compare, print, etc the objects.
The internal structure of version objects is a blessed hash with several components:
```
bless( {
'original' => 'v1.2.3_4',
'alpha' => 1,
'qv' => 1,
'version' => [
1,
2,
3,
4
]
}, 'version' );
```
original A faithful representation of the value used to initialize this version object. The only time this will not be precisely the same characters that exist in the source file is if a short dotted-decimal version like v1.2 was used (in which case it will contain 'v1.2'). This form is **STRONGLY** discouraged, in that it will confuse you and your users.
qv A boolean that denotes whether this is a decimal or dotted-decimal version. See ["is\_qv()" in version](version#is_qv%28%29).
alpha A boolean that denotes whether this is an alpha version. NOTE: that the underscore can only appear in the last position. See ["is\_alpha()" in version](version#is_alpha%28%29).
version An array of non-negative integers that is used for comparison purposes with other version objects.
###
Replacement UNIVERSAL::VERSION
In addition to the version objects, this modules also replaces the core UNIVERSAL::VERSION function with one that uses version objects for its comparisons. The return from this operator is always the stringified form as a simple scalar (i.e. not an object), but the warning message generated includes either the stringified form or the normal form, depending on how it was called.
For example:
```
package Foo;
$VERSION = 1.2;
package Bar;
$VERSION = "v1.3.5"; # works with all Perl's (since it is quoted)
package main;
use version;
print $Foo::VERSION; # prints 1.2
print $Bar::VERSION; # prints 1.003005
eval "use foo 10";
print $@; # prints "foo version 10 required..."
eval "use foo 1.3.5; # work in Perl 5.6.1 or better
print $@; # prints "foo version 1.3.5 required..."
eval "use bar 1.3.6";
print $@; # prints "bar version 1.3.6 required..."
eval "use bar 1.004"; # note Decimal version
print $@; # prints "bar version 1.004 required..."
```
IMPORTANT NOTE: This may mean that code which searches for a specific string (to determine whether a given module is available) may need to be changed. It is always better to use the built-in comparison implicit in `use` or `require`, rather than manually poking at `class->VERSION` and then doing a comparison yourself.
The replacement UNIVERSAL::VERSION, when used as a function, like this:
```
print $module->VERSION;
```
will also exclusively return the stringified form. See ["Stringification"](#Stringification) for more details.
USAGE DETAILS
--------------
###
Using modules that use version.pm
As much as possible, the version.pm module remains compatible with all current code. However, if your module is using a module that has defined `$VERSION` using the version class, there are a couple of things to be aware of. For purposes of discussion, we will assume that we have the following module installed:
```
package Example;
use version; $VERSION = qv('1.2.2');
...module code here...
1;
```
Decimal versions always work Code of the form:
```
use Example 1.002003;
```
will always work correctly. The `use` will perform an automatic `$VERSION` comparison using the floating point number given as the first term after the module name (e.g. above 1.002.003). In this case, the installed module is too old for the requested line, so you would see an error like:
```
Example version 1.002003 (v1.2.3) required--this is only version 1.002002 (v1.2.2)...
```
Dotted-Decimal version work sometimes With Perl >= 5.6.2, you can also use a line like this:
```
use Example 1.2.3;
```
and it will again work (i.e. give the error message as above), even with releases of Perl which do not normally support v-strings (see ["What about v-strings?"](#What-about-v-strings%3F) above). This has to do with that fact that `use` only checks to see if the second term *looks like a number* and passes that to the replacement [UNIVERSAL::VERSION](universal#VERSION). This is not true in Perl 5.005\_04, however, so you are **strongly encouraged** to always use a Decimal version in your code, even for those versions of Perl which support the Dotted-Decimal version.
###
Object Methods
new() Like many OO interfaces, the new() method is used to initialize version objects. If two arguments are passed to `new()`, the **second** one will be used as if it were prefixed with "v". This is to support historical use of the `qw` operator with the CVS variable $Revision, which is automatically incremented by CVS every time the file is committed to the repository.
In order to facilitate this feature, the following code can be employed:
```
$VERSION = version->new(qw$Revision: 2.7 $);
```
and the version object will be created as if the following code were used:
```
$VERSION = version->new("v2.7");
```
In other words, the version will be automatically parsed out of the string, and it will be quoted to preserve the meaning CVS normally carries for versions. The CVS $Revision$ increments differently from Decimal versions (i.e. 1.10 follows 1.9), so it must be handled as if it were a Dotted-Decimal Version.
A new version object can be created as a copy of an existing version object, either as a class method:
```
$v1 = version->new(12.3);
$v2 = version->new($v1);
```
or as an object method:
```
$v1 = version->new(12.3);
$v2 = $v1->new(12.3);
```
and in each case, $v1 and $v2 will be identical. NOTE: if you create a new object using an existing object like this:
```
$v2 = $v1->new();
```
the new object **will not** be a clone of the existing object. In the example case, $v2 will be an empty object of the same type as $v1.
qv() An alternate way to create a new version object is through the exported qv() sub. This is not strictly like other q? operators (like qq, qw), in that the only delimiters supported are parentheses (or spaces). It is the best way to initialize a short version without triggering the floating point interpretation. For example:
```
$v1 = qv(1.2); # v1.2.0
$v2 = qv("1.2"); # also v1.2.0
```
As you can see, either a bare number or a quoted string can usually be used interchangeably, except in the case of a trailing zero, which must be quoted to be converted properly. For this reason, it is strongly recommended that all initializers to qv() be quoted strings instead of bare numbers.
To prevent the `qv()` function from being exported to the caller's namespace, either use version with a null parameter:
```
use version ();
```
or just require version, like this:
```
require version;
```
Both methods will prevent the import() method from firing and exporting the `qv()` sub.
For the subsequent examples, the following three objects will be used:
```
$ver = version->new("1.2.3.4"); # see "Quoting Rules"
$alpha = version->new("1.2.3_4"); # see "Alpha Versions"
$nver = version->new(1.002); # see "Decimal Versions"
```
Normal Form For any version object which is initialized with multiple decimal places (either quoted or if possible v-string), or initialized using the [qv()](version#qv%28%29) operator, the stringified representation is returned in a normalized or reduced form (no extraneous zeros), and with a leading 'v':
```
print $ver->normal; # prints as v1.2.3.4
print $ver->stringify; # ditto
print $ver; # ditto
print $nver->normal; # prints as v1.2.0
print $nver->stringify; # prints as 1.002,
# see "Stringification"
```
In order to preserve the meaning of the processed version, the normalized representation will always contain at least three sub terms. In other words, the following is guaranteed to always be true:
```
my $newver = version->new($ver->stringify);
if ($newver eq $ver ) # always true
{...}
```
Numification Although all mathematical operations on version objects are forbidden by default, it is possible to retrieve a number which corresponds to the version object through the use of the $obj->numify method. For formatting purposes, when displaying a number which corresponds a version object, all sub versions are assumed to have three decimal places. So for example:
```
print $ver->numify; # prints 1.002003004
print $nver->numify; # prints 1.002
```
Unlike the stringification operator, there is never any need to append trailing zeros to preserve the correct version value.
Stringification The default stringification for version objects returns exactly the same string as was used to create it, whether you used `new()` or `qv()`, with one exception. The sole exception is if the object was created using `qv()` and the initializer did not have two decimal places or a leading 'v' (both optional), then the stringified form will have a leading 'v' prepended, in order to support round-trip processing.
For example:
```
Initialized as Stringifies to
============== ==============
version->new("1.2") 1.2
version->new("v1.2") v1.2
qv("1.2.3") 1.2.3
qv("v1.3.5") v1.3.5
qv("1.2") v1.2 ### exceptional case
```
See also [UNIVERSAL::VERSION](universal#VERSION), as this also returns the stringified form when used as a class method.
IMPORTANT NOTE: There is one exceptional cases shown in the above table where the "initializer" is not stringwise equivalent to the stringified representation. If you use the `qv`() operator on a version without a leading 'v' **and** with only a single decimal place, the stringified output will have a leading 'v', to preserve the sense. See the ["qv()"](#qv%28%29) operator for more details.
IMPORTANT NOTE 2: Attempting to bypass the normal stringification rules by manually applying [numify()](version#numify%28%29) and [normal()](version#normal%28%29) will sometimes yield surprising results:
```
print version->new(version->new("v1.0")->numify)->normal; # v1.0.0
```
The reason for this is that the [numify()](version#numify%28%29) operator will turn "v1.0" into the equivalent string "1.000000". Forcing the outer version object to [normal()](version#normal%28%29) form will display the mathematically equivalent "v1.0.0".
As the example in ["new()"](#new%28%29) shows, you can always create a copy of an existing version object with the same value by the very compact:
```
$v2 = $v1->new($v1);
```
and be assured that both `$v1` and `$v2` will be completely equivalent, down to the same internal representation as well as stringification.
Comparison operators Both `cmp` and `<=>` operators perform the same comparison between terms (upgrading to a version object automatically). Perl automatically generates all of the other comparison operators based on those two. In addition to the obvious equalities listed below, appending a single trailing 0 term does not change the value of a version for comparison purposes. In other words "v1.2" and "1.2.0" will compare as identical.
For example, the following relations hold:
```
As Number As String Truth Value
------------- ---------------- -----------
$ver > 1.0 $ver gt "1.0" true
$ver < 2.5 $ver lt true
$ver != 1.3 $ver ne "1.3" true
$ver == 1.2 $ver eq "1.2" false
$ver == 1.2.3.4 $ver eq "1.2.3.4" see discussion below
```
It is probably best to chose either the Decimal notation or the string notation and stick with it, to reduce confusion. Perl6 version objects **may** only support Decimal comparisons. See also ["Quoting Rules"](#Quoting-Rules).
WARNING: Comparing version with unequal numbers of decimal points (whether explicitly or implicitly initialized), may yield unexpected results at first glance. For example, the following inequalities hold:
```
version->new(0.96) > version->new(0.95); # 0.960.0 > 0.950.0
version->new("0.96.1") < version->new(0.95); # 0.096.1 < 0.950.0
```
For this reason, it is best to use either exclusively ["Decimal Versions"](#Decimal-Versions) or ["Dotted-Decimal Versions"](#Dotted-Decimal-Versions) with multiple decimal points.
Logical Operators If you need to test whether a version object has been initialized, you can simply test it directly:
```
$vobj = version->new($something);
if ( $vobj ) # true only if $something was non-blank
```
You can also test whether a version object is an alpha version, for example to prevent the use of some feature not present in the main release:
```
$vobj = version->new("1.2_3"); # MUST QUOTE
...later...
if ( $vobj->is_alpha ) # True
```
AUTHOR
------
John Peacock <[email protected]>
SEE ALSO
---------
<perl>.
| programming_docs |
perl TAP::Parser::YAMLish::Writer TAP::Parser::YAMLish::Writer
============================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
+ [Class Methods](#Class-Methods)
- [new](#new)
+ [Instance Methods](#Instance-Methods)
- [write](#write)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
TAP::Parser::YAMLish::Writer - Write YAMLish data
VERSION
-------
Version 3.44
SYNOPSIS
--------
```
use TAP::Parser::YAMLish::Writer;
my $data = {
one => 1,
two => 2,
three => [ 1, 2, 3 ],
};
my $yw = TAP::Parser::YAMLish::Writer->new;
# Write to an array...
$yw->write( $data, \@some_array );
# ...an open file handle...
$yw->write( $data, $some_file_handle );
# ...a string ...
$yw->write( $data, \$some_string );
# ...or a closure
$yw->write( $data, sub {
my $line = shift;
print "$line\n";
} );
```
DESCRIPTION
-----------
Encodes a scalar, hash reference or array reference as YAMLish.
METHODS
-------
###
Class Methods
#### `new`
```
my $writer = TAP::Parser::YAMLish::Writer->new;
```
The constructor `new` creates and returns an empty `TAP::Parser::YAMLish::Writer` object.
###
Instance Methods
#### `write`
```
$writer->write($obj, $output );
```
Encode a scalar, hash reference or array reference as YAML.
```
my $writer = sub {
my $line = shift;
print SOMEFILE "$line\n";
};
my $data = {
one => 1,
two => 2,
three => [ 1, 2, 3 ],
};
my $yw = TAP::Parser::YAMLish::Writer->new;
$yw->write( $data, $writer );
```
The `$output` argument may be:
* a reference to a scalar to append YAML to
* the handle of an open file
* a reference to an array into which YAML will be pushed
* a code reference
If you supply a code reference the subroutine will be called once for each line of output with the line as its only argument. Passed lines will have no trailing newline.
AUTHOR
------
Andy Armstrong, <[email protected]>
SEE ALSO
---------
<YAML::Tiny>, [YAML](yaml), <YAML::Syck>, <Config::Tiny>, <CSS::Tiny>, <http://use.perl.org/~Alias/journal/29427>
COPYRIGHT
---------
Copyright 2007-2011 Andy Armstrong.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.
perl CORE CORE
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [OVERRIDING CORE FUNCTIONS](#OVERRIDING-CORE-FUNCTIONS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
CORE - Namespace for Perl's core routines
SYNOPSIS
--------
```
BEGIN {
*CORE::GLOBAL::hex = sub { 1; };
}
print hex("0x50"),"\n"; # prints 1
print CORE::hex("0x50"),"\n"; # prints 80
CORE::say "yes"; # prints yes
BEGIN { *shove = \&CORE::push; }
shove @array, 1,2,3; # pushes on to @array
```
DESCRIPTION
-----------
The `CORE` namespace gives access to the original built-in functions of Perl. The `CORE` package is built into Perl, and therefore you do not need to use or require a hypothetical "CORE" module prior to accessing routines in this namespace.
A list of the built-in functions in Perl can be found in <perlfunc>.
For all Perl keywords, a `CORE::` prefix will force the built-in function to be used, even if it has been overridden or would normally require the <feature> pragma. Despite appearances, this has nothing to do with the CORE package, but is part of Perl's syntax.
For many Perl functions, the CORE package contains real subroutines. This feature is new in Perl 5.16. You can take references to these and make aliases. However, some can only be called as barewords; i.e., you cannot use ampersand syntax (`&foo`) or call them through references. See the `shove` example above. These subroutines exist for all keywords except the following:
`__DATA__`, `__END__`, `and`, `cmp`, `default`, `do`, `dump`, `else`, `elsif`, `eq`, `eval`, `for`, `foreach`, `format`, `ge`, `given`, `goto`, `grep`, `gt`, `if`, `last`, `le`, `local`, `lt`, `m`, `map`, `my`, `ne`, `next`, `no`, `or`, `our`, `package`, `print`, `printf`, `q`, `qq`, `qr`, `qw`, `qx`, `redo`, `require`, `return`, `s`, `say`, `sort`, `state`, `sub`, `tr`, `unless`, `until`, `use`, `when`, `while`, `x`, `xor`, `y`
Calling with ampersand syntax and through references does not work for the following functions, as they have special syntax that cannot always be translated into a simple list (e.g., `eof` vs `eof()`):
`chdir`, `chomp`, `chop`, `defined`, `delete`, `eof`, `exec`, `exists`, `lstat`, `split`, `stat`, `system`, `truncate`, `unlink`
OVERRIDING CORE FUNCTIONS
--------------------------
To override a Perl built-in routine with your own version, you need to import it at compile-time. This can be conveniently achieved with the `subs` pragma. This will affect only the package in which you've imported the said subroutine:
```
use subs 'chdir';
sub chdir { ... }
chdir $somewhere;
```
To override a built-in globally (that is, in all namespaces), you need to import your function into the `CORE::GLOBAL` pseudo-namespace at compile time:
```
BEGIN {
*CORE::GLOBAL::hex = sub {
# ... your code here
};
}
```
The new routine will be called whenever a built-in function is called without a qualifying package:
```
print hex("0x50"),"\n"; # prints 1
```
In both cases, if you want access to the original, unaltered routine, use the `CORE::` prefix:
```
print CORE::hex("0x50"),"\n"; # prints 80
```
AUTHOR
------
This documentation provided by Tels <[email protected]> 2007.
SEE ALSO
---------
<perlsub>, <perlfunc>.
perl Pod::Simple::PullParser Pod::Simple::PullParser
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [NOTE](#NOTE)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::PullParser -- a pull-parser interface to parsing Pod
SYNOPSIS
--------
```
my $parser = SomePodProcessor->new;
$parser->set_source( "whatever.pod" );
$parser->run;
```
Or:
```
my $parser = SomePodProcessor->new;
$parser->set_source( $some_filehandle_object );
$parser->run;
```
Or:
```
my $parser = SomePodProcessor->new;
$parser->set_source( \$document_source );
$parser->run;
```
Or:
```
my $parser = SomePodProcessor->new;
$parser->set_source( \@document_lines );
$parser->run;
```
And elsewhere:
```
require 5;
package SomePodProcessor;
use strict;
use base qw(Pod::Simple::PullParser);
sub run {
my $self = shift;
Token:
while(my $token = $self->get_token) {
...process each token...
}
}
```
DESCRIPTION
-----------
This class is for using Pod::Simple to build a Pod processor -- but one that uses an interface based on a stream of token objects, instead of based on events.
This is a subclass of <Pod::Simple> and inherits all its methods.
A subclass of Pod::Simple::PullParser should define a `run` method that calls `$token = $parser->get_token` to pull tokens.
See the source for Pod::Simple::RTF for an example of a formatter that uses Pod::Simple::PullParser.
METHODS
-------
my $token = $parser->get\_token This returns the next token object (which will be of a subclass of <Pod::Simple::PullParserToken>), or undef if the parser-stream has hit the end of the document.
$parser->unget\_token( $token )
$parser->unget\_token( $token1, $token2, ... ) This restores the token object(s) to the front of the parser stream.
The source has to be set before you can parse anything. The lowest-level way is to call `set_source`:
$parser->set\_source( $filename )
$parser->set\_source( $filehandle\_object )
$parser->set\_source( \$document\_source )
$parser->set\_source( \@document\_lines ) Or you can call these methods, which Pod::Simple::PullParser has defined to work just like Pod::Simple's same-named methods:
$parser->parse\_file(...)
$parser->parse\_string\_document(...)
$parser->filter(...)
$parser->parse\_from\_file(...) For those to work, the Pod-processing subclass of Pod::Simple::PullParser has to have defined a $parser->run method -- so it is advised that all Pod::Simple::PullParser subclasses do so. See the Synopsis above, or the source for Pod::Simple::RTF.
Authors of formatter subclasses might find these methods useful to call on a parser object that you haven't started pulling tokens from yet:
my $title\_string = $parser->get\_title This tries to get the title string out of $parser, by getting some tokens, and scanning them for the title, and then ungetting them so that you can process the token-stream from the beginning.
For example, suppose you have a document that starts out:
```
=head1 NAME
Hoo::Boy::Wowza -- Stuff B<wow> yeah!
```
$parser->get\_title on that document will return "Hoo::Boy::Wowza -- Stuff wow yeah!". If the document starts with:
```
=head1 Name
Hoo::Boy::W00t -- Stuff B<w00t> yeah!
```
Then you'll need to pass the `nocase` option in order to recognize "Name":
```
$parser->get_title(nocase => 1);
```
In cases where get\_title can't find the title, it will return empty-string ("").
my $title\_string = $parser->get\_short\_title This is just like get\_title, except that it returns just the modulename, if the title seems to be of the form "SomeModuleName -- description".
For example, suppose you have a document that starts out:
```
=head1 NAME
Hoo::Boy::Wowza -- Stuff B<wow> yeah!
```
then $parser->get\_short\_title on that document will return "Hoo::Boy::Wowza".
But if the document starts out:
```
=head1 NAME
Hooboy, stuff B<wow> yeah!
```
then $parser->get\_short\_title on that document will return "Hooboy, stuff wow yeah!". If the document starts with:
```
=head1 Name
Hoo::Boy::W00t -- Stuff B<w00t> yeah!
```
Then you'll need to pass the `nocase` option in order to recognize "Name":
```
$parser->get_short_title(nocase => 1);
```
If the title can't be found, then get\_short\_title returns empty-string ("").
$author\_name = $parser->get\_author This works like get\_title except that it returns the contents of the "=head1 AUTHOR\n\nParagraph...\n" section, assuming that that section isn't terribly long. To recognize a "=head1 Author\n\nParagraph\n" section, pass the `nocase` option:
```
$parser->get_author(nocase => 1);
```
(This method tolerates "AUTHORS" instead of "AUTHOR" too.)
$description\_name = $parser->get\_description This works like get\_title except that it returns the contents of the "=head1 DESCRIPTION\n\nParagraph...\n" section, assuming that that section isn't terribly long. To recognize a "=head1 Description\n\nParagraph\n" section, pass the `nocase` option:
```
$parser->get_description(nocase => 1);
```
$version\_block = $parser->get\_version This works like get\_title except that it returns the contents of the "=head1 VERSION\n\n[BIG BLOCK]\n" block. Note that this does NOT return the module's `$VERSION`!! To recognize a "=head1 Version\n\n[BIG BLOCK]\n" section, pass the `nocase` option:
```
$parser->get_version(nocase => 1);
```
NOTE
----
You don't actually *have* to define a `run` method. If you're writing a Pod-formatter class, you should define a `run` just so that users can call `parse_file` etc, but you don't *have* to.
And if you're not writing a formatter class, but are instead just writing a program that does something simple with a Pod::PullParser object (and not an object of a subclass), then there's no reason to bother subclassing to add a `run` method.
SEE ALSO
---------
<Pod::Simple>
<Pod::Simple::PullParserToken> -- and its subclasses <Pod::Simple::PullParserStartToken>, <Pod::Simple::PullParserTextToken>, and <Pod::Simple::PullParserEndToken>.
<HTML::TokeParser>, which inspired this.
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl ExtUtils::Mkbootstrap ExtUtils::Mkbootstrap
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader
SYNOPSIS
--------
```
Mkbootstrap
```
DESCRIPTION
-----------
Mkbootstrap typically gets called from an extension Makefile.
There is no `*.bs` file supplied with the extension. Instead, there may be a `*_BS` file which has code for the special cases, like posix for berkeley db on the NeXT.
This file will get parsed, and produce a maybe empty `@DynaLoader::dl_resolve_using` array for the current architecture. That will be extended by $BSLOADLIBS, which was computed by ExtUtils::Liblist::ext(). If this array still is empty, we do nothing, else we write a .bs file with an `@DynaLoader::dl_resolve_using` array.
The `*_BS` file can put some code into the generated `*.bs` file by placing it in `$bscode`. This is a handy 'escape' mechanism that may prove useful in complex situations.
If @DynaLoader::dl\_resolve\_using contains `-L*` or `-l*` entries then Mkbootstrap will automatically add a dl\_findfile() call to the generated `*.bs` file.
perl Locale::Maketext::TPJ13 Locale::Maketext::TPJ13
=======================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Localization and Perl: gettext breaks, Maketext fixes](#Localization-and-Perl:-gettext-breaks,-Maketext-fixes)
+ [A Localization Horror Story: It Could Happen To You](#A-Localization-Horror-Story:-It-Could-Happen-To-You)
+ [The Linguistic View](#The-Linguistic-View)
+ [Breaking gettext](#Breaking-gettext)
+ [Replacing gettext](#Replacing-gettext)
+ [Buzzwords: Abstraction and Encapsulation](#Buzzwords:-Abstraction-and-Encapsulation)
+ [Buzzword: Isomorphism](#Buzzword:-Isomorphism)
+ [Buzzword: Inheritance](#Buzzword:-Inheritance)
+ [Buzzword: Concision](#Buzzword:-Concision)
+ [The Devil in the Details](#The-Devil-in-the-Details)
+ [The Proof in the Pudding: Localizing Web Sites](#The-Proof-in-the-Pudding:-Localizing-Web-Sites)
+ [References](#References)
NAME
----
Locale::Maketext::TPJ13 -- article about software localization
SYNOPSIS
--------
```
# This an article, not a module.
```
DESCRIPTION
-----------
The following article by Sean M. Burke and Jordan Lachler first appeared in *The Perl Journal* #13 and is copyright 1999 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself.
Localization and Perl: gettext breaks, Maketext fixes
------------------------------------------------------
by Sean M. Burke and Jordan Lachler
This article points out cases where gettext (a common system for localizing software interfaces -- i.e., making them work in the user's language of choice) fails because of basic differences between human languages. This article then describes Maketext, a new system capable of correctly treating these differences.
###
A Localization Horror Story: It Could Happen To You
"There are a number of languages spoken by human beings in this world."
-- Harald Tveit Alvestrand, in RFC 1766, "Tags for the Identification of Languages"
Imagine that your task for the day is to localize a piece of software -- and luckily for you, the only output the program emits is two messages, like this:
```
I scanned 12 directories.
Your query matched 10 files in 4 directories.
```
So how hard could that be? You look at the code that produces the first item, and it reads:
```
printf("I scanned %g directories.",
$directory_count);
```
You think about that, and realize that it doesn't even work right for English, as it can produce this output:
```
I scanned 1 directories.
```
So you rewrite it to read:
```
printf("I scanned %g %s.",
$directory_count,
$directory_count == 1 ?
"directory" : "directories",
);
```
...which does the Right Thing. (In case you don't recall, "%g" is for locale-specific number interpolation, and "%s" is for string interpolation.)
But you still have to localize it for all the languages you're producing this software for, so you pull Locale::gettext off of CPAN so you can access the `gettext` C functions you've heard are standard for localization tasks.
And you write:
```
printf(gettext("I scanned %g %s."),
$dir_scan_count,
$dir_scan_count == 1 ?
gettext("directory") : gettext("directories"),
);
```
But you then read in the gettext manual (Drepper, Miller, and Pinard 1995) that this is not a good idea, since how a single word like "directory" or "directories" is translated may depend on context -- and this is true, since in a case language like German or Russian, you'd may need these words with a different case ending in the first instance (where the word is the object of a verb) than in the second instance, which you haven't even gotten to yet (where the word is the object of a preposition, "in %g directories") -- assuming these keep the same syntax when translated into those languages.
So, on the advice of the gettext manual, you rewrite:
```
printf( $dir_scan_count == 1 ?
gettext("I scanned %g directory.") :
gettext("I scanned %g directories."),
$dir_scan_count );
```
So, you email your various translators (the boss decides that the languages du jour are Chinese, Arabic, Russian, and Italian, so you have one translator for each), asking for translations for "I scanned %g directory." and "I scanned %g directories.". When they reply, you'll put that in the lexicons for gettext to use when it localizes your software, so that when the user is running under the "zh" (Chinese) locale, gettext("I scanned %g directory.") will return the appropriate Chinese text, with a "%g" in there where printf can then interpolate $dir\_scan.
Your Chinese translator emails right back -- he says both of these phrases translate to the same thing in Chinese, because, in linguistic jargon, Chinese "doesn't have number as a grammatical category" -- whereas English does. That is, English has grammatical rules that refer to "number", i.e., whether something is grammatically singular or plural; and one of these rules is the one that forces nouns to take a plural suffix (generally "s") when in a plural context, as they are when they follow a number other than "one" (including, oddly enough, "zero"). Chinese has no such rules, and so has just the one phrase where English has two. But, no problem, you can have this one Chinese phrase appear as the translation for the two English phrases in the "zh" gettext lexicon for your program.
Emboldened by this, you dive into the second phrase that your software needs to output: "Your query matched 10 files in 4 directories.". You notice that if you want to treat phrases as indivisible, as the gettext manual wisely advises, you need four cases now, instead of two, to cover the permutations of singular and plural on the two items, $dir\_count and $file\_count. So you try this:
```
printf( $file_count == 1 ?
( $directory_count == 1 ?
gettext("Your query matched %g file in %g directory.") :
gettext("Your query matched %g file in %g directories.") ) :
( $directory_count == 1 ?
gettext("Your query matched %g files in %g directory.") :
gettext("Your query matched %g files in %g directories.") ),
$file_count, $directory_count,
);
```
(The case of "1 file in 2 [or more] directories" could, I suppose, occur in the case of symlinking or something of the sort.)
It occurs to you that this is not the prettiest code you've ever written, but this seems the way to go. You mail off to the translators asking for translations for these four cases. The Chinese guy replies with the one phrase that these all translate to in Chinese, and that phrase has two "%g"s in it, as it should -- but there's a problem. He translates it word-for-word back: "In %g directories contains %g files match your query." The %g slots are in an order reverse to what they are in English. You wonder how you'll get gettext to handle that.
But you put it aside for the moment, and optimistically hope that the other translators won't have this problem, and that their languages will be better behaved -- i.e., that they will be just like English.
But the Arabic translator is the next to write back. First off, your code for "I scanned %g directory." or "I scanned %g directories." assumes there's only singular or plural. But, to use linguistic jargon again, Arabic has grammatical number, like English (but unlike Chinese), but it's a three-term category: singular, dual, and plural. In other words, the way you say "directory" depends on whether there's one directory, or *two* of them, or *more than two* of them. Your test of `($directory == 1)` no longer does the job. And it means that where English's grammatical category of number necessitates only the two permutations of the first sentence based on "directory [singular]" and "directories [plural]", Arabic has three -- and, worse, in the second sentence ("Your query matched %g file in %g directory."), where English has four, Arabic has nine. You sense an unwelcome, exponential trend taking shape.
Your Italian translator emails you back and says that "I searched 0 directories" (a possible English output of your program) is stilted, and if you think that's fine English, that's your problem, but that *just will not do* in the language of Dante. He insists that where $directory\_count is 0, your program should produce the Italian text for "I *didn't* scan *any* directories.". And ditto for "I didn't match any files in any directories", although he says the last part about "in any directories" should probably just be left off.
You wonder how you'll get gettext to handle this; to accommodate the ways Arabic, Chinese, and Italian deal with numbers in just these few very simple phrases, you need to write code that will ask gettext for different queries depending on whether the numerical values in question are 1, 2, more than 2, or in some cases 0, and you still haven't figured out the problem with the different word order in Chinese.
Then your Russian translator calls on the phone, to *personally* tell you the bad news about how really unpleasant your life is about to become:
Russian, like German or Latin, is an inflectional language; that is, nouns and adjectives have to take endings that depend on their case (i.e., nominative, accusative, genitive, etc...) -- which is roughly a matter of what role they have in syntax of the sentence -- as well as on the grammatical gender (i.e., masculine, feminine, neuter) and number (i.e., singular or plural) of the noun, as well as on the declension class of the noun. But unlike with most other inflected languages, putting a number-phrase (like "ten" or "forty-three", or their Arabic numeral equivalents) in front of noun in Russian can change the case and number that noun is, and therefore the endings you have to put on it.
He elaborates: In "I scanned %g directories", you'd *expect* "directories" to be in the accusative case (since it is the direct object in the sentence) and the plural number, except where $directory\_count is 1, then you'd expect the singular, of course. Just like Latin or German. *But!* Where $directory\_count % 10 is 1 ("%" for modulo, remember), assuming $directory count is an integer, and except where $directory\_count % 100 is 11, "directories" is forced to become grammatically singular, which means it gets the ending for the accusative singular... You begin to visualize the code it'd take to test for the problem so far, *and still work for Chinese and Arabic and Italian*, and how many gettext items that'd take, but he keeps going... But where $directory\_count % 10 is 2, 3, or 4 (except where $directory\_count % 100 is 12, 13, or 14), the word for "directories" is forced to be genitive singular -- which means another ending... The room begins to spin around you, slowly at first... But with *all other* integer values, since "directory" is an inanimate noun, when preceded by a number and in the nominative or accusative cases (as it is here, just your luck!), it does stay plural, but it is forced into the genitive case -- yet another ending... And you never hear him get to the part about how you're going to run into similar (but maybe subtly different) problems with other Slavic languages like Polish, because the floor comes up to meet you, and you fade into unconsciousness.
The above cautionary tale relates how an attempt at localization can lead from programmer consternation, to program obfuscation, to a need for sedation. But careful evaluation shows that your choice of tools merely needed further consideration.
###
The Linguistic View
"It is more complicated than you think."
-- The Eighth Networking Truth, from RFC 1925
The field of Linguistics has expended a great deal of effort over the past century trying to find grammatical patterns which hold across languages; it's been a constant process of people making generalizations that should apply to all languages, only to find out that, all too often, these generalizations fail -- sometimes failing for just a few languages, sometimes whole classes of languages, and sometimes nearly every language in the world except English. Broad statistical trends are evident in what the "average language" is like as far as what its rules can look like, must look like, and cannot look like. But the "average language" is just as unreal a concept as the "average person" -- it runs up against the fact no language (or person) is, in fact, average. The wisdom of past experience leads us to believe that any given language can do whatever it wants, in any order, with appeal to any kind of grammatical categories wants -- case, number, tense, real or metaphoric characteristics of the things that words refer to, arbitrary or predictable classifications of words based on what endings or prefixes they can take, degree or means of certainty about the truth of statements expressed, and so on, ad infinitum.
Mercifully, most localization tasks are a matter of finding ways to translate whole phrases, generally sentences, where the context is relatively set, and where the only variation in content is *usually* in a number being expressed -- as in the example sentences above. Translating specific, fully-formed sentences is, in practice, fairly foolproof -- which is good, because that's what's in the phrasebooks that so many tourists rely on. Now, a given phrase (whether in a phrasebook or in a gettext lexicon) in one language *might* have a greater or lesser applicability than that phrase's translation into another language -- for example, strictly speaking, in Arabic, the "your" in "Your query matched..." would take a different form depending on whether the user is male or female; so the Arabic translation "your[feminine] query" is applicable in fewer cases than the corresponding English phrase, which doesn't distinguish the user's gender. (In practice, it's not feasible to have a program know the user's gender, so the masculine "you" in Arabic is usually used, by default.)
But in general, such surprises are rare when entire sentences are being translated, especially when the functional context is restricted to that of a computer interacting with a user either to convey a fact or to prompt for a piece of information. So, for purposes of localization, translation by phrase (generally by sentence) is both the simplest and the least problematic.
###
Breaking gettext
"It Has To Work."
-- First Networking Truth, RFC 1925
Consider that sentences in a tourist phrasebook are of two types: ones like "How do I get to the marketplace?" that don't have any blanks to fill in, and ones like "How much do these \_\_\_ cost?", where there's one or more blanks to fill in (and these are usually linked to a list of words that you can put in that blank: "fish", "potatoes", "tomatoes", etc.). The ones with no blanks are no problem, but the fill-in-the-blank ones may not be really straightforward. If it's a Swahili phrasebook, for example, the authors probably didn't bother to tell you the complicated ways that the verb "cost" changes its inflectional prefix depending on the noun you're putting in the blank. The trader in the marketplace will still understand what you're saying if you say "how much do these potatoes cost?" with the wrong inflectional prefix on "cost". After all, *you* can't speak proper Swahili, *you're* just a tourist. But while tourists can be stupid, computers are supposed to be smart; the computer should be able to fill in the blank, and still have the results be grammatical.
In other words, a phrasebook entry takes some values as parameters (the things that you fill in the blank or blanks), and provides a value based on these parameters, where the way you get that final value from the given values can, properly speaking, involve an arbitrarily complex series of operations. (In the case of Chinese, it'd be not at all complex, at least in cases like the examples at the beginning of this article; whereas in the case of Russian it'd be a rather complex series of operations. And in some languages, the complexity could be spread around differently: while the act of putting a number-expression in front of a noun phrase might not be complex by itself, it may change how you have to, for example, inflect a verb elsewhere in the sentence. This is what in syntax is called "long-distance dependencies".)
This talk of parameters and arbitrary complexity is just another way to say that an entry in a phrasebook is what in a programming language would be called a "function". Just so you don't miss it, this is the crux of this article: *A phrase is a function; a phrasebook is a bunch of functions.*
The reason that using gettext runs into walls (as in the above second-person horror story) is that you're trying to use a string (or worse, a choice among a bunch of strings) to do what you really need a function for -- which is futile. Preforming (s)printf interpolation on the strings which you get back from gettext does allow you to do *some* common things passably well... sometimes... sort of; but, to paraphrase what some people say about `csh` script programming, "it fools you into thinking you can use it for real things, but you can't, and you don't discover this until you've already spent too much time trying, and by then it's too late."
###
Replacing gettext
So, what needs to replace gettext is a system that supports lexicons of functions instead of lexicons of strings. An entry in a lexicon from such a system should *not* look like this:
```
"J'ai trouv\xE9 %g fichiers dans %g r\xE9pertoires"
```
[\xE9 is e-acute in Latin-1. Some pod renderers would scream if I used the actual character here. -- SB]
but instead like this, bearing in mind that this is just a first stab:
```
sub I_found_X1_files_in_X2_directories {
my( $files, $dirs ) = @_[0,1];
$files = sprintf("%g %s", $files,
$files == 1 ? 'fichier' : 'fichiers');
$dirs = sprintf("%g %s", $dirs,
$dirs == 1 ? "r\xE9pertoire" : "r\xE9pertoires");
return "J'ai trouv\xE9 $files dans $dirs.";
}
```
Now, there's no particularly obvious way to store anything but strings in a gettext lexicon; so it looks like we just have to start over and make something better, from scratch. I call my shot at a gettext-replacement system "Maketext", or, in CPAN terms, Locale::Maketext.
When designing Maketext, I chose to plan its main features in terms of "buzzword compliance". And here are the buzzwords:
###
Buzzwords: Abstraction and Encapsulation
The complexity of the language you're trying to output a phrase in is entirely abstracted inside (and encapsulated within) the Maketext module for that interface. When you call:
```
print $lang->maketext("You have [quant,_1,piece] of new mail.",
scalar(@messages));
```
you don't know (and in fact can't easily find out) whether this will involve lots of figuring, as in Russian (if $lang is a handle to the Russian module), or relatively little, as in Chinese. That kind of abstraction and encapsulation may encourage other pleasant buzzwords like modularization and stratification, depending on what design decisions you make.
###
Buzzword: Isomorphism
"Isomorphism" means "having the same structure or form"; in discussions of program design, the word takes on the special, specific meaning that your implementation of a solution to a problem *has the same structure* as, say, an informal verbal description of the solution, or maybe of the problem itself. Isomorphism is, all things considered, a good thing -- it's what problem-solving (and solution-implementing) should look like.
What's wrong the with gettext-using code like this...
```
printf( $file_count == 1 ?
( $directory_count == 1 ?
"Your query matched %g file in %g directory." :
"Your query matched %g file in %g directories." ) :
( $directory_count == 1 ?
"Your query matched %g files in %g directory." :
"Your query matched %g files in %g directories." ),
$file_count, $directory_count,
);
```
is first off that it's not well abstracted -- these ways of testing for grammatical number (as in the expressions like `foo == 1 ? singular_form : plural_form`) should be abstracted to each language module, since how you get grammatical number is language-specific.
But second off, it's not isomorphic -- the "solution" (i.e., the phrasebook entries) for Chinese maps from these four English phrases to the one Chinese phrase that fits for all of them. In other words, the informal solution would be "The way to say what you want in Chinese is with the one phrase 'For your question, in Y directories you would find X files'" -- and so the implemented solution should be, isomorphically, just a straightforward way to spit out that one phrase, with numerals properly interpolated. It shouldn't have to map from the complexity of other languages to the simplicity of this one.
###
Buzzword: Inheritance
There's a great deal of reuse possible for sharing of phrases between modules for related dialects, or for sharing of auxiliary functions between related languages. (By "auxiliary functions", I mean functions that don't produce phrase-text, but which, say, return an answer to "does this number require a plural noun after it?". Such auxiliary functions would be used in the internal logic of functions that actually do produce phrase-text.)
In the case of sharing phrases, consider that you have an interface already localized for American English (probably by having been written with that as the native locale, but that's incidental). Localizing it for UK English should, in practical terms, be just a matter of running it past a British person with the instructions to indicate what few phrases would benefit from a change in spelling or possibly minor rewording. In that case, you should be able to put in the UK English localization module *only* those phrases that are UK-specific, and for all the rest, *inherit* from the American English module. (And I expect this same situation would apply with Brazilian and Continental Portugese, possibly with some *very* closely related languages like Czech and Slovak, and possibly with the slightly different "versions" of written Mandarin Chinese, as I hear exist in Taiwan and mainland China.)
As to sharing of auxiliary functions, consider the problem of Russian numbers from the beginning of this article; obviously, you'd want to write only once the hairy code that, given a numeric value, would return some specification of which case and number a given quantified noun should use. But suppose that you discover, while localizing an interface for, say, Ukrainian (a Slavic language related to Russian, spoken by several million people, many of whom would be relieved to find that your Web site's or software's interface is available in their language), that the rules in Ukrainian are the same as in Russian for quantification, and probably for many other grammatical functions. While there may well be no phrases in common between Russian and Ukrainian, you could still choose to have the Ukrainian module inherit from the Russian module, just for the sake of inheriting all the various grammatical methods. Or, probably better organizationally, you could move those functions to a module called `_E_Slavic` or something, which Russian and Ukrainian could inherit useful functions from, but which would (presumably) provide no lexicon.
###
Buzzword: Concision
Okay, concision isn't a buzzword. But it should be, so I decree that as a new buzzword, "concision" means that simple common things should be expressible in very few lines (or maybe even just a few characters) of code -- call it a special case of "making simple things easy and hard things possible", and see also the role it played in the MIDI::Simple language, discussed elsewhere in this issue [TPJ#13].
Consider our first stab at an entry in our "phrasebook of functions":
```
sub I_found_X1_files_in_X2_directories {
my( $files, $dirs ) = @_[0,1];
$files = sprintf("%g %s", $files,
$files == 1 ? 'fichier' : 'fichiers');
$dirs = sprintf("%g %s", $dirs,
$dirs == 1 ? "r\xE9pertoire" : "r\xE9pertoires");
return "J'ai trouv\xE9 $files dans $dirs.";
}
```
You may sense that a lexicon (to use a non-committal catch-all term for a collection of things you know how to say, regardless of whether they're phrases or words) consisting of functions *expressed* as above would make for rather long-winded and repetitive code -- even if you wisely rewrote this to have quantification (as we call adding a number expression to a noun phrase) be a function called like:
```
sub I_found_X1_files_in_X2_directories {
my( $files, $dirs ) = @_[0,1];
$files = quant($files, "fichier");
$dirs = quant($dirs, "r\xE9pertoire");
return "J'ai trouv\xE9 $files dans $dirs.";
}
```
And you may also sense that you do not want to bother your translators with having to write Perl code -- you'd much rather that they spend their *very costly time* on just translation. And this is to say nothing of the near impossibility of finding a commercial translator who would know even simple Perl.
In a first-hack implementation of Maketext, each language-module's lexicon looked like this:
```
%Lexicon = (
"I found %g files in %g directories"
=> sub {
my( $files, $dirs ) = @_[0,1];
$files = quant($files, "fichier");
$dirs = quant($dirs, "r\xE9pertoire");
return "J'ai trouv\xE9 $files dans $dirs.";
},
... and so on with other phrase => sub mappings ...
);
```
but I immediately went looking for some more concise way to basically denote the same phrase-function -- a way that would also serve to concisely denote *most* phrase-functions in the lexicon for *most* languages. After much time and even some actual thought, I decided on this system:
\* Where a value in a %Lexicon hash is a contentful string instead of an anonymous sub (or, conceivably, a coderef), it would be interpreted as a sort of shorthand expression of what the sub does. When accessed for the first time in a session, it is parsed, turned into Perl code, and then eval'd into an anonymous sub; then that sub replaces the original string in that lexicon. (That way, the work of parsing and evaling the shorthand form for a given phrase is done no more than once per session.)
\* Calls to `maketext` (as Maketext's main function is called) happen thru a "language session handle", notionally very much like an IO handle, in that you open one at the start of the session, and use it for "sending signals" to an object in order to have it return the text you want.
So, this:
```
$lang->maketext("You have [quant,_1,piece] of new mail.",
scalar(@messages));
```
basically means this: look in the lexicon for $lang (which may inherit from any number of other lexicons), and find the function that we happen to associate with the string "You have [quant,\_1,piece] of new mail" (which is, and should be, a functioning "shorthand" for this function in the native locale -- English in this case). If you find such a function, call it with $lang as its first parameter (as if it were a method), and then a copy of scalar(@messages) as its second, and then return that value. If that function was found, but was in string shorthand instead of being a fully specified function, parse it and make it into a function before calling it the first time.
\* The shorthand uses code in brackets to indicate method calls that should be performed. A full explanation is not in order here, but a few examples will suffice:
```
"You have [quant,_1,piece] of new mail."
```
The above code is shorthand for, and will be interpreted as, this:
```
sub {
my $handle = $_[0];
my(@params) = @_;
return join '',
"You have ",
$handle->quant($params[1], 'piece'),
"of new mail.";
}
```
where "quant" is the name of a method you're using to quantify the noun "piece" with the number $params[0].
A string with no brackety calls, like this:
```
"Your search expression was malformed."
```
is somewhat of a degenerate case, and just gets turned into:
```
sub { return "Your search expression was malformed." }
```
However, not everything you can write in Perl code can be written in the above shorthand system -- not by a long shot. For example, consider the Italian translator from the beginning of this article, who wanted the Italian for "I didn't find any files" as a special case, instead of "I found 0 files". That couldn't be specified (at least not easily or simply) in our shorthand system, and it would have to be written out in full, like this:
```
sub { # pretend the English strings are in Italian
my($handle, $files, $dirs) = @_[0,1,2];
return "I didn't find any files" unless $files;
return join '',
"I found ",
$handle->quant($files, 'file'),
" in ",
$handle->quant($dirs, 'directory'),
".";
}
```
Next to a lexicon full of shorthand code, that sort of sticks out like a sore thumb -- but this *is* a special case, after all; and at least it's possible, if not as concise as usual.
As to how you'd implement the Russian example from the beginning of the article, well, There's More Than One Way To Do It, but it could be something like this (using English words for Russian, just so you know what's going on):
```
"I [quant,_1,directory,accusative] scanned."
```
This shifts the burden of complexity off to the quant method. That method's parameters are: the numeric value it's going to use to quantify something; the Russian word it's going to quantify; and the parameter "accusative", which you're using to mean that this sentence's syntax wants a noun in the accusative case there, although that quantification method may have to overrule, for grammatical reasons you may recall from the beginning of this article.
Now, the Russian quant method here is responsible not only for implementing the strange logic necessary for figuring out how Russian number-phrases impose case and number on their noun-phrases, but also for inflecting the Russian word for "directory". How that inflection is to be carried out is no small issue, and among the solutions I've seen, some (like variations on a simple lookup in a hash where all possible forms are provided for all necessary words) are straightforward but *can* become cumbersome when you need to inflect more than a few dozen words; and other solutions (like using algorithms to model the inflections, storing only root forms and irregularities) *can* involve more overhead than is justifiable for all but the largest lexicons.
Mercifully, this design decision becomes crucial only in the hairiest of inflected languages, of which Russian is by no means the *worst* case scenario, but is worse than most. Most languages have simpler inflection systems; for example, in English or Swahili, there are generally no more than two possible inflected forms for a given noun ("error/errors"; "kosa/makosa"), and the rules for producing these forms are fairly simple -- or at least, simple rules can be formulated that work for most words, and you can then treat the exceptions as just "irregular", at least relative to your ad hoc rules. A simpler inflection system (simpler rules, fewer forms) means that design decisions are less crucial to maintaining sanity, whereas the same decisions could incur overhead-versus-scalability problems in languages like Russian. It may *also* be likely that code (possibly in Perl, as with Lingua::EN::Inflect, for English nouns) has already been written for the language in question, whether simple or complex.
Moreover, a third possibility may even be simpler than anything discussed above: "Just require that all possible (or at least applicable) forms be provided in the call to the given language's quant method, as in:"
```
"I found [quant,_1,file,files]."
```
That way, quant just has to chose which form it needs, without having to look up or generate anything. While possibly not optimal for Russian, this should work well for most other languages, where quantification is not as complicated an operation.
###
The Devil in the Details
There's plenty more to Maketext than described above -- for example, there's the details of how language tags ("en-US", "i-pwn", "fi", etc.) or locale IDs ("en\_US") interact with actual module naming ("BogoQuery/Locale/en\_us.pm"), and what magic can ensue; there's the details of how to record (and possibly negotiate) what character encoding Maketext will return text in (UTF8? Latin-1? KOI8?). There's the interesting fact that Maketext is for localization, but nowhere actually has a "`use locale;`" anywhere in it. For the curious, there's the somewhat frightening details of how I actually implement something like data inheritance so that searches across modules' %Lexicon hashes can parallel how Perl implements method inheritance.
And, most importantly, there's all the practical details of how to actually go about deriving from Maketext so you can use it for your interfaces, and the various tools and conventions for starting out and maintaining individual language modules.
That is all covered in the documentation for Locale::Maketext and the modules that come with it, available in CPAN. After having read this article, which covers the why's of Maketext, the documentation, which covers the how's of it, should be quite straightforward.
###
The Proof in the Pudding: Localizing Web Sites
Maketext and gettext have a notable difference: gettext is in C, accessible thru C library calls, whereas Maketext is in Perl, and really can't work without a Perl interpreter (although I suppose something like it could be written for C). Accidents of history (and not necessarily lucky ones) have made C++ the most common language for the implementation of applications like word processors, Web browsers, and even many in-house applications like custom query systems. Current conditions make it somewhat unlikely that the next one of any of these kinds of applications will be written in Perl, albeit clearly more for reasons of custom and inertia than out of consideration of what is the right tool for the job.
However, other accidents of history have made Perl a well-accepted language for design of server-side programs (generally in CGI form) for Web site interfaces. Localization of static pages in Web sites is trivial, feasible either with simple language-negotiation features in servers like Apache, or with some kind of server-side inclusions of language-appropriate text into layout templates. However, I think that the localization of Perl-based search systems (or other kinds of dynamic content) in Web sites, be they public or access-restricted, is where Maketext will see the greatest use.
I presume that it would be only the exceptional Web site that gets localized for English *and* Chinese *and* Italian *and* Arabic *and* Russian, to recall the languages from the beginning of this article -- to say nothing of German, Spanish, French, Japanese, Finnish, and Hindi, to name a few languages that benefit from large numbers of programmers or Web viewers or both.
However, the ever-increasing internationalization of the Web (whether measured in terms of amount of content, of numbers of content writers or programmers, or of size of content audiences) makes it increasingly likely that the interface to the average Web-based dynamic content service will be localized for two or maybe three languages. It is my hope that Maketext will make that task as simple as possible, and will remove previous barriers to localization for languages dissimilar to English.
```
__END__
```
Sean M. Burke ([email protected]) has a Master's in linguistics from Northwestern University; he specializes in language technology. Jordan Lachler ([email protected]) is a PhD student in the Department of Linguistics at the University of New Mexico; he specializes in morphology and pedagogy of North American native languages.
### References
Alvestrand, Harald Tveit. 1995. *RFC 1766: Tags for the Identification of Languages.* `<http://www.ietf.org/rfc/rfc1766.txt>` [Now see RFC 3066.]
Callon, Ross, editor. 1996. *RFC 1925: The Twelve Networking Truths.* `<http://www.ietf.org/rfc/rfc1925.txt>`
Drepper, Ulrich, Peter Miller, and François Pinard. 1995-2001. GNU `gettext`. Available in `<ftp://prep.ai.mit.edu/pub/gnu/>`, with extensive docs in the distribution tarball. [Since I wrote this article in 1998, I now see that the gettext docs are now trying more to come to terms with plurality. Whether useful conclusions have come from it is another question altogether. -- SMB, May 2001]
Forbes, Nevill. 1964. *Russian Grammar.* Third Edition, revised by J. C. Dumbreck. Oxford University Press.
| programming_docs |
perl Test::Builder::Formatter Test::Builder::Formatter
========================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::Builder::Formatter - Test::Builder subclass of Test2::Formatter::TAP
DESCRIPTION
-----------
This is what takes events and turns them into TAP.
SYNOPSIS
--------
```
use Test::Builder; # Loads Test::Builder::Formatter for you
```
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl ExtUtils::MM_Cygwin ExtUtils::MM\_Cygwin
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
ExtUtils::MM\_Cygwin - methods to override UN\*X behaviour in ExtUtils::MakeMaker
SYNOPSIS
--------
```
use ExtUtils::MM_Cygwin; # Done internally by ExtUtils::MakeMaker if needed
```
DESCRIPTION
-----------
See <ExtUtils::MM_Unix> for a documentation of the methods provided there.
os\_flavor We're Unix and Cygwin.
cflags if configured for dynamic loading, triggers #define EXT in EXTERN.h
replace\_manpage\_separator replaces strings '::' with '.' in MAN\*POD man page names
init\_linker points to libperl.a
maybe\_command Determine whether a file is native to Cygwin by checking whether it resides inside the Cygwin installation (using Windows paths). If so, use <ExtUtils::MM_Unix> to determine if it may be a command. Otherwise use the tests from <ExtUtils::MM_Win32>.
dynamic\_lib Use the default to produce the \*.dll's. But for new archdir dll's use the same rebase address if the old exists.
install Rebase dll's with the global rebase database after installation.
perl Test::Builder Test::Builder
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Construction](#Construction)
+ [Setting up tests](#Setting-up-tests)
+ [Running tests](#Running-tests)
+ [Other Testing Methods](#Other-Testing-Methods)
+ [Test building utility methods](#Test-building-utility-methods)
+ [Test style](#Test-style)
+ [Output](#Output)
+ [Test Status and Info](#Test-Status-and-Info)
* [EXIT CODES](#EXIT-CODES)
* [THREADS](#THREADS)
* [MEMORY](#MEMORY)
* [EXAMPLES](#EXAMPLES)
* [SEE ALSO](#SEE-ALSO)
+ [INTERNALS](#INTERNALS)
+ [LEGACY](#LEGACY)
+ [EXTERNAL](#EXTERNAL)
* [AUTHORS](#AUTHORS)
* [MAINTAINERS](#MAINTAINERS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::Builder - Backend for building test libraries
SYNOPSIS
--------
```
package My::Test::Module;
use base 'Test::Builder::Module';
my $CLASS = __PACKAGE__;
sub ok {
my($test, $name) = @_;
my $tb = $CLASS->builder;
$tb->ok($test, $name);
}
```
DESCRIPTION
-----------
<Test::Simple> and <Test::More> have proven to be popular testing modules, but they're not always flexible enough. Test::Builder provides a building block upon which to write your own test libraries *which can work together*.
### Construction
**new**
```
my $Test = Test::Builder->new;
```
Returns a Test::Builder object representing the current state of the test.
Since you only run one test per program `new` always returns the same Test::Builder object. No matter how many times you call `new()`, you're getting the same object. This is called a singleton. This is done so that multiple modules share such global information as the test counter and where test output is going.
If you want a completely new Test::Builder object different from the singleton, use `create`.
**create**
```
my $Test = Test::Builder->create;
```
Ok, so there can be more than one Test::Builder object and this is how you get it. You might use this instead of `new()` if you're testing a Test::Builder based module, but otherwise you probably want `new`.
**NOTE**: the implementation is not complete. `level`, for example, is still shared by **all** Test::Builder objects, even ones created using this method. Also, the method name may change in the future.
**subtest**
```
$builder->subtest($name, \&subtests, @args);
```
See documentation of `subtest` in Test::More.
`subtest` also, and optionally, accepts arguments which will be passed to the subtests reference.
**name**
```
diag $builder->name;
```
Returns the name of the current builder. Top level builders default to `$0` (the name of the executable). Child builders are named via the `child` method. If no name is supplied, will be named "Child of $parent->name".
**reset**
```
$Test->reset;
```
Reinitializes the Test::Builder singleton to its original state. Mostly useful for tests run in persistent environments where the same test might be run multiple times in the same process.
###
Setting up tests
These methods are for setting up tests and declaring how many there are. You usually only want to call one of these methods.
**plan**
```
$Test->plan('no_plan');
$Test->plan( skip_all => $reason );
$Test->plan( tests => $num_tests );
```
A convenient way to set up your tests. Call this and Test::Builder will print the appropriate headers and take the appropriate actions.
If you call `plan()`, don't call any of the other methods below.
**expected\_tests**
```
my $max = $Test->expected_tests;
$Test->expected_tests($max);
```
Gets/sets the number of tests we expect this test to run and prints out the appropriate headers.
**no\_plan**
```
$Test->no_plan;
```
Declares that this test will run an indeterminate number of tests.
**done\_testing**
```
$Test->done_testing();
$Test->done_testing($num_tests);
```
Declares that you are done testing, no more tests will be run after this point.
If a plan has not yet been output, it will do so.
$num\_tests is the number of tests you planned to run. If a numbered plan was already declared, and if this contradicts, a failing test will be run to reflect the planning mistake. If `no_plan` was declared, this will override.
If `done_testing()` is called twice, the second call will issue a failing test.
If `$num_tests` is omitted, the number of tests run will be used, like no\_plan.
`done_testing()` is, in effect, used when you'd want to use `no_plan`, but safer. You'd use it like so:
```
$Test->ok($a == $b);
$Test->done_testing();
```
Or to plan a variable number of tests:
```
for my $test (@tests) {
$Test->ok($test);
}
$Test->done_testing(scalar @tests);
```
**has\_plan**
```
$plan = $Test->has_plan
```
Find out whether a plan has been defined. `$plan` is either `undef` (no plan has been set), `no_plan` (indeterminate # of tests) or an integer (the number of expected tests).
**skip\_all**
```
$Test->skip_all;
$Test->skip_all($reason);
```
Skips all the tests, using the given `$reason`. Exits immediately with 0.
**exported\_to**
```
my $pack = $Test->exported_to;
$Test->exported_to($pack);
```
Tells Test::Builder what package you exported your functions to.
This method isn't terribly useful since modules which share the same Test::Builder object might get exported to different packages and only the last one will be honored.
###
Running tests
These actually run the tests, analogous to the functions in Test::More.
They all return true if the test passed, false if the test failed.
`$name` is always optional.
**ok**
```
$Test->ok($test, $name);
```
Your basic test. Pass if `$test` is true, fail if $test is false. Just like Test::Simple's `ok()`.
**is\_eq**
```
$Test->is_eq($got, $expected, $name);
```
Like Test::More's `is()`. Checks if `$got eq $expected`. This is the string version.
`undef` only ever matches another `undef`.
**is\_num**
```
$Test->is_num($got, $expected, $name);
```
Like Test::More's `is()`. Checks if `$got == $expected`. This is the numeric version.
`undef` only ever matches another `undef`.
**isnt\_eq**
```
$Test->isnt_eq($got, $dont_expect, $name);
```
Like <Test::More>'s `isnt()`. Checks if `$got ne $dont_expect`. This is the string version.
**isnt\_num**
```
$Test->isnt_num($got, $dont_expect, $name);
```
Like <Test::More>'s `isnt()`. Checks if `$got ne $dont_expect`. This is the numeric version.
**like**
```
$Test->like($thing, qr/$regex/, $name);
$Test->like($thing, '/$regex/', $name);
```
Like <Test::More>'s `like()`. Checks if $thing matches the given `$regex`.
**unlike**
```
$Test->unlike($thing, qr/$regex/, $name);
$Test->unlike($thing, '/$regex/', $name);
```
Like <Test::More>'s `unlike()`. Checks if $thing **does not match** the given `$regex`.
**cmp\_ok**
```
$Test->cmp_ok($thing, $type, $that, $name);
```
Works just like <Test::More>'s `cmp_ok()`.
```
$Test->cmp_ok($big_num, '!=', $other_big_num);
```
###
Other Testing Methods
These are methods which are used in the course of writing a test but are not themselves tests.
**BAIL\_OUT**
```
$Test->BAIL_OUT($reason);
```
Indicates to the <Test::Harness> that things are going so badly all testing should terminate. This includes running any additional test scripts.
It will exit with 255.
**skip**
```
$Test->skip;
$Test->skip($why);
```
Skips the current test, reporting `$why`.
**todo\_skip**
```
$Test->todo_skip;
$Test->todo_skip($why);
```
Like `skip()`, only it will declare the test as failing and TODO. Similar to
```
print "not ok $tnum # TODO $why\n";
```
###
Test building utility methods
These methods are useful when writing your own test methods.
**maybe\_regex**
```
$Test->maybe_regex(qr/$regex/);
$Test->maybe_regex('/$regex/');
```
This method used to be useful back when Test::Builder worked on Perls before 5.6 which didn't have qr//. Now its pretty useless.
Convenience method for building testing functions that take regular expressions as arguments.
Takes a quoted regular expression produced by `qr//`, or a string representing a regular expression.
Returns a Perl value which may be used instead of the corresponding regular expression, or `undef` if its argument is not recognized.
For example, a version of `like()`, sans the useful diagnostic messages, could be written as:
```
sub laconic_like {
my ($self, $thing, $regex, $name) = @_;
my $usable_regex = $self->maybe_regex($regex);
die "expecting regex, found '$regex'\n"
unless $usable_regex;
$self->ok($thing =~ m/$usable_regex/, $name);
}
```
**is\_fh**
```
my $is_fh = $Test->is_fh($thing);
```
Determines if the given `$thing` can be used as a filehandle.
###
Test style
**level**
```
$Test->level($how_high);
```
How far up the call stack should `$Test` look when reporting where the test failed.
Defaults to 1.
Setting `$Test::Builder::Level` overrides. This is typically useful localized:
```
sub my_ok {
my $test = shift;
local $Test::Builder::Level = $Test::Builder::Level + 1;
$TB->ok($test);
}
```
To be polite to other functions wrapping your own you usually want to increment `$Level` rather than set it to a constant.
**use\_numbers**
```
$Test->use_numbers($on_or_off);
```
Whether or not the test should output numbers. That is, this if true:
```
ok 1
ok 2
ok 3
```
or this if false
```
ok
ok
ok
```
Most useful when you can't depend on the test output order, such as when threads or forking is involved.
Defaults to on.
**no\_diag**
```
$Test->no_diag($no_diag);
```
If set true no diagnostics will be printed. This includes calls to `diag()`.
**no\_ending**
```
$Test->no_ending($no_ending);
```
Normally, Test::Builder does some extra diagnostics when the test ends. It also changes the exit code as described below.
If this is true, none of that will be done.
**no\_header**
```
$Test->no_header($no_header);
```
If set to true, no "1..N" header will be printed.
### Output
Controlling where the test output goes.
It's ok for your test to change where STDOUT and STDERR point to, Test::Builder's default output settings will not be affected.
**diag**
```
$Test->diag(@msgs);
```
Prints out the given `@msgs`. Like `print`, arguments are simply appended together.
Normally, it uses the `failure_output()` handle, but if this is for a TODO test, the `todo_output()` handle is used.
Output will be indented and marked with a # so as not to interfere with test output. A newline will be put on the end if there isn't one already.
We encourage using this rather than calling print directly.
Returns false. Why? Because `diag()` is often used in conjunction with a failing test (`ok() || diag()`) it "passes through" the failure.
```
return ok(...) || diag(...);
```
**note**
```
$Test->note(@msgs);
```
Like `diag()`, but it prints to the `output()` handle so it will not normally be seen by the user except in verbose mode.
**explain**
```
my @dump = $Test->explain(@msgs);
```
Will dump the contents of any references in a human readable format. Handy for things like...
```
is_deeply($have, $want) || diag explain $have;
```
or
```
is_deeply($have, $want) || note explain $have;
```
**output** **failure\_output** **todo\_output**
```
my $filehandle = $Test->output;
$Test->output($filehandle);
$Test->output($filename);
$Test->output(\$scalar);
```
These methods control where Test::Builder will print its output. They take either an open `$filehandle`, a `$filename` to open and write to or a `$scalar` reference to append to. It will always return a `$filehandle`.
**output** is where normal "ok/not ok" test output goes.
Defaults to STDOUT.
**failure\_output** is where diagnostic output on test failures and `diag()` goes. It is normally not read by Test::Harness and instead is displayed to the user.
Defaults to STDERR.
`todo_output` is used instead of `failure_output()` for the diagnostics of a failing TODO test. These will not be seen by the user.
Defaults to STDOUT.
reset\_outputs
```
$tb->reset_outputs;
```
Resets all the output filehandles back to their defaults.
carp
```
$tb->carp(@message);
```
Warns with `@message` but the message will appear to come from the point where the original test function was called (`$tb->caller`).
croak
```
$tb->croak(@message);
```
Dies with `@message` but the message will appear to come from the point where the original test function was called (`$tb->caller`).
###
Test Status and Info
**no\_log\_results** This will turn off result long-term storage. Calling this method will make `details` and `summary` useless. You may want to use this if you are running enough tests to fill up all available memory.
```
Test::Builder->new->no_log_results();
```
There is no way to turn it back on.
**current\_test**
```
my $curr_test = $Test->current_test;
$Test->current_test($num);
```
Gets/sets the current test number we're on. You usually shouldn't have to set this.
If set forward, the details of the missing tests are filled in as 'unknown'. if set backward, the details of the intervening tests are deleted. You can erase history if you really want to.
**is\_passing**
```
my $ok = $builder->is_passing;
```
Indicates if the test suite is currently passing.
More formally, it will be false if anything has happened which makes it impossible for the test suite to pass. True otherwise.
For example, if no tests have run `is_passing()` will be true because even though a suite with no tests is a failure you can add a passing test to it and start passing.
Don't think about it too much.
**summary**
```
my @tests = $Test->summary;
```
A simple summary of the tests so far. True for pass, false for fail. This is a logical pass/fail, so todos are passes.
Of course, test #1 is $tests[0], etc...
**details**
```
my @tests = $Test->details;
```
Like `summary()`, but with a lot more detail.
```
$tests[$test_num - 1] =
{ 'ok' => is the test considered a pass?
actual_ok => did it literally say 'ok'?
name => name of the test (if any)
type => type of test (if any, see below).
reason => reason for the above (if any)
};
```
'ok' is true if Test::Harness will consider the test to be a pass.
'actual\_ok' is a reflection of whether or not the test literally printed 'ok' or 'not ok'. This is for examining the result of 'todo' tests.
'name' is the name of the test.
'type' indicates if it was a special test. Normal tests have a type of ''. Type can be one of the following:
```
skip see skip()
todo see todo()
todo_skip see todo_skip()
unknown see below
```
Sometimes the Test::Builder test counter is incremented without it printing any test output, for example, when `current_test()` is changed. In these cases, Test::Builder doesn't know the result of the test, so its type is 'unknown'. These details for these tests are filled in. They are considered ok, but the name and actual\_ok is left `undef`.
For example "not ok 23 - hole count # TODO insufficient donuts" would result in this structure:
```
$tests[22] = # 23 - 1, since arrays start from 0.
{ ok => 1, # logically, the test passed since its todo
actual_ok => 0, # in absolute terms, it failed
name => 'hole count',
type => 'todo',
reason => 'insufficient donuts'
};
```
**todo**
```
my $todo_reason = $Test->todo;
my $todo_reason = $Test->todo($pack);
```
If the current tests are considered "TODO" it will return the reason, if any. This reason can come from a `$TODO` variable or the last call to `todo_start()`.
Since a TODO test does not need a reason, this function can return an empty string even when inside a TODO block. Use `$Test->in_todo` to determine if you are currently inside a TODO block.
`todo()` is about finding the right package to look for `$TODO` in. It's pretty good at guessing the right package to look at. It first looks for the caller based on `$Level + 1`, since `todo()` is usually called inside a test function. As a last resort it will use `exported_to()`.
Sometimes there is some confusion about where `todo()` should be looking for the `$TODO` variable. If you want to be sure, tell it explicitly what $pack to use.
**find\_TODO**
```
my $todo_reason = $Test->find_TODO();
my $todo_reason = $Test->find_TODO($pack);
```
Like `todo()` but only returns the value of `$TODO` ignoring `todo_start()`.
Can also be used to set `$TODO` to a new value while returning the old value:
```
my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
```
**in\_todo**
```
my $in_todo = $Test->in_todo;
```
Returns true if the test is currently inside a TODO block.
**todo\_start**
```
$Test->todo_start();
$Test->todo_start($message);
```
This method allows you declare all subsequent tests as TODO tests, up until the `todo_end` method has been called.
The `TODO:` and `$TODO` syntax is generally pretty good about figuring out whether or not we're in a TODO test. However, often we find that this is not possible to determine (such as when we want to use `$TODO` but the tests are being executed in other packages which can't be inferred beforehand).
Note that you can use this to nest "todo" tests
```
$Test->todo_start('working on this');
# lots of code
$Test->todo_start('working on that');
# more code
$Test->todo_end;
$Test->todo_end;
```
This is generally not recommended, but large testing systems often have weird internal needs.
We've tried to make this also work with the TODO: syntax, but it's not guaranteed and its use is also discouraged:
```
TODO: {
local $TODO = 'We have work to do!';
$Test->todo_start('working on this');
# lots of code
$Test->todo_start('working on that');
# more code
$Test->todo_end;
$Test->todo_end;
}
```
Pick one style or another of "TODO" to be on the safe side.
`todo_end`
```
$Test->todo_end;
```
Stops running tests as "TODO" tests. This method is fatal if called without a preceding `todo_start` method call.
**caller**
```
my $package = $Test->caller;
my($pack, $file, $line) = $Test->caller;
my($pack, $file, $line) = $Test->caller($height);
```
Like the normal `caller()`, except it reports according to your `level()`.
`$height` will be added to the `level()`.
If `caller()` winds up off the top of the stack it report the highest context.
EXIT CODES
-----------
If all your tests passed, Test::Builder will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run Test::Builder will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255.
So the exit codes are...
```
0 all tests successful
255 test died or all passed but wrong # of tests run
any other number how many failed (including missing or extras)
```
If you fail more than 254 tests, it will be reported as 254.
THREADS
-------
In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is shared by all threads. This means if one thread sets the test number using `current_test()` they will all be effected.
While versions earlier than 5.8.1 had threads they contain too many bugs to support.
Test::Builder is only thread-aware if threads.pm is loaded *before* Test::Builder.
You can directly disable thread support with one of the following:
```
$ENV{T2_NO_IPC} = 1
```
or
```
no Test2::IPC;
```
or
```
Test2::API::test2_ipc_disable()
```
MEMORY
------
An informative hash, accessible via `details()`, is stored for each test you perform. So memory usage will scale linearly with each test run. Although this is not a problem for most test suites, it can become an issue if you do large (hundred thousands to million) combinatorics tests in the same run.
In such cases, you are advised to either split the test file into smaller ones, or use a reverse approach, doing "normal" (code) compares and triggering `fail()` should anything go unexpected.
Future versions of Test::Builder will have a way to turn history off.
EXAMPLES
--------
CPAN can provide the best examples. <Test::Simple>, <Test::More>, <Test::Exception> and <Test::Differences> all use Test::Builder.
SEE ALSO
---------
### INTERNALS
[Test2](test2), <Test2::API>
### LEGACY
<Test::Simple>, <Test::More>
### EXTERNAL
<Test::Harness>
AUTHORS
-------
Original code by chromatic, maintained by Michael G Schwern <[email protected]>
MAINTAINERS
-----------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2002-2008 by chromatic <[email protected]> and Michael G Schwern <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://www.perl.com/perl/misc/Artistic.html*
| programming_docs |
perl Pod::Simple::XMLOutStream Pod::Simple::XMLOutStream
=========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [ABOUT EXTENDING POD](#ABOUT-EXTENDING-POD)
* [SEE ALSO](#SEE-ALSO1)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::XMLOutStream -- turn Pod into XML
SYNOPSIS
--------
```
perl -MPod::Simple::XMLOutStream -e \
"exit Pod::Simple::XMLOutStream->filter(shift)->any_errata_seen" \
thingy.pod
```
DESCRIPTION
-----------
Pod::Simple::XMLOutStream is a subclass of <Pod::Simple> that parses Pod and turns it into XML.
Pod::Simple::XMLOutStream inherits methods from <Pod::Simple>.
SEE ALSO
---------
<Pod::Simple::DumpAsXML> is rather like this class; see its documentation for a discussion of the differences.
<Pod::Simple>, <Pod::Simple::DumpAsXML>, <Pod::SAX>
<Pod::Simple::Subclassing>
The older (and possibly obsolete) libraries <Pod::PXML>, <Pod::XML>
ABOUT EXTENDING POD
--------------------
TODO: An example or two of =extend, then point to Pod::Simple::Subclassing
SEE ALSO
---------
<Pod::Simple>, <Pod::Simple::Text>, <Pod::Spell>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002-2004 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl Devel::PPPort Devel::PPPort
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [Start using Devel::PPPort for XS projects](#Start-using-Devel::PPPort-for-XS-projects)
* [DESCRIPTION](#DESCRIPTION)
+ [Why use ppport.h?](#Why-use-ppport.h?)
+ [How to use ppport.h](#How-to-use-ppport.h)
+ [Running ppport.h](#Running-ppport.h)
* [FUNCTIONS](#FUNCTIONS)
+ [WriteFile](#WriteFile)
+ [GetFileContents](#GetFileContents)
* [COMPATIBILITY](#COMPATIBILITY)
+ [Provided Perl compatibility API](#Provided-Perl-compatibility-API)
+ [Supported Perl API, sorted by version](#Supported-Perl-API,-sorted-by-version)
* [BUGS](#BUGS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Devel::PPPort - Perl/Pollution/Portability
SYNOPSIS
--------
```
Devel::PPPort::WriteFile(); # defaults to ./ppport.h
Devel::PPPort::WriteFile('someheader.h');
# Same as above but retrieve contents rather than write file
my $contents = Devel::PPPort::GetFileContents();
my $contents = Devel::PPPort::GetFileContents('someheader.h');
```
Start using Devel::PPPort for XS projects
------------------------------------------
```
$ cpan Devel::PPPort
$ perl -MDevel::PPPort -e'Devel::PPPort::WriteFile'
$ perl ppport.h --compat-version=5.6.1 --patch=diff.patch *.xs
$ patch -p0 < diff.patch
$ echo ppport.h >>MANIFEST
```
DESCRIPTION
-----------
Perl's API has changed over time, gaining new features, new functions, increasing its flexibility, and reducing the impact on the C namespace environment (reduced pollution). The header file written by this module, typically *ppport.h*, attempts to bring some of the newer Perl API features to older versions of Perl, so that you can worry less about keeping track of old releases, but users can still reap the benefit.
`Devel::PPPort` contains two functions, `WriteFile` and `GetFileContents`. `WriteFile`'s only purpose is to write the *ppport.h* C header file. This file contains a series of macros and, if explicitly requested, functions that allow XS modules to be built using older versions of Perl. Currently, Perl versions from 5.003\_07 to 5.35.9 are supported.
`GetFileContents` can be used to retrieve the file contents rather than writing it out.
This module is used by `h2xs` to write the file *ppport.h*.
###
Why use ppport.h?
You should use *ppport.h* in modern code so that your code will work with the widest range of Perl interpreters possible, without significant additional work.
You should attempt to get older code to fully use *ppport.h*, because the reduced pollution of newer Perl versions is an important thing. It's so important that the old polluting ways of original Perl modules will not be supported very far into the future, and your module will almost certainly break! By adapting to it now, you'll gain compatibility and a sense of having done the electronic ecology some good.
###
How to use ppport.h
Don't direct the users of your module to download `Devel::PPPort`. They are most probably not XS writers. Also, don't make *ppport.h* optional. Rather, just take the most recent copy of *ppport.h* that you can find (e.g. by generating it with the latest `Devel::PPPort` release from CPAN), copy it into your project, adjust your project to use it, test it, and distribute the header along with your module.
It is important to use the most recent version of *ppport.h*. You do need to test before shipping a newer version than you already had. One possible failure is that someone had to convert a backported element from a macro into a function, and actual functions must be enabled with a NEED macro to minimize the possibility of namespace pollution. See [HACKERS](hackers) for details. The developers of `Devel::PPPort` want to hear if there are other problems that arise from using a later *ppport.h*. Use <https://github.com/Dual-Life/Devel-PPPort/issues> to report any.
###
Running ppport.h
But *ppport.h* is more than just a C header. It's also a Perl script that can check your source code. It will suggest hints and portability notes, and can even make suggestions on how to change your code. You can run it like any other Perl program:
```
perl ppport.h [options] [files]
```
It also has embedded documentation, so you can use
```
perldoc ppport.h
```
to find out more about how to use it.
FUNCTIONS
---------
### WriteFile
`WriteFile` takes one optional argument. When called with one argument, it expects to be passed a filename. When called with no arguments, it defaults to the filename *ppport.h*.
The function returns a true value if the file was written successfully. Otherwise it returns a false value.
### GetFileContents
`GetFileContents` behaves like `WriteFile` above, but returns the contents of the would-be file rather than writing it out.
COMPATIBILITY
-------------
*ppport.h* supports Perl versions from 5.003\_07 to 5.35.9 in threaded and non-threaded configurations.
###
Provided Perl compatibility API
The header file written by this module, typically *ppport.h*, provides access to the following elements of the Perl API that are not otherwise available in Perl releases older than when the elements were first introduced. (Note that many of these are not supported all the way back to 5.003\_07, but it may be that they are supported back as far as you need; see ["Supported Perl API, sorted by version"](#Supported-Perl-API%2C-sorted-by-version) for that information.)
```
_aMY_CXT
aMY_CXT
aMY_CXT_
__ASSERT_
ASSUME
aTHX
aTHX_
aTHXR
aTHXR_
av_count
AvFILLp
av_tindex
av_top_index
BOM_UTF8
boolSV
call_argv
caller_cx
call_method
call_pv
call_sv
C_ARRAY_END
C_ARRAY_LENGTH
cBOOL
ckWARN
ckWARN2
ckWARN2_d
ckWARN3
ckWARN3_d
ckWARN4
ckWARN4_d
ckWARN_d
ck_warner
ck_warner_d
CopFILE
CopFILEAV
CopFILEGV
CopFILEGV_set
CopFILE_set
CopFILESV
CopSTASH
CopSTASH_eq
CopSTASHPV
CopSTASHPV_set
CopSTASH_set
CopyD
CPERLscope
croak_memory_wrap
croak_nocontext
croak_no_modify
croak_sv
croak_xs_usage
dAX
dAXMARK
DECLARATION_FOR_LC_NUMERIC_MANIPULATION
DEFSV
DEFSV_set
die_sv
dITEMS
dMY_CXT
dMY_CXT_SV
dNOOP
dTHR
dTHX
dTHXa
dTHXoa
dTHXR
dUNDERBAR
dVAR
dXCPT
dXSTARG
END_EXTERN_C
ERRSV
eval_pv
eval_sv
EXTERN_C
foldEQ_utf8
get_av
get_cv
get_cvn_flags
get_cvs
get_hv
get_sv
G_METHOD
G_RETHROW
grok_bin
grok_hex
grok_number
GROK_NUMERIC_RADIX
grok_numeric_radix
grok_oct
gv_fetchpvn_flags
gv_fetchpvs
gv_fetchsv
gv_init_pvn
gv_stashpvn
gv_stashpvs
GvSVn
HEf_SVKEY
HeUTF8
hv_fetchs
HvNAME_get
HvNAMELEN_get
hv_stores
IN_LOCALE
IN_LOCALE_COMPILETIME
IN_LOCALE_RUNTIME
IN_PERL_COMPILETIME
INT2PTR
isALNUM
isALNUM_A
isALNUMC
isALNUMC_A
isALNUMC_L1
isALPHA
isALPHA_A
isALPHA_L1
isALPHA_LC_utf8_safe
isALPHANUMERIC
isALPHANUMERIC_A
isALPHANUMERIC_L1
isALPHANUMERIC_LC
isALPHANUMERIC_LC_utf8_safe
isALPHANUMERIC_utf8_safe
isALPHANUMERIC_uvchr
isALPHA_utf8_safe
isALPHA_uvchr
isASCII
isASCII_A
isASCII_L1
isASCII_LC
isASCII_utf8_safe
isASCII_uvchr
isBLANK
isBLANK_A
isBLANK_L1
isBLANK_LC
isBLANK_LC_utf8_safe
isBLANK_utf8_safe
isBLANK_uvchr
isCNTRL
isCNTRL_A
isCNTRL_L1
isCNTRL_LC_utf8_safe
isCNTRL_utf8_safe
isCNTRL_uvchr
isDIGIT
isDIGIT_A
isDIGIT_L1
isDIGIT_LC_utf8_safe
isDIGIT_utf8_safe
isDIGIT_uvchr
isGRAPH
isGRAPH_A
isGRAPH_L1
isGRAPH_LC_utf8_safe
isGRAPH_utf8_safe
isGRAPH_uvchr
isGV_with_GP
isIDCONT
isIDCONT_A
isIDCONT_L1
isIDCONT_LC
isIDCONT_LC_utf8_safe
isIDCONT_utf8_safe
isIDCONT_uvchr
isIDFIRST
isIDFIRST_A
isIDFIRST_L1
isIDFIRST_LC
isIDFIRST_LC_utf8_safe
isIDFIRST_utf8_safe
isIDFIRST_uvchr
is_invariant_string
isLOWER
isLOWER_A
isLOWER_L1
isLOWER_LC_utf8_safe
isLOWER_utf8_safe
isLOWER_uvchr
IS_NUMBER_GREATER_THAN_UV_MAX
IS_NUMBER_INFINITY
IS_NUMBER_IN_UV
IS_NUMBER_NAN
IS_NUMBER_NEG
IS_NUMBER_NOT_INT
isOCTAL
isOCTAL_A
isOCTAL_L1
isPRINT
isPRINT_A
isPRINT_L1
isPRINT_LC_utf8_safe
isPRINT_utf8_safe
isPRINT_uvchr
isPSXSPC
isPSXSPC_A
isPSXSPC_L1
isPSXSPC_LC_utf8_safe
isPSXSPC_utf8_safe
isPSXSPC_uvchr
isPUNCT
isPUNCT_A
isPUNCT_L1
isPUNCT_LC_utf8_safe
isPUNCT_utf8_safe
isPUNCT_uvchr
isSPACE
isSPACE_A
isSPACE_L1
isSPACE_LC_utf8_safe
isSPACE_utf8_safe
isSPACE_uvchr
isUPPER
isUPPER_A
isUPPER_L1
isUPPER_LC_utf8_safe
isUPPER_utf8_safe
isUPPER_uvchr
isUTF8_CHAR
is_utf8_invariant_string
isWORDCHAR
isWORDCHAR_A
isWORDCHAR_L1
isWORDCHAR_LC
isWORDCHAR_LC_utf8_safe
isWORDCHAR_utf8_safe
isWORDCHAR_uvchr
isXDIGIT
isXDIGIT_A
isXDIGIT_L1
isXDIGIT_LC
isXDIGIT_LC_utf8_safe
isXDIGIT_utf8_safe
isXDIGIT_uvchr
IVdf
IVSIZE
IVTYPE
LATIN1_TO_NATIVE
LC_NUMERIC_LOCK
LC_NUMERIC_UNLOCK
LIKELY
load_module
LOCK_LC_NUMERIC_STANDARD
LOCK_NUMERIC_STANDARD
memCHRs
memEQ
memEQs
memNE
memNEs
mess
mess_nocontext
mess_sv
mg_findext
MoveD
mPUSHi
mPUSHn
mPUSHp
mPUSHs
mPUSHu
MUTABLE_AV
MUTABLE_CV
MUTABLE_GV
MUTABLE_HV
MUTABLE_IO
MUTABLE_PTR
MUTABLE_SV
mXPUSHi
mXPUSHn
mXPUSHp
mXPUSHs
mXPUSHu
MY_CXT
MY_CXT_CLONE
MY_CXT_INIT
my_snprintf
my_sprintf
my_strlcat
my_strlcpy
my_strnlen
NATIVE_TO_LATIN1
NATIVE_TO_UNI
newCONSTSUB
newRV_inc
newRV_noinc
newSVpvn
newSVpvn_flags
newSVpvn_share
newSVpvn_utf8
newSVpvs
newSVpvs_flags
newSVpvs_share
newSVsv_flags
newSVsv_nomg
newSV_type
newSVuv
Newx
Newxc
Newxz
NOOP
NOT_REACHED
NUM2PTR
NVef
NVff
NVgf
NVTYPE
OpHAS_SIBLING
OpLASTSIB_set
OpMAYBESIB_set
OpMORESIB_set
OpSIBLING
packWARN
packWARN2
packWARN3
packWARN4
PERL_ABS
PERL_ARGS_ASSERT_CROAK_XS_USAGE
Perl_ck_warner
Perl_ck_warner_d
Perl_croak_no_modify
PERL_HASH
PERL_INT_MAX
PERL_INT_MIN
PERLIO_FUNCS_CAST
PERLIO_FUNCS_DECL
PERL_LONG_MAX
PERL_LONG_MIN
PERL_MAGIC_arylen
PERL_MAGIC_backref
PERL_MAGIC_bm
PERL_MAGIC_collxfrm
PERL_MAGIC_dbfile
PERL_MAGIC_dbline
PERL_MAGIC_defelem
PERL_MAGIC_env
PERL_MAGIC_envelem
PERL_MAGIC_ext
PERL_MAGIC_fm
PERL_MAGIC_glob
PERL_MAGIC_isa
PERL_MAGIC_isaelem
PERL_MAGIC_mutex
PERL_MAGIC_nkeys
PERL_MAGIC_overload
PERL_MAGIC_overload_elem
PERL_MAGIC_overload_table
PERL_MAGIC_pos
PERL_MAGIC_qr
PERL_MAGIC_regdata
PERL_MAGIC_regdatum
PERL_MAGIC_regex_global
PERL_MAGIC_shared
PERL_MAGIC_shared_scalar
PERL_MAGIC_sig
PERL_MAGIC_sigelem
PERL_MAGIC_substr
PERL_MAGIC_sv
PERL_MAGIC_taint
PERL_MAGIC_tied
PERL_MAGIC_tiedelem
PERL_MAGIC_tiedscalar
PERL_MAGIC_utf8
PERL_MAGIC_uvar
PERL_MAGIC_uvar_elem
PERL_MAGIC_vec
PERL_MAGIC_vstring
PERL_PV_ESCAPE_ALL
PERL_PV_ESCAPE_FIRSTCHAR
PERL_PV_ESCAPE_NOBACKSLASH
PERL_PV_ESCAPE_NOCLEAR
PERL_PV_ESCAPE_QUOTE
PERL_PV_ESCAPE_RE
PERL_PV_ESCAPE_UNI
PERL_PV_ESCAPE_UNI_DETECT
PERL_PV_PRETTY_DUMP
PERL_PV_PRETTY_ELLIPSES
PERL_PV_PRETTY_LTGT
PERL_PV_PRETTY_NOCLEAR
PERL_PV_PRETTY_QUOTE
PERL_PV_PRETTY_REGPROP
PERL_QUAD_MAX
PERL_QUAD_MIN
PERL_SCAN_ALLOW_UNDERSCORES
PERL_SCAN_DISALLOW_PREFIX
PERL_SCAN_GREATER_THAN_UV_MAX
PERL_SCAN_SILENT_ILLDIGIT
PERL_SHORT_MAX
PERL_SHORT_MIN
PERL_SIGNALS_UNSAFE_FLAG
PERL_STATIC_INLINE
PERL_UCHAR_MAX
PERL_UCHAR_MIN
PERL_UINT_MAX
PERL_UINT_MIN
PERL_ULONG_MAX
PERL_ULONG_MIN
PERL_UNUSED_ARG
PERL_UNUSED_CONTEXT
PERL_UNUSED_DECL
PERL_UNUSED_RESULT
PERL_UNUSED_VAR
PERL_UQUAD_MAX
PERL_UQUAD_MIN
PERL_USE_GCC_BRACE_GROUPS
PERL_USHORT_MAX
PERL_USHORT_MIN
PERL_VERSION_EQ
PERL_VERSION_GE
PERL_VERSION_GT
PERL_VERSION_LE
PERL_VERSION_LT
PERL_VERSION_NE
Perl_warner
Perl_warner_nocontext
PL_bufend
PL_bufptr
PL_compiling
PL_copline
PL_curcop
PL_curstash
PL_DBsignal
PL_DBsingle
PL_DBsub
PL_DBtrace
PL_debstash
PL_defgv
PL_diehook
PL_dirty
PL_dowarn
PL_errgv
PL_error_count
PL_expect
PL_hexdigit
PL_hints
PL_in_my
PL_in_my_stash
PL_laststatval
PL_lex_state
PL_lex_stuff
PL_linestr
PL_mess_sv
PL_na
PL_no_modify
PL_parser
PL_perldb
PL_perl_destruct_level
PL_ppaddr
PL_rsfp
PL_rsfp_filters
PL_signals
PL_stack_base
PL_stack_sp
PL_statcache
PL_stdingv
PL_Sv
PL_sv_arenaroot
PL_sv_no
PL_sv_undef
PL_sv_yes
PL_tainted
PL_tainting
PL_tokenbuf
PL_Xpv
_pMY_CXT
pMY_CXT
pMY_CXT_
Poison
PoisonFree
PoisonNew
PoisonWith
pTHX
pTHX_
PTR2IV
PTR2nat
PTR2NV
PTR2ul
PTR2UV
PTRV
PUSHmortal
PUSHu
pv_display
pv_escape
pv_pretty
REPLACEMENT_CHARACTER_UTF8
RESTORE_LC_NUMERIC
SAVE_DEFSV
START_EXTERN_C
START_MY_CXT
start_subparse
STMT_END
STMT_START
STORE_LC_NUMERIC_SET_STANDARD
STORE_NUMERIC_SET_STANDARD
STR_WITH_LEN
sv_2pvbyte
sv_2pvbyte_nolen
sv_2pv_flags
sv_2pv_nolen
sv_2uv
sv_catpvf_mg
sv_catpvf_mg_nocontext
sv_catpv_mg
sv_catpvn_mg
sv_catpvn_nomg
sv_catpvs
sv_catsv_mg
sv_catsv_nomg
SV_CONST_RETURN
SV_COW_DROP_PV
SV_COW_SHARED_HASH_KEYS
SVf
SVfARG
SVf_UTF8
SvGETMAGIC
SV_GMAGIC
SV_HAS_TRAILING_NUL
SV_IMMEDIATE_UNREF
SvIV_nomg
sv_len_utf8
sv_len_utf8_nomg
sv_magic_portable
SvMAGIC_set
sv_mortalcopy_flags
SV_MUTABLE_RETURN
SV_NOSTEAL
SvNV_nomg
SvPVbyte
SvPVCLEAR
SvPV_const
SvPV_flags
SvPV_flags_const
SvPV_flags_const_nolen
SvPV_flags_mutable
SvPV_force
SvPV_force_flags
SvPV_force_flags_mutable
SvPV_force_flags_nolen
SvPV_force_mutable
SvPV_force_nolen
SvPV_force_nomg
SvPV_force_nomg_nolen
SvPV_mutable
sv_pvn_force_flags
sv_pvn_nomg
SvPV_nolen
SvPV_nolen_const
SvPV_nomg
SvPV_nomg_const
SvPV_nomg_const_nolen
SvPV_nomg_nolen
SvPV_renew
SvPVX_const
SvPVX_mutable
SvPVx_nolen_const
SvREFCNT_inc
SvREFCNT_inc_NN
SvREFCNT_inc_simple
SvREFCNT_inc_simple_NN
SvREFCNT_inc_simple_void
SvREFCNT_inc_simple_void_NN
SvREFCNT_inc_void
SvREFCNT_inc_void_NN
SvRV_set
SvRX
SvRXOK
sv_setiv_mg
sv_setnv_mg
sv_setpvf_mg
sv_setpvf_mg_nocontext
sv_setpv_mg
sv_setpvn_mg
sv_setpvs
sv_setsv_flags
sv_setsv_mg
sv_setsv_nomg
sv_setuv
sv_setuv_mg
SvSHARED_HASH
SV_SMAGIC
SvSTASH_set
SvTRUE_nomg
sv_unmagicext
SvUOK
sv_usepvn_mg
SvUTF8
SV_UTF8_NO_ENCODING
sv_uv
SvUV
SvUV_nomg
SvUV_set
SvUVX
SvUVx
SvUVXx
sv_vcatpvf
sv_vcatpvf_mg
sv_vsetpvf
sv_vsetpvf_mg
SvVSTRING_mg
switch_to_global_locale
sync_locale
toFOLD_utf8_safe
toFOLD_uvchr
toLOWER_utf8_safe
toLOWER_uvchr
toTITLE_utf8_safe
toTITLE_uvchr
toUPPER_utf8_safe
toUPPER_uvchr
UNDERBAR
UNICODE_REPLACEMENT
UNI_TO_NATIVE
UNLIKELY
UNLOCK_LC_NUMERIC_STANDARD
UNLOCK_NUMERIC_STANDARD
UTF8_CHK_SKIP
UTF8f
UTF8fARG
UTF8_IS_INVARIANT
UTF8_MAXBYTES
UTF8_MAXBYTES_CASE
UTF8_SAFE_SKIP
UTF8_SKIP
utf8_to_uvchr
utf8_to_uvchr_buf
UVCHR_IS_INVARIANT
UVCHR_SKIP
UVof
UVSIZE
UVTYPE
UVuf
UVXf
UVxf
vload_module
vmess
vnewSVpvf
vwarner
WARN_ALL
WARN_AMBIGUOUS
WARN_ASSERTIONS
WARN_BAREWORD
WARN_CLOSED
WARN_CLOSURE
WARN_DEBUGGING
WARN_DEPRECATED
WARN_DIGIT
warner
WARN_EXEC
WARN_EXITING
WARN_GLOB
WARN_INPLACE
WARN_INTERNAL
WARN_IO
WARN_LAYER
WARN_MALLOC
WARN_MISC
WARN_NEWLINE
warn_nocontext
WARN_NUMERIC
WARN_ONCE
WARN_OVERFLOW
WARN_PACK
WARN_PARENTHESIS
WARN_PIPE
WARN_PORTABLE
WARN_PRECEDENCE
WARN_PRINTF
WARN_PROTOTYPE
WARN_QW
WARN_RECURSION
WARN_REDEFINE
WARN_REGEXP
WARN_RESERVED
WARN_SEMICOLON
WARN_SEVERE
WARN_SIGNAL
WARN_SUBSTR
warn_sv
WARN_SYNTAX
WARN_TAINT
WARN_THREADS
WARN_UNINITIALIZED
WARN_UNOPENED
WARN_UNPACK
WARN_UNTIE
WARN_UTF8
WARN_VOID
WIDEST_UTYPE
XCPT_CATCH
XCPT_RETHROW
XCPT_TRY_END
XCPT_TRY_START
XPUSHmortal
XPUSHu
XSprePUSH
XSPROTO
XSRETURN
XSRETURN_UV
XST_mUV
ZeroD
```
###
Supported Perl API, sorted by version
The table in this section lists all the Perl API elements available, sorted by the version in which support starts. This includes all the elements that *ppport.h* helps out with, as well as those elements that it doesn't.
In some cases, it doesn't make practical sense for elements to be supported earlier than they already are. For example, UTF-8 functionality isn't provided prior to the release where it was first introduced.
But in other cases, it just is that no one has implemented support yet. Patches welcome! Some elements are ported backward for some releases, but not all the way to 5.003\_07.
If an element, call it ELEMENT, is not on this list, try using this command to find out why:
```
perl ppport.h --api-info=ELEMENT
```
A few of the entries in the list below are marked as DEPRECATED. You should not use these for new code, and should be converting existing uses to use something better.
Some of the entries in the list are marked as "experimental". This means these should not generally be used. They may be removed or changed without notice. You can ask why they are experimental by sending email to <mailto:[email protected]>.
And some of the entries are marked as "undocumented". This means that they aren't necessarily considered stable, and could be changed or removed in some future release without warning. It is therefore a bad idea to use them without further checking. It could be that these are considered to be for perl core use only; or it could be, though, that `Devel::PPPort` doesn't know where to find their documentation, or that it's just an oversight that they haven't been documented. If you want to use one, and potentially have it backported, first send mail to <mailto:[email protected]>.
perl 5.35.9
```
NV_ZERO_IS_ALLBITS_ZERO
PERL_INC_VERSION_LIST
sv_numeq
sv_numeq_flags
sv_streq
sv_streq_flags
USE_C_BACKTRACE
WARN_EXPERIMENTAL__ARGS_ARRAY_WITH_SIGNATURES
WARN_EXPERIMENTAL__BUILTIN
```
perl 5.35.8
```
op_wrap_finally (marked experimental)
```
perl 5.35.7
```
phase_name
```
perl 5.35.6
```
CopFILEAVn
sv_setpvn_fresh
```
perl 5.35.5
```
SAVESTRLEN
WARN_EXPERIMENTAL__FOR_LIST
```
perl 5.35.4
```
newDEFEROP (marked experimental)
PERL_THREAD_LOCAL
ST_DEV_SIGN
ST_DEV_SIZE
SvIsBOOL
sv_setbool
sv_setbool_mg
sv_setrv_inc
sv_setrv_inc_mg
sv_setrv_noinc
sv_setrv_noinc_mg
WARN_EXPERIMENTAL__DEFER
```
perl 5.35.1
```
av_new_alloc
HAS_FFS
HAS_FFSL
HAS_NL_LANGINFO_L
HAS_NON_INT_BITFIELDS
HAS_STRXFRM_L
newAV_alloc_x
newAV_alloc_xz
```
perl 5.33.8
```
cophh_exists_pv (marked experimental)
cophh_exists_pvn (marked experimental)
cophh_exists_pvs (marked experimental)
cophh_exists_sv (marked experimental)
cop_hints_exists_pv
cop_hints_exists_pvn
cop_hints_exists_pvs
cop_hints_exists_sv
```
perl 5.33.7
```
newTRYCATCHOP (marked experimental)
WARN_EXPERIMENTAL__TRY
```
perl 5.33.5
```
GETENV_PRESERVES_OTHER_THREAD
pad_compname_type (DEPRECATED)
```
perl 5.33.2
```
pack_cat (DEPRECATED)
```
perl 5.32.1
```
GDBMNDBM_H_USES_PROTOTYPES
HAS_DBMINIT_PROTO
HAS_SOCKADDR_STORAGE
I_DBM
I_NDBM
NDBM_H_USES_PROTOTYPES
```
perl 5.31.9
```
UNI_DISPLAY_BACKSPACE
```
perl 5.31.7
```
HASATTRIBUTE_ALWAYS_INLINE
HAS_ISLESS
HAS_WCRTOMB
sv_isa_sv (marked experimental)
WARN_EXPERIMENTAL__ISA
```
perl 5.31.5
```
isALPHANUMERIC_utf8
isALPHA_utf8
isASCII_utf8
isBLANK_utf8
isCNTRL_utf8
isDIGIT_utf8
isGRAPH_utf8
isIDCONT_utf8
isIDFIRST_utf8
isLOWER_utf8
isPRINT_utf8
isPSXSPC_utf8
isPUNCT_utf8
isSPACE_utf8
isUPPER_utf8
isWORDCHAR_utf8
isXDIGIT_utf8
toFOLD_utf8
toLOWER_utf8
toTITLE_utf8
toUPPER_utf8
```
perl 5.31.4
```
cop_fetch_label (marked experimental)
cop_store_label (marked experimental)
sv_2pvbyte_flags (undocumented)
sv_2pvutf8_flags (undocumented)
sv_nolocking (DEPRECATED)
SvPVbyte_nomg
SvPVbyte_or_null
SvPVbyte_or_null_nomg
SvPVutf8_nomg
SvPVutf8_or_null
SvPVutf8_or_null_nomg
sv_utf8_downgrade_flags
sv_utf8_downgrade_nomg
```
perl 5.31.3
```
parse_subsignature (marked experimental)
SANE_ERRSV
STORE_LC_NUMERIC_SET_TO_NEEDED_IN
WITH_LC_NUMERIC_SET_TO_NEEDED
WITH_LC_NUMERIC_SET_TO_NEEDED_IN
```
perl 5.29.10
```
my_strtod
Strtod
```
perl 5.29.9
```
HAS_TOWLOWER
HAS_TOWUPPER
I_WCTYPE
WARN_EXPERIMENTAL__PRIVATE_USE
WARN_EXPERIMENTAL__UNIPROP_WILDCARDS
WARN_EXPERIMENTAL__VLB
```
perl 5.27.11
```
HAS_DUPLOCALE
HAS_STRTOD_L
```
perl 5.27.9
```
PERL_MAGIC_nonelem
thread_locale_init (marked experimental) (undocumented)
thread_locale_term (marked experimental) (undocumented)
utf8n_to_uvchr_msgs
uvchr_to_utf8_flags_msgs
WARN_EXPERIMENTAL__ALPHA_ASSERTIONS
```
perl 5.27.8
```
HAS_ACCEPT4
HAS_DUP3
HAS_MKOSTEMP
HAS_PIPE2
newWHENOP
WARN_EXPERIMENTAL__SCRIPT_RUN
```
perl 5.27.7
```
WARN_SHADOW
```
perl 5.27.6
```
HAS_MBRLEN
HAS_MBRTOWC
HAS_NANOSLEEP
HAS_STRNLEN
HAS_STRTOLD_L
HAS_THREAD_SAFE_NL_LANGINFO_L
I_WCHAR
wrap_keyword_plugin (marked experimental)
```
perl 5.27.5
```
HAS_MEMRCHR
```
perl 5.27.4
```
HAS_FCHMODAT
HAS_LINKAT
HAS_OPENAT
HAS_RENAMEAT
HAS_UNLINKAT
mg_freeext
Perl_langinfo
sv_rvunweaken
```
perl 5.27.3
```
cv_get_call_checker_flags
PL_sv_zero
sv_string_from_errnum
```
perl 5.27.2
```
Perl_setlocale
UNICODE_DISALLOW_PERL_EXTENDED
UNICODE_WARN_PERL_EXTENDED
UTF8_DISALLOW_PERL_EXTENDED
UTF8_GOT_PERL_EXTENDED
UTF8_WARN_PERL_EXTENDED
```
perl 5.27.1
```
is_utf8_invariant_string_loc
```
perl 5.25.11
```
DEFAULT_INC_EXCLUDES_DOT
```
perl 5.25.10
```
op_class
```
perl 5.25.9
```
isASCII_LC_utf8_safe
```
perl 5.25.8
```
sv_set_undef
```
perl 5.25.7
```
CLEAR_ERRSV
DOUBLE_HAS_NEGATIVE_ZERO
DOUBLE_HAS_SUBNORMALS
DOUBLE_STYLE_IEEE
LONG_DOUBLE_STYLE_IEEE
LONG_DOUBLE_STYLE_IEEE_EXTENDED
utf8_hop_back
utf8_hop_forward
utf8_hop_safe
```
perl 5.25.6
```
DOUBLE_IS_CRAY_SINGLE_64_BIT
DOUBLE_IS_IBM_DOUBLE_64_BIT
DOUBLE_IS_IBM_SINGLE_32_BIT
is_c9strict_utf8_string
is_c9strict_utf8_string_loc
is_c9strict_utf8_string_loclen
is_strict_utf8_string
is_strict_utf8_string_loc
is_strict_utf8_string_loclen
is_utf8_fixed_width_buf_flags
is_utf8_fixed_width_buf_loc_flags
is_utf8_fixed_width_buf_loclen_flags
is_utf8_string_flags
is_utf8_string_loc_flags
is_utf8_string_loclen_flags
SvPVCLEAR
sv_setpv_bufsize
UTF8_GOT_CONTINUATION
UTF8_GOT_EMPTY
UTF8_GOT_LONG
UTF8_GOT_NONCHAR
UTF8_GOT_NON_CONTINUATION
UTF8_GOT_OVERFLOW
UTF8_GOT_SHORT
UTF8_GOT_SUPER
UTF8_GOT_SURROGATE
utf8n_to_uvchr_error
```
perl 5.25.5
```
isC9_STRICT_UTF8_CHAR
isSTRICT_UTF8_CHAR
isUTF8_CHAR_flags
is_utf8_valid_partial_char
is_utf8_valid_partial_char_flags
UNICODE_DISALLOW_ILLEGAL_C9_INTERCHANGE
UNICODE_WARN_ILLEGAL_C9_INTERCHANGE
UTF8_DISALLOW_ILLEGAL_C9_INTERCHANGE
UTF8_WARN_ILLEGAL_C9_INTERCHANGE
```
perl 5.25.4
```
HAS_GAI_STRERROR
I_XLOCALE
LONG_DOUBLE_IS_VAX_H_FLOAT
```
perl 5.25.3
```
DOUBLE_HAS_INF
DOUBLE_HAS_NAN
DOUBLE_IS_VAX_D_FLOAT
DOUBLE_IS_VAX_F_FLOAT
DOUBLE_IS_VAX_G_FLOAT
hv_bucket_ratio (marked experimental)
WARN_EXPERIMENTAL__DECLARED_REFS
```
perl 5.25.2
```
HAS_STRERROR_L
```
perl 5.25.1
```
op_parent
```
perl 5.24.0
```
HAS_MEMMEM
```
perl 5.23.9
```
HAS_FREELOCALE
HAS_NEWLOCALE
HAS_USELOCALE
```
perl 5.23.8
```
clear_defarray (undocumented)
HAS_SIGINFO_SI_ADDR
HAS_SIGINFO_SI_BAND
HAS_SIGINFO_SI_ERRNO
HAS_SIGINFO_SI_PID
HAS_SIGINFO_SI_STATUS
HAS_SIGINFO_SI_UID
HAS_SIGINFO_SI_VALUE
leave_adjust_stacks (marked experimental) (undocumented)
Perl_savetmps (undocumented)
```
perl 5.23.6
```
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_BE
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BE_LE
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_BE
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LE_LE
UNICODE_DISALLOW_ABOVE_31_BIT
UNICODE_WARN_ABOVE_31_BIT
```
perl 5.23.5
```
HAS_FSTATFS
HAS_FSTATVFS
HAS_GETMNTENT
HAS_HASMNTOPT
HAS_STRUCT_STATFS
HAS_STRUCT_STATFS_F_FLAGS
HAS_USTAT
I_MNTENT
I_SYS_MOUNT
I_SYS_STATFS
I_SYS_STATVFS
I_SYS_VFS
I_USTAT
sv_ref
```
perl 5.23.2
```
INT64_C
UINT64_C
UTF8_IS_NONCHAR
UTF8_IS_SUPER
UTF8_IS_SURROGATE
```
perl 5.23.0
```
DOUBLEINFBYTES
DOUBLEMANTBITS
DOUBLENANBYTES
LONGDBLINFBYTES
LONGDBLMANTBITS
LONGDBLNANBYTES
NVMANTBITS
```
perl 5.21.10
```
DECLARATION_FOR_LC_NUMERIC_MANIPULATION
RESTORE_LC_NUMERIC
STORE_LC_NUMERIC_FORCE_TO_UNDERLYING
STORE_LC_NUMERIC_SET_TO_NEEDED
```
perl 5.21.9
```
HAS_LLRINTL
HAS_LLROUNDL
HAS_LRINTL
HAS_LROUNDL
WARN_EXPERIMENTAL__BITWISE
```
perl 5.21.8
```
sv_get_backrefs (marked experimental)
WARN_EXPERIMENTAL__CONST_ATTR
WARN_EXPERIMENTAL__RE_STRICT
```
perl 5.21.7
```
HAS_REGCOMP
HAS_STAT
I_GDBM
I_GDBMNDBM
newPADNAMELIST (marked experimental)
newPADNAMEouter (marked experimental)
newPADNAMEpvn (marked experimental)
newUNOP_AUX
padnamelist_fetch (marked experimental)
PadnamelistREFCNT (marked experimental)
PadnamelistREFCNT_dec (marked experimental)
padnamelist_store (marked experimental)
PadnameREFCNT (marked experimental)
PadnameREFCNT_dec (marked experimental)
PADNAMEt_OUTER
```
perl 5.21.6
```
block_end
block_start
DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
DOUBLE_IS_IEEE_754_32_BIT_BIG_ENDIAN
DOUBLE_IS_IEEE_754_32_BIT_LITTLE_ENDIAN
DOUBLE_IS_IEEE_754_64_BIT_BIG_ENDIAN
DOUBLE_IS_IEEE_754_64_BIT_LITTLE_ENDIAN
DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_BE_LE
DOUBLE_IS_IEEE_754_64_BIT_MIXED_ENDIAN_LE_BE
DOUBLE_IS_UNKNOWN_FORMAT
DOUBLEKIND
HAS_ASINH
HAS_ATANH
HAS_CBRT
HAS_COPYSIGN
HAS_ERF
HAS_ERFC
HAS_EXP2
HAS_EXPM1
HAS_FDIM
HAS_FMA
HAS_FMAX
HAS_FMIN
HAS_HYPOT
HAS_ILOGB
HAS_ISNORMAL
HAS_LGAMMA
HAS_LGAMMA_R
HAS_LLRINT
HAS_LLROUND
HAS_LOG1P
HAS_LOG2
HAS_LOGB
HAS_LRINT
HAS_LROUND
HAS_NAN
HAS_NEARBYINT
HAS_NEXTAFTER
HAS_NEXTTOWARD
HAS_REMAINDER
HAS_REMQUO
HAS_RINT
HAS_ROUND
HAS_SCALBN
HAS_TGAMMA
HAS_TRUNC
intro_my
newDEFSVOP
op_convert_list
WARN_LOCALE
```
perl 5.21.5
```
cv_name
CV_NAME_NOTQUAL
HAS_LC_MONETARY_2008
newMETHOP
newMETHOP_named
PERL_MAGIC_debugvar
PERL_MAGIC_lvref
SV_CATBYTES
SV_CATUTF8
WARN_EXPERIMENTAL__REFALIASING
```
perl 5.21.4
```
CALL_CHECKER_REQUIRE_GV
cv_set_call_checker_flags
grok_infnan
HAS_ACOSH
HAS_FEGETROUND
HAS_FPCLASSIFY
HAS_ISFINITE
HAS_ISINFL
HAS_J0
HAS_J0L
HAS_TRUNCL
I_FENV
isinfnan
I_STDINT
Perl_acos
Perl_asin
Perl_atan
Perl_cosh
Perl_log10
Perl_sinh
Perl_tan
Perl_tanh
```
perl 5.21.3
```
HAS_LDEXPL
LONG_DOUBLE_IS_DOUBLE
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_BIG_ENDIAN
LONG_DOUBLE_IS_DOUBLEDOUBLE_128_BIT_LITTLE_ENDIAN
LONG_DOUBLE_IS_IEEE_754_128_BIT_BIG_ENDIAN
LONG_DOUBLE_IS_IEEE_754_128_BIT_LITTLE_ENDIAN
LONG_DOUBLE_IS_UNKNOWN_FORMAT
LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN
LONG_DOUBLEKIND
Perl_ldexp
```
perl 5.21.2
```
grok_number_flags
op_sibling_splice
PERL_SCAN_TRAILING
WARN_MISSING
WARN_REDUNDANT
```
perl 5.21.1
```
HAS_BACKTRACE
HAS_DLADDR
HAS_PTRDIFF_T
HAS_WCSCMP
HAS_WCSXFRM
I_EXECINFO
markstack_grow (undocumented)
```
perl 5.19.10
```
OP_TYPE_IS_OR_WAS
```
perl 5.19.9
```
WARN_EXPERIMENTAL__SIGNATURES
```
perl 5.19.7
```
OP_TYPE_IS
```
perl 5.19.5
```
WARN_EXPERIMENTAL__POSTDEREF
```
perl 5.19.4
```
IS_SAFE_SYSCALL
is_safe_syscall
WARN_SYSCALLS
```
perl 5.19.3
```
PERL_EXIT_ABORT
PERL_EXIT_WARN
sv_pos_b2u_flags
```
perl 5.19.2
```
G_METHOD_NAMED
```
perl 5.19.1
```
toFOLD
toFOLD_A
toLOWER_A
toLOWER_L1
toTITLE
toTITLE_A
toUPPER_A
```
perl 5.18.0
```
hv_rand_set (undocumented)
```
perl 5.17.11
```
WARN_EXPERIMENTAL__SMARTMATCH
```
perl 5.17.8
```
isALPHANUMERIC_LC_uvchr
isIDCONT_LC_uvchr
WARN_EXPERIMENTAL__REGEX_SETS
```
perl 5.17.7
```
isALNUMC_LC_uvchr
isASCII_LC_uvchr
isBLANK_LC_uvchr
isPSXSPC_LC_uvchr
isWORDCHAR_LC_uvchr
isXDIGIT_LC_uvchr
SvREFCNT_dec_NN
SvTRUE_NN
SvTRUE_nomg_NN
```
perl 5.17.6
```
READ_XDIGIT
```
perl 5.17.5
```
WARN_EXPERIMENTAL__LEXICAL_SUBS
```
perl 5.17.4
```
GV_SUPER
HAS_IP_MREQ_SOURCE
newMYSUB (undocumented)
newSVpadname (marked experimental)
PadARRAY (marked experimental)
PadlistARRAY (marked experimental)
PadlistMAX (marked experimental)
PadlistNAMES (marked experimental)
PadlistNAMESARRAY (marked experimental)
PadlistNAMESMAX (marked experimental)
PadlistREFCNT (marked experimental)
PadMAX (marked experimental)
PadnameLEN (marked experimental)
PadnamelistARRAY (marked experimental)
PadnamelistMAX (marked experimental)
PadnamePV (marked experimental)
PadnameSV (marked experimental)
PadnameUTF8 (marked experimental)
PL_comppad_name (marked experimental)
WARN_EXPERIMENTAL
```
perl 5.17.2
```
HAS_IP_MREQ
PERL_RELOCATABLE_INC
sv_copypv_flags
sv_copypv_nomg
sv_vcatpvfn_flags
```
perl 5.17.1
```
alloccopstash (marked experimental)
CopSTASHPV_set
```
perl 5.16.0
```
CopLABEL_len
CopLABEL_len_flags
```
perl 5.15.8
```
HAS_IPV6_MREQ
HAS_SOCKADDR_IN6
is_utf8_char_buf
wrap_op_checker
```
perl 5.15.7
```
HAS_ISBLANK
```
perl 5.15.6
```
newCONSTSUB_flags
```
perl 5.15.4
```
gv_autoload_pv (undocumented)
gv_autoload_pvn (undocumented)
gv_autoload_sv (undocumented)
gv_fetchmethod_pv_flags (marked experimental) (undocumented)
gv_fetchmethod_pvn_flags (marked experimental) (undocumented)
gv_fetchmethod_sv_flags (marked experimental) (undocumented)
gv_fetchmeth_pv
gv_fetchmeth_pv_autoload
gv_fetchmeth_pvn
gv_fetchmeth_pvn_autoload
gv_fetchmeth_sv
gv_fetchmeth_sv_autoload
gv_init_pv
gv_init_sv
HvENAMELEN
HvENAMEUTF8
HvNAMELEN
HvNAMEUTF8
newGVgen_flags (undocumented)
sv_derived_from_pv
sv_derived_from_pvn
sv_derived_from_sv
sv_does_pv
sv_does_pvn
sv_does_sv
whichsig_pv
whichsig_pvn
whichsig_sv
```
perl 5.15.3
```
GV_ADDMG
gv_fetchsv_nomg
GV_NO_SVGMAGIC
I_STDBOOL
QUAD_IS___INT64
```
perl 5.15.2
```
ST_INO_SIGN
ST_INO_SIZE
XS_EXTERNAL (undocumented)
XS_INTERNAL (undocumented)
```
perl 5.15.1
```
cv_clone
pad_add_anon
pad_add_name_pv
pad_add_name_pvn
pad_add_name_pvs
pad_add_name_sv
pad_alloc (marked experimental)
pad_findmy_pv
pad_findmy_pvn
pad_findmy_pvs
pad_findmy_sv
pad_new
pad_tidy (marked experimental)
```
perl 5.13.10
```
WARN_NONCHAR
WARN_NON_UNICODE
WARN_SURROGATE
```
perl 5.13.9
```
HAS_SIN6_SCOPE_ID
PERL_PV_ESCAPE_NONASCII
UNICODE_DISALLOW_ILLEGAL_INTERCHANGE
UNICODE_DISALLOW_NONCHAR
UNICODE_DISALLOW_SUPER
UNICODE_DISALLOW_SURROGATE
UNICODE_IS_NONCHAR
UNICODE_IS_SUPER
UNICODE_WARN_ILLEGAL_INTERCHANGE
UNICODE_WARN_NONCHAR
UNICODE_WARN_SUPER
UNICODE_WARN_SURROGATE
UTF8_DISALLOW_ILLEGAL_INTERCHANGE
UTF8_DISALLOW_NONCHAR
UTF8_DISALLOW_SUPER
UTF8_DISALLOW_SURROGATE
UTF8_WARN_ILLEGAL_INTERCHANGE
UTF8_WARN_NONCHAR
UTF8_WARN_SUPER
UTF8_WARN_SURROGATE
```
perl 5.13.8
```
parse_arithexpr (marked experimental)
parse_fullexpr (marked experimental)
parse_listexpr (marked experimental)
parse_termexpr (marked experimental)
```
perl 5.13.7
```
amagic_deref_call (undocumented)
bytes_cmp_utf8
cophh_2hv (marked experimental)
cophh_copy (marked experimental)
cophh_delete_pv (marked experimental)
cophh_delete_pvn (marked experimental)
cophh_delete_pvs (marked experimental)
cophh_delete_sv (marked experimental)
cophh_fetch_pv (marked experimental)
cophh_fetch_pvn (marked experimental)
cophh_fetch_pvs (marked experimental)
cophh_fetch_sv (marked experimental)
cophh_free (marked experimental)
COPHH_KEY_UTF8
cophh_new_empty (marked experimental)
cophh_store_pv (marked experimental)
cophh_store_pvn (marked experimental)
cophh_store_pvs (marked experimental)
cophh_store_sv (marked experimental)
cop_hints_2hv
cop_hints_fetch_pv
cop_hints_fetch_pvn
cop_hints_fetch_pvs
cop_hints_fetch_sv
dirp_dup (undocumented)
HvENAME
lex_start (marked experimental)
newFOROP
newWHILEOP
OP_CLASS
op_lvalue (marked experimental)
op_scope (marked experimental)
parse_barestmt (marked experimental)
parse_block (marked experimental)
parse_label (marked experimental)
PARSE_OPTIONAL
Perl_custom_op_register (undocumented)
PL_phase
XopDISABLE
XopENABLE
XopENTRY
XopENTRYCUSTOM
XopENTRY_set
XopFLAGS
```
perl 5.13.6
```
ck_entersub_args_list
ck_entersub_args_proto
ck_entersub_args_proto_or_list
cv_get_call_checker
cv_set_call_checker
gv_fetchpvn
lex_stuff_pv (marked experimental)
LINKLIST
load_module_nocontext
mg_free_type
newSVpv_share
op_append_elem
op_append_list
op_contextualize
op_linklist
op_prepend_elem
parse_stmtseq (marked experimental)
PERL_MAGIC_checkcall
rv2cv_op_cv
RV2CVOPCV_MARK_EARLY
RV2CVOPCV_RETURN_NAME_GV
save_pushi32ptr (undocumented)
save_pushptrptr (undocumented)
savesharedpvs
savesharedsvpv
sv_catpv_flags
sv_catpv_nomg
sv_catpvs_flags
sv_catpvs_mg
sv_catpvs_nomg
sv_cmp_flags
sv_cmp_locale_flags
sv_collxfrm_flags
sv_eq_flags
sv_setpvs_mg
sv_setref_pvs
```
perl 5.13.5
```
hv_copy_hints_hv
lex_stuff_pvs (marked experimental)
parse_fullstmt (marked experimental)
PL_rpeepp
save_hints (undocumented)
```
perl 5.13.4
```
HAS_STATIC_INLINE
PERL_STATIC_INLINE
XS_APIVERSION_BOOTCHECK
```
perl 5.13.3
```
Perl_blockhook_register (undocumented)
```
perl 5.13.2
```
find_rundefsv
foldEQ
foldEQ_locale
Perl_clone_params_del (undocumented)
Perl_clone_params_new (undocumented)
Perl_hv_fill (undocumented)
sv_dec_nomg
sv_dup_inc (undocumented)
sv_inc_nomg
```
perl 5.13.1
```
sv_2nv_flags
```
perl 5.13.0
```
HAS_PRCTL
HAS_PRCTL_SET_NAME
```
perl 5.11.5
```
sv_pos_u2b_flags
```
perl 5.11.4
```
prescan_version
WARN_ILLEGALPROTO
```
perl 5.11.2
```
CHARBITS
ENTER_with_name
LEAVE_with_name
lex_bufutf8 (marked experimental)
lex_discard_to (marked experimental)
lex_grow_linestr (marked experimental)
LEX_KEEP_PREVIOUS
lex_next_chunk (marked experimental)
lex_peek_unichar (marked experimental)
lex_read_space (marked experimental)
lex_read_to (marked experimental)
lex_read_unichar (marked experimental)
lex_stuff_pvn (marked experimental)
lex_stuff_sv (marked experimental)
LEX_STUFF_UTF8
lex_unstuff (marked experimental)
PL_keyword_plugin (marked experimental)
toLOWER_LATIN1
```
perl 5.11.0
```
gv_add_by_type (undocumented)
Gv_AMupdate (undocumented)
is_ascii_string
is_invariant_string
is_utf8_invariant_string
PL_opfreehook
PUSH_MULTICALL
re_dup_guts
save_adelete (undocumented)
save_aelem_flags (undocumented)
save_hdelete (undocumented)
save_helem_flags (undocumented)
setdefout
SV_FORCE_UTF8_UPGRADE
SvOOK_offset
SVt_REGEXP
sv_utf8_upgrade_flags_grow
WARN_IMPRECISION
```
perl 5.10.1
```
GMTIME_MAX
GMTIME_MIN
HASATTRIBUTE_DEPRECATED
HAS_BUILTIN_EXPECT
HAS_GETADDRINFO
HAS_GETNAMEINFO
HAS_INETNTOP
HAS_INETPTON
HAS_TIMEGM
HvMROMETA
I_SYS_POLL
LOCALTIME_MAX
LOCALTIME_MIN
MRO_GET_PRIVATE_DATA
NV_OVERFLOWS_INTEGERS_AT
Perl_mro_get_from_name (undocumented)
Perl_mro_register (undocumented)
Perl_mro_set_mro (undocumented)
Perl_mro_set_private_data (undocumented)
PERL_USE_DEVEL
SAVEFREEOP
save_op (undocumented)
save_padsv_and_mortalize (undocumented)
save_pushptr (undocumented)
sv_insert_flags
```
perl 5.10.0
```
HAS_ASCTIME_R
HAS_CRYPT_R
HAS_CTIME_R
HAS_DRAND48_R
HAS_GETGRENT_R
HAS_GETGRGID_R
HAS_GETGRNAM_R
HAS_GETHOSTBYADDR_R
HAS_GETHOSTBYNAME_R
HAS_GETHOSTENT_R
HAS_GETLOGIN_R
HAS_GETNETBYADDR_R
HAS_GETNETBYNAME_R
HAS_GETNETENT_R
HAS_GETPROTOBYNAME_R
HAS_GETPROTOBYNUMBER_R
HAS_GETPROTOENT_R
HAS_GETPWENT_R
HAS_GETPWNAM_R
HAS_GETPWUID_R
HAS_GETSERVBYNAME_R
HAS_GETSERVBYPORT_R
HAS_GETSERVENT_R
HAS_GETSPNAM_R
HAS_GMTIME_R
HAS_LOCALTIME_R
HAS_OFF64_T
HAS_PTHREAD_ATFORK
HAS_RANDOM_R
HAS_READDIR64_R
HAS_READDIR_R
HAS_SETRESGID_PROTO
HAS_SETRESUID_PROTO
HAS_SRAND48_R
HAS_SRANDOM_R
HAS_STRERROR_R
HAS_TMPNAM_R
HAS_TTYNAME_R
LOCALTIME_R_NEEDS_TZSET
START_MY_CXT
sv_destroyable
USE_ITHREADS
UVf (DEPRECATED)
```
perl 5.9.5
```
CopLABEL
find_runcv
gv_fetchfile_flags
HAS_CTERMID
HAS_PTHREAD_YIELD
HAS_SIGNBIT
L_R_TZSET
mro_get_linear_isa
mro_method_changed_in
my_dirfd (undocumented)
Perl_av_create_and_push (undocumented)
Perl_av_create_and_unshift_one (undocumented)
Perl_signbit (marked experimental)
pregcomp
PRINTF_FORMAT_NULL_OK
ptr_table_fetch (undocumented)
ptr_table_free (undocumented)
ptr_table_new (undocumented)
ptr_table_split (undocumented)
ptr_table_store (undocumented)
re_compile (undocumented)
savesharedpvn
scan_vstring (undocumented)
upg_version
```
perl 5.9.4
```
gv_name_set (undocumented)
GV_NOTQUAL
HAS_BUILTIN_CHOOSE_EXPR
HAS_C99_VARIADIC_MACROS
my_vsnprintf
newXS_flags (marked experimental) (undocumented)
PERL_MAGIC_hints
PERL_MAGIC_hintselem
Perl_PerlIO_context_layers (undocumented)
sv_does
sv_nounlocking (DEPRECATED)
sv_usepvn_flags
```
perl 5.9.3
```
dMULTICALL
doref (undocumented)
gv_const_sv
GV_NOADD_NOINIT
GV_NOEXPAND
HASATTRIBUTE_FORMAT
HASATTRIBUTE_MALLOC
HASATTRIBUTE_NONNULL
HASATTRIBUTE_NORETURN
HASATTRIBUTE_PURE
HASATTRIBUTE_UNUSED
HASATTRIBUTE_WARN_UNUSED_RESULT
HAS_CLEARENV
HAS_FUTIMES
HAS_MODFL_PROTO
HAS_SNPRINTF
HAS_UNSETENV
HAS_VSNPRINTF
hv_name_set (undocumented)
is_utf8_string_loclen
LIBM_LIB_VERSION
MULTICALL
newGIVENOP
newSVhek
Perl_hv_eiter_p (undocumented)
Perl_hv_eiter_set (undocumented)
Perl_hv_placeholders_get (undocumented)
Perl_hv_placeholders_set (undocumented)
Perl_hv_riter_p (undocumented)
Perl_hv_riter_set (undocumented)
PERLIO_FUNCS_DECL (undocumented)
PERL_MAGIC_arylen_p
PERL_MAGIC_rhash
PERL_MAGIC_symtab
POP_MULTICALL
savepvs
seed (undocumented)
share_hek (undocumented)
sortsv_flags
SvPVbytex_nolen
SvPV_free
SvPVx_const
SvPVx_nolen
vverify
```
perl 5.9.2
```
find_rundefsvoffset (DEPRECATED)
op_refcnt_lock (undocumented)
op_refcnt_unlock (undocumented)
PERL_MALLOC_WRAP
savesvpv
SvPVbyte_force
vnormal
```
perl 5.9.1
```
hv_clear_placeholders
hv_scalar
Perl_ceil
scan_version
sv_2iv_flags
sv_2uv_flags
```
perl 5.9.0
```
_aMY_CXT
aMY_CXT
aMY_CXT_
dMY_CXT
hek_dup (undocumented)
MY_CXT
MY_CXT_CLONE
MY_CXT_INIT
new_version
parser_dup (undocumented)
Perl_my_cxt_init (undocumented)
_pMY_CXT
pMY_CXT
pMY_CXT_
save_set_svflags (undocumented)
SVs_PADSTALE
vcmp
vnumify
vstringify
```
perl 5.8.9
```
Perl_hv_assert (undocumented)
```
perl 5.8.8
```
__ASSERT_
rvpv_dup (undocumented)
```
perl 5.8.3
```
SvIsCOW
SvIsCOW_shared_hash
```
perl 5.8.1
```
CvPADLIST (marked experimental)
HAS_COPYSIGNL
HAS_FAST_STDIO
HAS_ILOGBL
HAS_PTHREAD_ATTR_SETSCOPE
HAS_SCALBNL
HAS_TM_TM_GMTOFF
IN_PERL_RUNTIME
is_utf8_string_loc
packlist
PL_comppad (marked experimental)
SAVEBOOL
savestack_grow_cnt (undocumented)
sv_cat_decode
sv_setpviv (DEPRECATED)
sv_setpviv_mg (DEPRECATED)
SvVOK
unpackstring
```
perl 5.8.0
```
ASCTIME_R_PROTO
CRYPT_R_PROTO
CTERMID_R_PROTO
CTIME_R_PROTO
DRAND48_R_PROTO
ENDGRENT_R_PROTO
ENDHOSTENT_R_PROTO
ENDNETENT_R_PROTO
ENDPROTOENT_R_PROTO
ENDPWENT_R_PROTO
ENDSERVENT_R_PROTO
GETGRENT_R_PROTO
GETGRGID_R_PROTO
GETGRNAM_R_PROTO
GETHOSTBYADDR_R_PROTO
GETHOSTBYNAME_R_PROTO
GETHOSTENT_R_PROTO
GETLOGIN_R_PROTO
GETNETBYADDR_R_PROTO
GETNETBYNAME_R_PROTO
GETNETENT_R_PROTO
GETPROTOBYNAME_R_PROTO
GETPROTOBYNUMBER_R_PROTO
GETPROTOENT_R_PROTO
GETPWENT_R_PROTO
GETPWNAM_R_PROTO
GETPWUID_R_PROTO
GETSERVBYNAME_R_PROTO
GETSERVBYPORT_R_PROTO
GETSERVENT_R_PROTO
GETSPNAM_R_PROTO
GMTIME_R_PROTO
HAS_TIME
HAS_TM_TM_ZONE
HeUTF8
hv_iternext_flags (marked experimental)
HV_ITERNEXT_WANTPLACEHOLDERS
hv_store_flags (marked experimental) (undocumented)
I_CRYPT
LOCALTIME_R_PROTO
nothreadhook
RANDOM_R_PROTO
READDIR64_R_PROTO
READDIR_R_PROTO
SETGRENT_R_PROTO
SETHOSTENT_R_PROTO
SETLOCALE_R_PROTO
SETNETENT_R_PROTO
SETPROTOENT_R_PROTO
SETPWENT_R_PROTO
SETSERVENT_R_PROTO
SRAND48_R_PROTO
SRANDOM_R_PROTO
STRERROR_R_PROTO
TMPNAM_R_PROTO
TTYNAME_R_PROTO
```
perl 5.7.3
```
atfork_lock (undocumented)
atfork_unlock (undocumented)
custom_op_desc (DEPRECATED)
custom_op_name (DEPRECATED)
debstack (undocumented)
debstackptrs (undocumented)
foldEQ_utf8
fp_dup (undocumented)
gp_dup (undocumented)
gv_fetchmeth_autoload
HAS_DIRFD
HAS_FINITE
HAS_FINITEL
HAS_ISINF
HAS_PROCSELFEXE
he_dup (undocumented)
ibcmp_utf8
mg_dup (undocumented)
my_fork (undocumented)
my_socketpair (undocumented)
OP_DESC
OP_NAME
Perl_deb (undocumented)
Perl_deb_nocontext (undocumented)
perl_destruct
PERL_EXIT_DESTRUCT_END
PerlIO_clearerr
PerlIO_close
PerlIO_eof
PerlIO_error
PerlIO_fileno
PerlIO_flush
PerlIO_get_base
PerlIO_get_bufsiz
PerlIO_get_cnt
PerlIO_get_ptr
PERLIO_K_MULTIARG
PerlIO_read
PerlIO_seek
PerlIO_set_cnt
PerlIO_setlinebuf
PerlIO_set_ptrcnt
PerlIO_stderr
PerlIO_stdin
PerlIO_stdout
PerlIO_tell
PerlIO_unread (undocumented)
PerlIO_write
Perl_isfinite
Perl_isinf
PL_peepp
PROCSELFEXE_PATH
pv_uni_display
savesharedpv
save_shared_pvref (undocumented)
si_dup (undocumented)
sortsv
ss_dup (undocumented)
sv_copypv
sv_dup (undocumented)
SvLOCK
sv_magicext
sv_nosharing
sv_recode_to_utf8
SvSHARE
sv_uni_display
SvUNLOCK
UNI_DISPLAY_BACKSLASH
UNI_DISPLAY_ISPRINT
UNI_DISPLAY_QQ
UNI_DISPLAY_REGEX
unpack_str (DEPRECATED)
uvchr_to_utf8_flags
vdeb (undocumented)
```
perl 5.7.2
```
DB_VERSION_MAJOR_CFG
DB_VERSION_MINOR_CFG
DB_VERSION_PATCH_CFG
getcwd_sv
HAS_FCHDIR
HAS_FLOCK_PROTO
HAS_NL_LANGINFO
HAS_SOCKATMARK_PROTO
HAS_STRFTIME
HAS_SYSCALL_PROTO
HAS_USLEEP_PROTO
I_LANGINFO
init_tm (undocumented)
mini_mktime
op_null
OSVERS
Perl_calloc (undocumented)
Perl_malloc (undocumented)
Perl_mfree (undocumented)
Perl_my_strftime (undocumented)
Perl_realloc (undocumented)
PERL_TARGETARCH
sv_catpvn_flags
sv_catsv_flags
sv_utf8_upgrade_flags
sv_utf8_upgrade_nomg
U_32
UNICODE_IS_REPLACEMENT
```
perl 5.7.1
```
bytes_from_utf8 (marked experimental)
do_openn (undocumented)
FCNTL_CAN_LOCK
gv_handler (undocumented)
HAS_FSYNC
HAS_GETITIMER
HAS_GETPAGESIZE
HAS_READV
HAS_RECVMSG
HAS_SBRK_PROTO
HAS_SENDMSG
HAS_SETITIMER
HAS_SIGPROCMASK
HAS_SOCKATMARK
HAS_STRTOQ
HAS_STRUCT_CMSGHDR
HAS_STRUCT_MSGHDR
HAS_UALARM
HAS_USLEEP
HAS_WRITEV
isALNUM_LC_uvchr
isALPHA_LC_uvchr
isCNTRL_LC_uvchr
isDIGIT_LC_uvchr
isGRAPH_LC_uvchr
isIDFIRST_LC_uvchr
isLOWER_LC_uvchr
is_lvalue_sub (undocumented)
isPRINT_LC_uvchr
isPUNCT_LC_uvchr
isSPACE_LC_uvchr
isUPPER_LC_uvchr
my_popen_list (undocumented)
NEED_VA_COPY
PerlIO_apply_layers
PerlIO_binmode
PerlIO_debug
PERLIO_F_APPEND
PERLIO_F_CANREAD
PERLIO_F_CANWRITE
PERLIO_F_CRLF
PERLIO_F_EOF
PERLIO_F_ERROR
PERLIO_F_FASTGETS
PERLIO_F_LINEBUF
PERLIO_F_OPEN
PERLIO_F_RDBUF
PERLIO_F_TEMP
PERLIO_F_TRUNCATE
PERLIO_F_UNBUF
PERLIO_F_UTF8
PERLIO_F_WRBUF
PERLIO_K_BUFFERED
PERLIO_K_CANCRLF
PERLIO_K_FASTGETS
PERLIO_K_RAW
Perl_printf_nocontext (undocumented)
POPpbytex
SAVEMORTALIZESV
SIG_SIZE
STDIO_PTR_LVAL_SETS_CNT
sv_force_normal_flags
sv_setref_uv
sv_unref_flags
sv_utf8_upgrade
U32_ALIGNMENT_REQUIRED
UNICODE_IS_SURROGATE
USE_PERLIO
UTF8_CHECK_ONLY
utf8_length
utf8n_to_uvchr
uvchr_to_utf8
UVXf
```
perl 5.7.0
```
FILE_base
FILE_bufsiz
FILE_cnt
FILE_ptr
PerlIO_fill (undocumented)
```
perl 5.6.1
```
apply_attrs_string (marked experimental) (undocumented)
bytes_to_utf8 (marked experimental)
gv_efullname4 (undocumented)
gv_fullname4 (undocumented)
HAS_FREXPL
HAS_ISNAN
HAS_ISNANL
HAS_MODFL
isPSXSPC_LC
isUTF8_CHAR
is_utf8_string
NV_PRESERVES_UV_BITS
NVSIZE
Perl_isnan
PERL_PRIeldbl
PERL_SCNfldbl
save_generic_pvref (undocumented)
SvGAMAGIC
utf8_to_bytes (marked experimental)
utf8_to_uvchr (DEPRECATED)
utf8_to_uvchr_buf
```
perl 5.6.0
```
av_delete
av_exists
call_atexit (undocumented)
caller_cx
CopLINE
CPPLAST
CPPRUN
do_open9 (DEPRECATED) (undocumented)
DO_UTF8
Drand01
dump_all
dump_eval (undocumented)
dump_form (undocumented)
dump_packsubs
dump_sub (undocumented)
FFLUSH_NULL
get_context (undocumented)
get_ppaddr (undocumented)
Gid_t_f
Gid_t_sign
Gid_t_size
gv_dump (undocumented)
HAS_ACCESS
HAS_ATOLL
HAS_DRAND48_PROTO
HAS_EACCESS
HAS_FD_SET
HAS_FSEEKO
HAS_FTELLO
HAS_GETCWD
HAS_GETHOSTNAME
HAS_GETSPNAM
HAS_INT64_T
HAS_LDBL_DIG
HAS_LSEEK_PROTO
HAS_MADVISE
HAS_MKDTEMP
HAS_MKSTEMP
HAS_MKSTEMPS
HAS_MMAP
HAS_MPROTECT
HAS_MSYNC
HAS_MUNMAP
HAS_SQRTL
HAS_STRTOLD
HAS_STRTOLL
HAS_STRTOULL
HAS_STRTOUQ
HAS_TELLDIR_PROTO
I16SIZE
I16TYPE
I32SIZE
I32TYPE
I64SIZE
I64TYPE
I8SIZE
I8TYPE
I_INTTYPES
I_NETINET_TCP
I_POLL
isALNUMC_LC
isALPHA_LC_utf8_safe
isALPHANUMERIC_LC_utf8_safe
isALPHANUMERIC_utf8_safe
isALPHANUMERIC_uvchr
isALPHA_utf8_safe
isALPHA_uvchr
isBLANK_LC_utf8_safe
isBLANK_utf8_safe
isBLANK_uvchr
isCNTRL_LC
isCNTRL_LC_utf8_safe
isCNTRL_utf8_safe
isCNTRL_uvchr
isDIGIT_LC_utf8_safe
isDIGIT_utf8_safe
isDIGIT_uvchr
isGRAPH_LC
isGRAPH_LC_utf8_safe
isGRAPH_utf8_safe
isGRAPH_uvchr
I_SHADOW
isIDCONT_LC_utf8_safe
isIDCONT_utf8_safe
isIDCONT_uvchr
isIDFIRST_LC_utf8_safe
isIDFIRST_utf8_safe
isIDFIRST_uvchr
isLOWER_LC_utf8_safe
isLOWER_utf8_safe
isLOWER_uvchr
isPRINT_LC_utf8_safe
isPRINT_utf8_safe
isPRINT_uvchr
isPSXSPC_LC_utf8_safe
isPSXSPC_utf8_safe
isPSXSPC_uvchr
isPUNCT_LC
isPUNCT_LC_utf8_safe
isPUNCT_utf8_safe
isPUNCT_uvchr
isSPACE_LC_utf8_safe
isSPACE_utf8_safe
isSPACE_uvchr
isUPPER_LC_utf8_safe
isUPPER_utf8_safe
isUPPER_uvchr
is_utf8_char (DEPRECATED)
isWORDCHAR_LC_utf8_safe
isWORDCHAR_utf8_safe
isWORDCHAR_uvchr
isXDIGIT_LC_utf8_safe
isXDIGIT_utf8_safe
isXDIGIT_uvchr
I_SYSLOG
I_SYSUIO
I_SYSUTSNAME
LSEEKSIZE
magic_dump (undocumented)
Mmap_t
MULTIPLICITY
my_atof
my_fflush_all (undocumented)
newANONATTRSUB (undocumented)
newATTRSUB
newXS
newXSproto
Off_t_size
op_dump
OPpEARLY_CV
PERL_ASYNC_CHECK
Perl_atan2
Perl_cos
PERL_EXIT_EXPECTED
Perl_exp
Perl_floor
Perl_fmod
Perl_frexp
Perl_log
Perl_modf
perl_parse
Perl_pow
PERL_PRIfldbl
PERL_PRIgldbl
PERL_REVISION (DEPRECATED)
Perl_sin
Perl_sqrt
PERL_SYS_INIT3
PHOSTNAME
PL_check
PL_exit_flags
PL_runops
pmop_dump (undocumented)
POPul
QUAD_IS_INT
QUAD_IS_INT64_T
QUAD_IS_LONG
QUAD_IS_LONG_LONG
QUADKIND
Rand_seed_t
require_pv
safesyscalloc
safesysfree
safesysmalloc
safesysrealloc
save_alloc (undocumented)
SAVEDESTRUCTOR
SAVEDESTRUCTOR_X
SAVEI8
save_vptr (undocumented)
scan_bin
SCHED_YIELD
seedDrand01
set_context (undocumented)
SITELIB_STEM
Size_t_size
Sock_size_t
STDIO_PTR_LVALUE
STDIO_STREAM_ARRAY
Strtol
Strtoul
sv_2pvutf8
sv_force_normal
SvIOK_notUV
SvIOK_only_UV
SvIOK_UV
sv_len_utf8
sv_len_utf8_nomg
SvPOK_only_UTF8
sv_pos_b2u
sv_pos_u2b
SvPVbyte_nolen
SvPVbytex
SvPVbytex_force
SvPVutf8
SvPVutf8_force
SvPVutf8_nolen
SvPVutf8x
SvPVutf8x_force
sv_rvweaken
SvUOK
sv_utf8_decode
sv_utf8_downgrade
sv_utf8_encode
SvUTF8_off
SvUTF8_on
toFOLD_utf8_safe
toFOLD_uvchr
toLOWER_utf8_safe
toLOWER_uvchr
toTITLE_utf8_safe
toTITLE_uvchr
toUPPER_utf8_safe
toUPPER_uvchr
U16SIZE
U16TYPE
U32SIZE
U32TYPE
U64SIZE
U64TYPE
U8SIZE
U8TYPE
Uid_t_f
Uid_t_sign
Uid_t_size
Uquad_t
USE_64_BIT_ALL
USE_64_BIT_INT
USE_LARGE_FILES
USE_STDIO_BASE
USE_STDIO_PTR
USE_THREADS
UTF8_CHK_SKIP
utf8_distance
utf8_hop
UTF8_MAXBYTES
UTF8_SAFE_SKIP
UTF8_SKIP
UTF8SKIP
vcroak
vform
```
perl 5.005\_03
```
get_vtbl (undocumented)
I_PTHREAD
POPpx
save_generic_svref (undocumented)
SELECT_MIN_BITS
SvTIED_obj
USE_STAT_BLOCKS
```
perl 5.005
```
debop (undocumented)
debprofdump (undocumented)
DOUBLESIZE
fbm_compile
fbm_instr
get_op_descs (undocumented)
get_op_names (undocumented)
GRPASSWD
HAS_CSH
HAS_ENDGRENT
HAS_ENDHOSTENT
HAS_ENDNETENT
HAS_ENDPROTOENT
HAS_ENDPWENT
HAS_ENDSERVENT
HAS_GETGRENT
HAS_GETHOSTBYADDR
HAS_GETHOSTBYNAME
HAS_GETHOST_PROTOS
HAS_GETNETBYADDR
HAS_GETNETBYNAME
HAS_GETNETENT
HAS_GETNET_PROTOS
HAS_GETPROTOBYNAME
HAS_GETPROTOBYNUMBER
HAS_GETPROTOENT
HAS_GETPROTO_PROTOS
HAS_GETPWENT
HAS_GETSERVBYNAME
HAS_GETSERVBYPORT
HAS_GETSERVENT
HAS_GETSERV_PROTOS
HAS_LCHOWN
HAS_LONG_DOUBLE
HAS_LONG_LONG
HAS_SCHED_YIELD
HAS_SETGRENT
HAS_SETHOSTENT
HAS_SETNETENT
HAS_SETPROTOENT
HAS_SETPWENT
HAS_SETSERVENT
HAS_SETVBUF
I_ARPA_INET
I_NETDB
init_stacks (undocumented)
LONG_DOUBLESIZE
LONGLONGSIZE
mg_length (DEPRECATED)
mg_size (undocumented)
Netdb_hlen_t
Netdb_host_t
Netdb_name_t
Netdb_net_t
newHVhv (undocumented)
new_stackinfo (undocumented)
Pid_t
PL_curpad (marked experimental)
PL_in_my_stash (undocumented)
PL_maxsysfd
PL_modglobal
PL_restartop
PTRSIZE
PWPASSWD
regdump (undocumented)
sv_peek (undocumented)
sv_pvn_nomg (DEPRECATED) (undocumented)
SvPVx_force
```
perl 5.004\_05
```
do_binmode (DEPRECATED) (undocumented)
GV_NOINIT
HAS_CHSIZE
HAS_GNULIBC
PWGECOS
save_aelem (undocumented)
save_helem (undocumented)
USE_SEMCTL_SEMID_DS
USE_SEMCTL_SEMUN
```
perl 5.004
```
ARCHNAME
BIN_EXP
block_gimme (undocumented)
call_list (undocumented)
delimcpy
GIMME_V
gv_autoload4
gv_fetchmethod_autoload
G_VOID
HAS_GETTIMEOFDAY
HAS_INET_ATON
HAS_SETGROUPS
HAS_STRTOD
HAS_STRTOL
HAS_STRTOUL
HePV
HeSVKEY_set
hv_delayfree_ent (undocumented)
hv_free_ent (undocumented)
ibcmp_locale
IN_LOCALE
IN_LOCALE_COMPILETIME
IN_LOCALE_RUNTIME
isALNUM_LC
isALPHA_LC
isALPHANUMERIC_LC
isDIGIT_LC
isIDCONT_LC
isIDFIRST_LC
isLOWER_LC
isPRINT_LC
isSPACE_LC
isUPPER_LC
isWORDCHAR_LC
JMPENV_JUMP
mess_sv
my_failure_exit (undocumented)
Perl_ck_warner (undocumented)
Perl_ck_warner_d (undocumented)
Perl_form (undocumented)
Perl_mess (undocumented)
Perl_newSVpvf (undocumented)
Perl_sv_catpvf (undocumented)
Perl_sv_catpvf_mg (undocumented)
Perl_sv_setpvf (undocumented)
Perl_sv_setpvf_mg (undocumented)
Perl_warner (undocumented)
Perl_warner_nocontext (undocumented)
PL_mess_sv (undocumented)
POPu
rsignal
rsignal_state (undocumented)
save_gp
SAVEI16
SAVESTACK_POS
SHORTSIZE
sv_cmp_locale
sv_derived_from
sv_magic_portable (undocumented)
SvSetMagicSV
SvSetMagicSV_nosteal
SvSetSV_nosteal
SvTAINTED
SvTAINTED_off
SvTAINTED_on
sv_vcatpvf
sv_vcatpvf_mg
sv_vcatpvfn
sv_vsetpvf
sv_vsetpvf_mg
sv_vsetpvfn
Timeval
toLOWER_LC
vmess
vnewSVpvf
vwarner
```
perl 5.003\_07 (or maybe earlier)
```
amagic_call (undocumented)
ARCHLIB
ARCHLIB_EXP
ASSUME
aTHX
aTHX_
aTHXR (undocumented)
aTHXR_ (undocumented)
AvARRAY
av_clear
av_count
av_extend
av_fetch
av_fill
AvFILL
av_len
av_make
av_pop
av_push
av_shift
av_store
av_tindex
av_top_index
av_undef
av_unshift
ax
BIN
BOM_UTF8
boolSV
BYTEORDER
call_argv
call_method
call_pv
call_sv
C_ARRAY_END
C_ARRAY_LENGTH
CASTFLAGS
CASTNEGFLOAT
CAT2
cBOOL
ckWARN
ckWARN2
ckWARN2_d
ckWARN3
ckWARN3_d
ckWARN4
ckWARN4_d
ckWARN_d
CLASS
CopFILE
CopFILEAV
CopFILEGV
CopFILEGV_set
CopFILE_set
CopFILESV
CopSTASH
CopSTASH_eq
CopSTASHPV
CopSTASH_set
Copy
CopyD
CPERLscope (DEPRECATED)
CPPMINUS
CPPSTDIN
croak_no_modify
croak_sv
croak_xs_usage
CSH
cv_const_sv
CvDEPTH (undocumented)
CvGV
CvSTASH
cv_undef
dAX
dAXMARK
DB_Hash_t
DB_Prefix_t
DEFSV
DEFSV_set
die_sv
Direntry_t
dITEMS
dMARK
dMY_CXT_SV
dNOOP
do_close (undocumented)
do_join (undocumented)
do_open (undocumented)
dORIGMARK
do_sprintf (undocumented)
dounwind (undocumented)
dowantarray (undocumented)
dSP
dTARGET
dTHR
dTHX
dTHXa
dTHXoa
dTHXR (undocumented)
dUNDERBAR
dVAR
dXCPT
dXSARGS
dXSI32
dXSTARG (undocumented)
END_EXTERN_C
ENTER
EOF_NONBLOCK
ERRSV
eval_pv
eval_sv
EXTEND
EXTERN_C
filter_add
filter_del (undocumented)
filter_read
FLEXFILENAMES
Fpos_t
Free_t
FREETMPS
Gconvert
G_DISCARD
get_av
get_cv
get_cvn_flags
get_cvs
get_hv
get_sv
G_EVAL
Gid_t
GIMME (DEPRECATED)
G_KEEPERR
G_LIST
G_METHOD
G_NOARGS
gp_free (undocumented)
gp_ref (undocumented)
G_RETHROW
grok_bin
grok_hex
grok_number
GROK_NUMERIC_RADIX
grok_numeric_radix
grok_oct
Groups_t
G_SCALAR
GV_ADD
GV_ADDMULTI
GV_ADDWARN
GvAV
gv_AVadd (undocumented)
GvCV
gv_efullname (DEPRECATED) (undocumented)
gv_efullname3 (undocumented)
gv_fetchfile
gv_fetchmeth
gv_fetchmethod
gv_fetchpv
gv_fetchpvn_flags
gv_fetchpvs
gv_fetchsv
gv_fullname (DEPRECATED) (undocumented)
gv_fullname3 (undocumented)
GvHV
gv_HVadd (undocumented)
gv_init
gv_init_pvn
gv_IOadd (undocumented)
gv_stashpv
gv_stashpvn
gv_stashpvs
gv_stashsv
GvSV
GvSVn
HAS_ALARM
HAS_CHOWN
HAS_CHROOT
HAS_CRYPT
HAS_CUSERID
HAS_DIFFTIME
HAS_DLERROR
HAS_DUP2
HAS_FCHMOD
HAS_FCHOWN
HAS_FCNTL
HAS_FGETPOS
HAS_FLOCK
HAS_FORK
HAS_FPATHCONF
HAS_FSETPOS
HAS_GETGROUPS
HAS_GETHOSTENT
HAS_GETLOGIN
HAS_GETPGID
HAS_GETPGRP
HAS_GETPPID
HAS_GETPRIORITY
HAS_HTONL
HAS_HTONS
HAS_ISASCII
HAS_KILLPG
HAS_LINK
HAS_LOCALECONV
HAS_LOCKF
HAS_LSTAT
HAS_MBLEN
HAS_MBSTOWCS
HAS_MBTOWC
HAS_MKDIR
HAS_MKFIFO
HAS_MKTIME
HAS_MSG
HAS_NICE
HAS_NTOHL
HAS_NTOHS
HAS_OPEN3
HAS_PATHCONF
HAS_PAUSE
HAS_PIPE
HAS_POLL
HAS_QUAD
HAS_READDIR
HAS_READLINK
HAS_RENAME
HAS_REWINDDIR
HAS_RMDIR
HAS_SEEKDIR
HAS_SELECT
HAS_SEM
HAS_SETEGID
HAS_SETEUID
HAS_SETLINEBUF
HAS_SETLOCALE
HAS_SETPGID
HAS_SETPGRP
HAS_SETPRIORITY
HAS_SETREGID
HAS_SETRESGID
HAS_SETRESUID
HAS_SETREUID
HAS_SETSID
HAS_SHM
HAS_SHMAT_PROTOTYPE
HAS_SIGACTION
HAS_SIGSETJMP
HAS_SOCKET
HAS_SOCKETPAIR
HAS_STRCOLL
HAS_STRXFRM
HAS_SYMLINK
HAS_SYSCALL
HAS_SYSCONF
HAS_SYS_ERRLIST
HAS_SYSTEM
HAS_TCGETPGRP
HAS_TCSETPGRP
HAS_TELLDIR
HAS_TIMES
HAS_TRUNCATE
HAS_TZNAME
HAS_UMASK
HAS_UNAME
HAS_WAIT4
HAS_WAITPID
HAS_WCSTOMBS
HAS_WCTOMB
HEf_SVKEY
HeHASH
HeKEY
HeKLEN
HeSVKEY
HeSVKEY_force
HeVAL
hv_clear
hv_delete
hv_delete_ent
hv_exists
hv_exists_ent
hv_fetch
hv_fetch_ent
hv_fetchs
HvFILL
hv_iterinit
hv_iterkey
hv_iterkeysv
hv_iternext
hv_iternextsv
hv_iterval
hv_ksplit (undocumented)
hv_magic
HvNAME
HvNAMELEN_get
hv_store
hv_store_ent
hv_stores
hv_undef
I_32
ibcmp
I_DIRENT
I_DLFCN
I_GRP
I_LOCALE
I_NETINET_IN
IN_PERL_COMPILETIME
instr
INT16_C
INT2PTR
INT32_C
INTMAX_C
INTSIZE
I_PWD
isALNUM
isALNUM_A
isALNUMC
isALNUMC_A
isALNUMC_L1
isALPHA
isALPHA_A
isALPHA_L1
isALPHANUMERIC
isALPHANUMERIC_A
isALPHANUMERIC_L1
isASCII
isASCII_A
isASCII_L1
isASCII_LC
isASCII_utf8_safe
isASCII_uvchr
isBLANK
isBLANK_A
isBLANK_L1
isBLANK_LC
isCNTRL
isCNTRL_A
isCNTRL_L1
isDIGIT
isDIGIT_A
isDIGIT_L1
isGRAPH
isGRAPH_A
isGRAPH_L1
isGV_with_GP
isIDCONT
isIDCONT_A
isIDCONT_L1
isIDFIRST
isIDFIRST_A
isIDFIRST_L1
isLOWER
isLOWER_A
isLOWER_L1
IS_NUMBER_GREATER_THAN_UV_MAX
IS_NUMBER_INFINITY
IS_NUMBER_IN_UV
IS_NUMBER_NAN
IS_NUMBER_NEG
IS_NUMBER_NOT_INT
isOCTAL
isOCTAL_A
isOCTAL_L1
isPRINT
isPRINT_A
isPRINT_L1
isPSXSPC
isPSXSPC_A
isPSXSPC_L1
isPUNCT
isPUNCT_A
isPUNCT_L1
isSPACE
isSPACE_A
isSPACE_L1
isUPPER
isUPPER_A
isUPPER_L1
isWORDCHAR
isWORDCHAR_A
isWORDCHAR_L1
isXDIGIT
isXDIGIT_A
isXDIGIT_L1
isXDIGIT_LC
I_SYS_DIR
I_SYS_FILE
I_SYS_IOCTL
I_SYS_PARAM
I_SYS_RESOURCE
I_SYS_SELECT
I_SYS_STAT
I_SYS_TIME
I_SYS_TIMES
I_SYS_TYPES
I_SYS_UN
I_SYS_WAIT
items
I_TERMIOS
I_TIME
I_UNISTD
I_UTIME
I_V
IVdf
IV_MAX
IV_MIN
IVSIZE
IVTYPE
ix
LATIN1_TO_NATIVE
LEAVE
leave_scope (undocumented)
LIKELY
load_module
LOC_SED
LONGSIZE
looks_like_number
Malloc_t
MARK
MEM_ALIGNBYTES
memCHRs
memEQ
memEQs
memNE
memNEs
memzero
mg_clear
mg_copy
mg_find
mg_findext
mg_free
mg_get
mg_magical
mg_set
Mode_t
Move
MoveD
mPUSHi
mPUSHn
mPUSHp
mPUSHs
mPUSHu
MUTABLE_AV
MUTABLE_CV
MUTABLE_GV
MUTABLE_HV
MUTABLE_IO
MUTABLE_PTR
MUTABLE_SV
mXPUSHi
mXPUSHn
mXPUSHp
mXPUSHs
mXPUSHu
my_exit
my_pclose (undocumented)
my_popen (undocumented)
my_setenv
my_sprintf (DEPRECATED)
my_strlcat
my_strlcpy
my_strnlen
NATIVE_TO_LATIN1
NATIVE_TO_UNI
newANONHASH (undocumented)
newANONLIST (undocumented)
newANONSUB (undocumented)
newASSIGNOP
newAV
newAVREF (undocumented)
newBINOP
newCONDOP
newCONSTSUB
newCVREF (undocumented)
newFORM (undocumented)
newGVgen (undocumented)
newGVOP
newGVREF (undocumented)
newHV
newHVREF (undocumented)
newIO (undocumented)
newLISTOP
newLOGOP
newLOOPEX
newLOOPOP
newNULLLIST
newOP
newPMOP
newPROG (undocumented)
newPVOP
newRANGE
newRV
newRV_inc
newRV_noinc
newSLICEOP
newSTATEOP
newSUB
newSV
newSViv
newSVnv
newSVOP
newSVpv
newSVpvn
newSVpvn_flags
newSVpvn_share
newSVpvn_utf8
newSVpvs
newSVpvs_flags
newSVpvs_share
newSVREF (undocumented)
newSVrv
newSVsv
newSVsv_flags
newSVsv_nomg
newSV_type
newSVuv
newUNOP
Newx
Newxc
Newxz
ninstr
NOOP
NOT_REACHED (undocumented)
Nullav (DEPRECATED)
Nullch
Nullcv (DEPRECATED)
Nullhv (DEPRECATED)
Nullsv
NVef
NVff
NVgf
NVTYPE
Off_t
OPf_KIDS
op_free
OpHAS_SIBLING
OpLASTSIB_set
OpMAYBESIB_set
OpMORESIB_set
OPpENTERSUB_AMPER
OpSIBLING
ORIGMARK
OSNAME
packWARN
packWARN2
packWARN3
packWARN4
PERL_ABS
perl_alloc
PERL_BCDVERSION (undocumented)
perl_construct
Perl_croak (undocumented)
Perl_die (undocumented)
Perl_eval_pv (undocumented)
Perl_eval_sv (undocumented)
perl_free
PERL_HASH
PERL_INT_MAX
PERL_INT_MIN
PerlIO_canset_cnt
PerlIO_exportFILE
PerlIO_fast_gets
PerlIO_fdopen
PerlIO_findFILE
PerlIO_getc
PerlIO_getpos
PerlIO_has_base
PerlIO_has_cntptr
PerlIO_importFILE
PerlIO_open
PerlIO_printf
PerlIO_putc
PerlIO_puts
PerlIO_releaseFILE
PerlIO_reopen
PerlIO_rewind
PerlIO_setpos
PerlIO_stdoutf
PerlIO_ungetc
PerlIO_vprintf
PERL_LOADMOD_DENY
PERL_LOADMOD_IMPORT_OPS
PERL_LOADMOD_NOIMPORT
PERL_LONG_MAX
PERL_LONG_MIN
PERL_MAGIC_arylen
PERL_MAGIC_backref
PERL_MAGIC_bm
PERL_MAGIC_collxfrm
PERL_MAGIC_dbfile
PERL_MAGIC_dbline
PERL_MAGIC_defelem
PERL_MAGIC_env
PERL_MAGIC_envelem
PERL_MAGIC_ext
PERL_MAGIC_fm
PERL_MAGIC_glob (undocumented)
PERL_MAGIC_isa
PERL_MAGIC_isaelem
PERL_MAGIC_mutex (undocumented)
PERL_MAGIC_nkeys
PERL_MAGIC_overload (undocumented)
PERL_MAGIC_overload_elem (undocumented)
PERL_MAGIC_overload_table
PERL_MAGIC_pos
PERL_MAGIC_qr
PERL_MAGIC_regdata
PERL_MAGIC_regdatum
PERL_MAGIC_regex_global
PERL_MAGIC_shared
PERL_MAGIC_shared_scalar
PERL_MAGIC_sig
PERL_MAGIC_sigelem
PERL_MAGIC_substr
PERL_MAGIC_sv
PERL_MAGIC_taint
PERL_MAGIC_tied
PERL_MAGIC_tiedelem
PERL_MAGIC_tiedscalar
PERL_MAGIC_utf8
PERL_MAGIC_uvar
PERL_MAGIC_uvar_elem
PERL_MAGIC_vec
PERL_MAGIC_vstring
Perl_my_snprintf (undocumented)
PERL_PV_ESCAPE_ALL
PERL_PV_ESCAPE_FIRSTCHAR
PERL_PV_ESCAPE_NOBACKSLASH
PERL_PV_ESCAPE_NOCLEAR
PERL_PV_ESCAPE_QUOTE
PERL_PV_ESCAPE_RE
PERL_PV_ESCAPE_UNI
PERL_PV_ESCAPE_UNI_DETECT
PERL_PV_PRETTY_ELLIPSES
PERL_PV_PRETTY_LTGT
PERL_PV_PRETTY_QUOTE
PERL_QUAD_MAX
PERL_QUAD_MIN
perl_run
PERL_SCAN_ALLOW_UNDERSCORES
PERL_SCAN_DISALLOW_PREFIX
PERL_SCAN_GREATER_THAN_UV_MAX
PERL_SCAN_SILENT_ILLDIGIT
PERL_SHORT_MAX
PERL_SHORT_MIN
PERL_SIGNALS_UNSAFE_FLAG
PERL_SUBVERSION (DEPRECATED)
PERL_SYS_INIT
PERL_SYS_TERM
PERL_UCHAR_MAX
PERL_UCHAR_MIN
PERL_UINT_MAX
PERL_UINT_MIN
PERL_ULONG_MAX
PERL_ULONG_MIN
PERL_UNUSED_ARG
PERL_UNUSED_CONTEXT
PERL_UNUSED_DECL
PERL_UNUSED_RESULT
PERL_UNUSED_VAR
PERL_UQUAD_MAX
PERL_UQUAD_MIN
PERL_USE_GCC_BRACE_GROUPS
PERL_USHORT_MAX
PERL_USHORT_MIN
PERL_VERSION (DEPRECATED)
PERL_VERSION_GE
PERL_VERSION_GT
PERL_VERSION_LE
PERL_VERSION_LT
Perl_warn (undocumented)
PL_bufend (undocumented)
PL_bufptr (undocumented)
PL_compiling (undocumented)
PL_copline (undocumented)
PL_curcop
PL_curstash
PL_DBsignal (undocumented)
PL_debstash (undocumented)
PL_defgv
PL_diehook (undocumented)
PL_dirty (undocumented)
PL_errgv
PL_error_count (undocumented)
PL_expect (undocumented)
PL_hexdigit
PL_hints (undocumented)
PL_in_my (undocumented)
PL_laststatval (undocumented)
PL_lex_state (undocumented)
PL_lex_stuff (undocumented)
PL_linestr (undocumented)
PL_na
PL_no_modify (undocumented)
PL_parser
PL_perldb (undocumented)
PL_perl_destruct_level
PL_ppaddr (undocumented)
PL_rsfp (undocumented)
PL_rsfp_filters (undocumented)
PL_signals (undocumented)
PL_stack_base (undocumented)
PL_stack_sp (undocumented)
PL_statcache (undocumented)
PL_stdingv (undocumented)
PL_sv_arenaroot (undocumented)
PL_sv_no
PL_sv_undef
PL_sv_yes
PL_tainted (undocumented)
PL_tainting (undocumented)
PL_tokenbuf (undocumented)
PL_Xpv (undocumented)
Poison
PoisonFree
PoisonNew
PoisonWith
POPi
POPl
POPn
POPp
POPs
pop_scope (undocumented)
pregexec
pregfree (undocumented)
PRIVLIB
PRIVLIB_EXP
pTHX
pTHX_
PTR2IV
PTR2nat
PTR2NV
PTR2ul
PTR2UV
PTRV (undocumented)
PUSHi
PUSHMARK
PUSHmortal
PUSHn
PUSHp
PUSHs
push_scope (undocumented)
PUSHu
PUTBACK
pv_display
pv_escape
pv_pretty
Quad_t
RANDBITS
RD_NODATA
Renew
Renewc
repeatcpy (undocumented)
REPLACEMENT_CHARACTER_UTF8
RETVAL
rninstr
Safefree
save_aptr
save_ary
SAVE_DEFSV
SAVEDELETE
SAVEFREEPV
SAVEFREESV
save_hash
save_hptr
SAVEI32
SAVEINT
save_item
SAVEIV
save_list (DEPRECATED)
SAVELONG
save_nogv (DEPRECATED) (undocumented)
SAVEPPTR
savepv
savepvn
save_scalar
SAVESPTR
savestack_grow (undocumented)
save_svref
SAVETMPS
scan_hex
scan_oct
Select_fd_set_t
Shmat_t
SH_PATH
Sigjmp_buf
Siglongjmp
Signal_t
SIG_NAME
SIG_NUM
Sigsetjmp
SITEARCH
SITEARCH_EXP
SITELIB
SITELIB_EXP
Size_t
SP
SPAGAIN
SSize_t
ST
START_EXTERN_C
STARTPERL
start_subparse (undocumented)
STDCHAR
STMT_END
STMT_START
strEQ
strGE
strGT
STRINGIFY
strLE
strLT
strNE
strnEQ
strnNE
StructCopy
STR_WITH_LEN
sv_2cv
sv_2io
sv_2mortal
sv_2pvbyte
SvAMAGIC_off (undocumented)
SvAMAGIC_on (undocumented)
sv_backoff
sv_bless
sv_catpv
sv_catpv_mg
sv_catpvn
sv_catpvn_mg
sv_catpvn_nomg
sv_catpvs
sv_catsv
sv_catsv_mg
sv_catsv_nomg
sv_chop
sv_clear
sv_cmp
SV_CONST_RETURN (undocumented)
SV_COW_DROP_PV
SV_COW_SHARED_HASH_KEYS (undocumented)
SvCUR
SvCUR_set
sv_dec
sv_dump
SvEND
sv_eq
SVf
SVfARG
sv_free
SVf_UTF8
SvGETMAGIC
sv_gets
SV_GMAGIC
SvGROW
SV_HAS_TRAILING_NUL
SV_IMMEDIATE_UNREF
sv_inc
sv_insert
SvIOK
SvIOK_off
SvIOK_on
SvIOK_only
SvIOKp
sv_isa
sv_isobject
SvIV
SvIV_nomg
SvIV_set
SvIVX
SvIVx
sv_len
SvLEN
SvLEN_set
sv_magic
SvMAGIC_set
sv_mortalcopy
sv_mortalcopy_flags
SV_MUTABLE_RETURN (undocumented)
sv_newmortal
SvNIOK
SvNIOK_off
SvNIOKp
SvNOK
SvNOK_off
SvNOK_on
SvNOK_only
SvNOKp
SV_NOSTEAL
SvNV
SvNV_nomg
SvNV_set
SvNVX
SvNVx
SvOK
SvOOK
SvOOK_off
SvPOK
SvPOK_off
SvPOK_on
SvPOK_only
SvPOKp
SvPV
SvPVbyte
SvPV_const
SvPV_flags
SvPV_flags_const
SvPV_flags_mutable
SvPV_force
SvPV_force_flags
SvPV_force_flags_mutable
SvPV_force_flags_nolen
SvPV_force_mutable
SvPV_force_nolen
SvPV_force_nomg
SvPV_force_nomg_nolen
SvPV_mutable
sv_pvn_force_flags
SvPV_nolen
SvPV_nolen_const
SvPV_nomg
SvPV_nomg_const
SvPV_nomg_const_nolen
SvPV_nomg_nolen
SvPV_renew
SvPV_set
SvPVX
SvPVx
SvPVX_const
SvPVX_mutable
SvPVx_nolen_const
SvPVXx
SvREADONLY
SvREADONLY_off
SvREADONLY_on
SvREFCNT
SvREFCNT_dec
SvREFCNT_inc
SvREFCNT_inc_NN
SvREFCNT_inc_simple
SvREFCNT_inc_simple_NN
SvREFCNT_inc_simple_void
SvREFCNT_inc_simple_void_NN
SvREFCNT_inc_void
SvREFCNT_inc_void_NN
sv_reftype
sv_replace
sv_report_used
sv_reset
SvROK
SvROK_off
SvROK_on
SvRV
SvRV_set
SvRX
SvRXOK
sv_setiv
sv_setiv_mg
SvSETMAGIC
sv_setnv
sv_setnv_mg
sv_setpv
sv_setpv_mg
sv_setpvn
sv_setpvn_mg
sv_setpvs
sv_setref_iv
sv_setref_nv
sv_setref_pv
sv_setref_pvn
sv_setsv
SvSetSV
sv_setsv_flags
sv_setsv_mg
sv_setsv_nomg
sv_setuv
sv_setuv_mg
SvSHARED_HASH
SV_SMAGIC
SvSTASH
SvSTASH_set
SVs_TEMP
SvTAINT
SVt_IV
SVt_NULL
SVt_NV
SVt_PV
SVt_PVAV
SVt_PVCV
SVt_PVFM
SVt_PVGV
SVt_PVHV
SVt_PVIO
SVt_PVIV
SVt_PVLV
SVt_PVMG
SVt_PVNV
SvTRUE
SvTRUE_nomg
SvTRUEx
SvTYPE
svtype (undocumented)
sv_unmagic
sv_unmagicext
sv_unref
sv_upgrade
SvUPGRADE
sv_usepvn
sv_usepvn_mg
SvUTF8
SV_UTF8_NO_ENCODING (DEPRECATED)
SvUV
SvUV_nomg
SvUV_set
SvUVX
SvUVx
SvUVXx (DEPRECATED)
SvVSTRING_mg
switch_to_global_locale
sync_locale
taint_env (undocumented)
taint_proper (undocumented)
TARG
THIS
Time_t
toLOWER
toUPPER
Uid_t
UINT16_C
UINT32_C
UINTMAX_C
UNDERBAR
UNICODE_REPLACEMENT
UNI_TO_NATIVE
UNLIKELY
unsharepvn (undocumented)
USE_DYNAMIC_LOADING
UTF8f
UTF8fARG
UTF8_IS_INVARIANT
UTF8_MAXBYTES_CASE
U_V
UVCHR_IS_INVARIANT
UVCHR_SKIP
UV_MAX
UV_MIN
UVof
UVSIZE
UVTYPE
UVuf
UVxf
VAL_EAGAIN
VAL_O_NONBLOCK
vload_module
vwarn
WARN_ALL
WARN_AMBIGUOUS
WARN_ASSERTIONS (undocumented)
WARN_BAREWORD
WARN_CLOSED
WARN_CLOSURE
WARN_DEBUGGING
WARN_DEPRECATED
WARN_DIGIT
WARN_EXEC
WARN_EXITING
WARN_GLOB
WARN_INPLACE
WARN_INTERNAL
WARN_IO
WARN_LAYER
WARN_MALLOC
WARN_MISC
WARN_NEWLINE
WARN_NUMERIC
WARN_ONCE
WARN_OVERFLOW
WARN_PACK
WARN_PARENTHESIS
WARN_PIPE
WARN_PORTABLE
WARN_PRECEDENCE
WARN_PRINTF
WARN_PROTOTYPE
WARN_QW
WARN_RECURSION
WARN_REDEFINE
WARN_REGEXP
WARN_RESERVED
WARN_SEMICOLON
WARN_SEVERE
WARN_SIGNAL
WARN_SUBSTR
warn_sv
WARN_SYNTAX
WARN_TAINT
WARN_THREADS
WARN_UNINITIALIZED
WARN_UNOPENED
WARN_UNPACK
WARN_UNTIE
WARN_UTF8
WARN_VOID
whichsig
WIDEST_UTYPE (undocumented)
XCPT_CATCH
XCPT_RETHROW
XCPT_TRY_END
XCPT_TRY_START
XPUSHi
XPUSHmortal
XPUSHn
XPUSHp
XPUSHs
XPUSHu
XS (undocumented)
XSprePUSH (undocumented)
XSPROTO (undocumented)
XSRETURN
XSRETURN_EMPTY
XSRETURN_IV
XSRETURN_NO
XSRETURN_NV
XSRETURN_PV
XSRETURN_UNDEF
XSRETURN_UV
XSRETURN_YES
XST_mIV
XST_mNO
XST_mNV
XST_mPV
XST_mUNDEF
XST_mUV
XST_mYES
XS_VERSION
XS_VERSION_BOOTCHECK
Zero
ZeroD
```
Backported version unknown
```
LC_NUMERIC_LOCK (undocumented)
LC_NUMERIC_UNLOCK (undocumented)
LOCK_NUMERIC_STANDARD (undocumented)
NUM2PTR (undocumented)
PERLIO_FUNCS_CAST (undocumented)
PERLIO_FUNCS_DECL (undocumented)
STORE_LC_NUMERIC_SET_STANDARD (undocumented)
STORE_NUMERIC_SET_STANDARD (undocumented)
SvPV_flags_const_nolen (undocumented)
UNLOCK_NUMERIC_STANDARD (undocumented)
XSPROTO (undocumented)
```
BUGS
----
If you find any bugs, `Devel::PPPort` doesn't seem to build on your system, or any of its tests fail, please send a bug report to <https://github.com/Dual-Life/Devel-PPPort/issues/new>.
AUTHORS
-------
* Version 1.x of Devel::PPPort was written by Kenneth Albanowski.
* Version 2.x was ported to the Perl core by Paul Marquess.
* Version 3.x was ported back to CPAN by Marcus Holland-Moritz.
* Versions >= 3.22 are maintained by perl5 porters
COPYRIGHT
---------
Version 3.x, Copyright (C) 2004-2013, Marcus Holland-Moritz.
```
Copyright (C) 2018-2020, The perl5 porters
```
Version 2.x, Copyright (C) 2001, Paul Marquess.
Version 1.x, Copyright (C) 1999, Kenneth Albanowski.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
---------
See <h2xs>, <ppport.h>.
| programming_docs |
perl perlsecpolicy perlsecpolicy
=============
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [REPORTING SECURITY ISSUES IN PERL](#REPORTING-SECURITY-ISSUES-IN-PERL)
* [WHAT ARE SECURITY ISSUES](#WHAT-ARE-SECURITY-ISSUES)
+ [Software covered by the Perl security team](#Software-covered-by-the-Perl-security-team)
+ [Bugs that may qualify as security issues in Perl](#Bugs-that-may-qualify-as-security-issues-in-Perl)
+ [Bugs that do not qualify as security issues in Perl](#Bugs-that-do-not-qualify-as-security-issues-in-Perl)
- [Feeding untrusted code to the interpreter](#Feeding-untrusted-code-to-the-interpreter)
- [Stack overflows due to excessive recursion](#Stack-overflows-due-to-excessive-recursion)
- [Out of memory errors](#Out-of-memory-errors)
- [Escape from a Safe compartment](#Escape-from-a-Safe-compartment)
- [Use of the p and P pack templates](#Use-of-the-p-and-P-pack-templates)
- [Stack not reference-counted issues](#Stack-not-reference-counted-issues)
- [Thawing attacker-supplied data with Storable](#Thawing-attacker-supplied-data-with-Storable)
- [Using attacker supplied SDBM\_File databases](#Using-attacker-supplied-SDBM_File-databases)
- [Badly encoded UTF-8 flagged scalars](#Badly-encoded-UTF-8-flagged-scalars)
- [Issues that exist only in blead, or in a release candidate](#Issues-that-exist-only-in-blead,-or-in-a-release-candidate)
- [CPAN modules or other Perl project resources](#CPAN-modules-or-other-Perl-project-resources)
- [Emulated POSIX behaviors on Windows systems](#Emulated-POSIX-behaviors-on-Windows-systems)
+ [Bugs that require special categorization](#Bugs-that-require-special-categorization)
- [Regular expressions](#Regular-expressions)
- [DB\_File, ODBM\_File, or GDBM\_File databases](#DB_File,-ODBM_File,-or-GDBM_File-databases)
- [Algorithmic complexity attacks](#Algorithmic-complexity-attacks)
* [HOW WE DEAL WITH SECURITY ISSUES](#HOW-WE-DEAL-WITH-SECURITY-ISSUES)
+ [Perl's vulnerability remediation workflow](#Perl's-vulnerability-remediation-workflow)
- [Initial contact](#Initial-contact)
- [Initial triage](#Initial-triage)
- [Issue ID assignment](#Issue-ID-assignment)
- [Development of patches](#Development-of-patches)
- [CVE ID assignment](#CVE-ID-assignment)
- [Pre-release notifications](#Pre-release-notifications)
- [Pre-release testing](#Pre-release-testing)
- [Release of fixes and announcements](#Release-of-fixes-and-announcements)
+ [Publicly known and zero-day security issues](#Publicly-known-and-zero-day-security-issues)
- [Zero-day security issues](#Zero-day-security-issues)
- [Other leaks of security issue information](#Other-leaks-of-security-issue-information)
+ [Vulnerability credit and bounties](#Vulnerability-credit-and-bounties)
- [Credits in vulnerability announcements](#Credits-in-vulnerability-announcements)
- [Bounties for Perl vulnerabilities](#Bounties-for-Perl-vulnerabilities)
NAME
----
perlsecpolicy - Perl security report handling policy
DESCRIPTION
-----------
The Perl project takes security issues seriously.
The responsibility for handling security reports in a timely and effective manner has been delegated to a security team composed of a subset of the Perl core developers.
This document describes how the Perl security team operates and how the team evaluates new security reports.
REPORTING SECURITY ISSUES IN PERL
----------------------------------
If you believe you have found a security vulnerability in the Perl interpreter or modules maintained in the core Perl codebase, email the details to [[email protected]](mailto:[email protected]). This address is a closed membership mailing list monitored by the Perl security team.
You should receive an initial response to your report within 72 hours. If you do not receive a response in that time, please contact the [Perl Steering Council](mailto:[email protected]).
When members of the security team reply to your messages, they will generally include the [email protected] address in the "To" or "CC" fields of the response. This allows all of the security team to follow the discussion and chime in as needed. Use the "Reply-all" functionality of your email client when you send subsequent responses so that the entire security team receives the message.
The security team will evaluate your report and make an initial determination of whether it is likely to fit the scope of issues the team handles. General guidelines about how this is determined are detailed in the ["WHAT ARE SECURITY ISSUES"](#WHAT-ARE-SECURITY-ISSUES) section.
If your report meets the team's criteria, an issue will be opened in the team's private issue tracker and you will be provided the issue's ID number. Issue identifiers have the form perl-security#NNN. Include this identifier with any subsequent messages you send.
The security team will send periodic updates about the status of your issue and guide you through any further action that is required to complete the vulnerability remediation process. The stages vulnerabilities typically go through are explained in the ["HOW WE DEAL WITH SECURITY ISSUES"](#HOW-WE-DEAL-WITH-SECURITY-ISSUES) section.
WHAT ARE SECURITY ISSUES
-------------------------
A vulnerability is a behavior of a software system that compromises the system's expected confidentiality, integrity or availability protections.
A security issue is a bug in one or more specific components of a software system that creates a vulnerability.
Software written in the Perl programming language is typically composed of many layers of software written by many different groups. It can be very complicated to determine which specific layer of a complex real-world application was responsible for preventing a vulnerable behavior, but this is an essential part of fixing the vulnerability.
###
Software covered by the Perl security team
The Perl security team handles security issues in:
* The Perl interpreter
* The Perl modules shipped with the interpreter that are developed in the core Perl repository
* The command line tools shipped with the interpreter that are developed in the core Perl repository
Files under the *cpan/* directory in Perl's repository and release tarballs are developed and maintained independently. The Perl security team does not directly handle security issues for these modules, but since this code is bundled with Perl, we will assist in forwarding the issue to the relevant maintainer(s) and you can still report these issues to us in secrecy.
###
Bugs that may qualify as security issues in Perl
Perl is designed to be a fast and flexible general purpose programming language. The Perl interpreter and Perl modules make writing safe and secure applications easy, but they do have limitations.
As a general rule, a bug in Perl needs to meet all of the following criteria to be considered a security issue:
* The vulnerable behavior is not mentioned in Perl's documentation or public issue tracker.
* The vulnerable behavior is not implied by an expected behavior.
* The vulnerable behavior is not a generally accepted limitation of the implementation.
* The vulnerable behavior is likely to be exposed to attack in otherwise secure applications written in Perl.
* The vulnerable behavior provides a specific tangible benefit to an attacker that triggers the behavior.
###
Bugs that do not qualify as security issues in Perl
There are certain categories of bugs that are frequently reported to the security team that do not meet the criteria listed above.
The following is a list of commonly reported bugs that are not handled as security issues.
####
Feeding untrusted code to the interpreter
The Perl parser is not designed to evaluate untrusted code. If your application requires the evaluation of untrusted code, it should rely on an operating system level sandbox for its security.
####
Stack overflows due to excessive recursion
Excessive recursion is often caused by code that does not enforce limits on inputs. The Perl interpreter assumes limits on recursion will be enforced by the application.
####
Out of memory errors
Common Perl constructs such as `pack`, the `x` operator, and regular expressions accept numeric quantifiers that control how much memory will be allocated to store intermediate values or results. If you allow an attacker to supply these quantifiers and consume all available memory, the Perl interpreter will not prevent it.
####
Escape from a [Safe](safe) compartment
[Opcode](opcode) restrictions and [Safe](safe) compartments are not supported as security mechanisms. The Perl parser is not designed to evaluate untrusted code.
####
Use of the `p` and `P` pack templates
These templates are unsafe by design.
####
Stack not reference-counted issues
These bugs typically present as use-after-free errors or as assertion failures on the type of a `SV`. Stack not reference-counted crashes usually occur because code is both modifying a reference or glob and using the values referenced by that glob or reference.
This type of bug is a long standing issue with the Perl interpreter that seldom occurs in normal code. Examples of this type of bug generally assume that attacker-supplied code will be evaluated by the Perl interpreter.
####
Thawing attacker-supplied data with [Storable](storable)
[Storable](storable) is designed to be a very fast serialization format. It is not designed to be safe for deserializing untrusted inputs.
####
Using attacker supplied [SDBM\_File](sdbm_file) databases
The [SDBM\_File](sdbm_file) module is not intended for use with untrusted SDBM databases.
####
Badly encoded UTF-8 flagged scalars
This type of bug occurs when the `:utf8` PerlIO layer is used to read badly encoded data, or other mechanisms are used to directly manipulate the UTF-8 flag on an SV.
A badly encoded UTF-8 flagged SV is not a valid SV. Code that creates SV's in this fashion is corrupting Perl's internal state.
####
Issues that exist only in blead, or in a release candidate
The blead branch and Perl release candidates do not receive security support. Security defects that are present only in pre-release versions of Perl are handled through the normal bug reporting and resolution process.
####
CPAN modules or other Perl project resources
The Perl security team is focused on the Perl interpreter and modules maintained in the core Perl codebase. The team has no special access to fix CPAN modules, applications written in Perl, Perl project websites, Perl mailing lists or the Perl IRC servers.
####
Emulated POSIX behaviors on Windows systems
The Perl interpreter attempts to emulate `fork`, `system`, `exec` and other POSIX behaviors on Windows systems. This emulation has many quirks that are extensively documented in Perl's public issue tracker. Changing these behaviors would cause significant disruption for existing users on Windows.
###
Bugs that require special categorization
Some bugs in the Perl interpreter occur in areas of the codebase that are both security sensitive and prone to failure during normal usage.
####
Regular expressions
Untrusted regular expressions are generally safe to compile and match against with several caveats. The following behaviors of Perl's regular expression engine are the developer's responsibility to constrain.
The evaluation of untrusted regular expressions while `use re 'eval';` is in effect is never safe.
Regular expressions are not guaranteed to compile or evaluate in any specific finite time frame.
Regular expressions may consume all available system memory when they are compiled or evaluated.
Regular expressions may cause excessive recursion that halts the perl interpreter.
As a general rule, do not expect Perl's regular expression engine to be resistant to denial of service attacks.
####
[DB\_File](db_file), [ODBM\_File](odbm_file), or [GDBM\_File](gdbm_file) databases
These modules rely on external libraries to interact with database files.
Bugs caused by reading and writing these file formats are generally caused by the underlying library implementation and are not security issues in Perl.
Bugs where Perl mishandles unexpected valid return values from the underlying libraries may qualify as security issues in Perl.
####
Algorithmic complexity attacks
The perl interpreter is reasonably robust to algorithmic complexity attacks. It is not immune to them.
Algorithmic complexity bugs that depend on the interpreter processing extremely large amounts of attacker supplied data are not generally handled as security issues.
See ["Algorithmic Complexity Attacks" in perlsec](perlsec#Algorithmic-Complexity-Attacks) for additional information.
HOW WE DEAL WITH SECURITY ISSUES
---------------------------------
The Perl security team follows responsible disclosure practices. Security issues are kept secret until a fix is readily available for most users. This minimizes inherent risks users face from vulnerabilities in Perl.
Hiding problems from the users temporarily is a necessary trade-off to keep them safe. Hiding problems from users permanently is not the goal.
When you report a security issue privately to the [[email protected]](mailto:[email protected]) contact address, we normally expect you to follow responsible disclosure practices in the handling of the report. If you are unable or unwilling to keep the issue secret until a fix is available to users you should state this clearly in the initial report.
The security team's vulnerability remediation workflow is intended to be as open and transparent as possible about the state of your security report.
###
Perl's vulnerability remediation workflow
####
Initial contact
New vulnerability reports will receive an initial reply within 72 hours from the time they arrive at the security team's mailing list. If you do not receive any response in that time, contact the [Perl Steering Council](mailto:[email protected]).
The initial response sent by the security team will confirm your message was received and provide an estimated time frame for the security team's triage analysis.
####
Initial triage
The security team will evaluate the report and determine whether or not it is likely to meet the criteria for handling as a security issue.
The security team aims to complete the initial report triage within two weeks' time. Complex issues that require significant discussion or research may take longer.
If the security report cannot be reproduced or does not meet the team's criteria for handling as a security issue, you will be notified by email and given an opportunity to respond.
####
Issue ID assignment
Security reports that pass initial triage analysis are turned into issues in the security team's private issue tracker. When a report progresses to this point you will be provided the issue ID for future reference. These identifiers have the format perl-security#NNN or Perl/perl-security#NNN.
The assignment of an issue ID does not confirm that a security report represents a vulnerability in Perl. Many reports require further analysis to reach that determination.
Issues in the security team's private tracker are used to collect details about the problem and track progress towards a resolution. These notes and other details are not made public when the issue is resolved. Keeping the issue notes private allows the security team to freely discuss attack methods, attack tools, and other related private issues.
####
Development of patches
Members of the security team will inspect the report and related code in detail to produce fixes for supported versions of Perl.
If the team discovers that the reported issue does not meet the team's criteria at this stage, you will be notified by email and given an opportunity to respond before the issue is closed.
The team may discuss potential fixes with you or provide you with patches for testing purposes during this time frame. No information should be shared publicly at this stage.
####
CVE ID assignment
Once an issue is fully confirmed and a potential fix has been found, the security team will request a CVE identifier for the issue to use in public announcements.
Details like the range of vulnerable Perl versions and identities of the people that discovered the flaw need to be collected to submit the CVE ID request.
The security team may ask you to clarify the exact name we should use when crediting discovery of the issue. The ["Vulnerability credit and bounties"](#Vulnerability-credit-and-bounties) section of this document explains our preferred format for this credit.
Once a CVE ID has been assigned, you will be notified by email. The vulnerability should not be discussed publicly at this stage.
####
Pre-release notifications
When the security team is satisfied that the fix for a security issue is ready to release publicly, a pre-release notification announcement is sent to the major redistributors of Perl.
This pre-release announcement includes a list of Perl versions that are affected by the flaw, an analysis of the risks to users, patches the security team has produced, and any information about mitigations or backporting fixes to older versions of Perl that the security team has available.
The pre-release announcement will include a specific target date when the issue will be announced publicly. The time frame between the pre-release announcement and the release date allows redistributors to prepare and test their own updates and announcements. During this period the vulnerability details and fixes are embargoed and should not be shared publicly. This embargo period may be extended further if problems are discovered during testing.
You will be sent the portions of pre-release announcements that are relevant to the specific issue you reported. This email will include the target release date. Additional updates will be sent if the target release date changes.
####
Pre-release testing
The Perl security team does not directly produce official Perl releases. The team releases security fixes by placing commits in Perl's public git repository and sending announcements.
Many users and redistributors prefer using official Perl releases rather than applying patches to an older release. The security team works with Perl's release managers to make this possible.
New official releases of Perl are generally produced and tested on private systems during the pre-release embargo period.
####
Release of fixes and announcements
At the end of the embargo period the security fixes will be committed to Perl's public git repository and announcements will be sent to the [perl5-porters](https://lists.perl.org/list/perl5-porters.html) and [oss-security](https://oss-security.openwall.org/wiki/mailing-lists/oss-security) mailing lists.
If official Perl releases are ready, they will be published at this time and announced on the [perl5-porters](https://lists.perl.org/list/perl5-porters.html) mailing list.
The security team will send a follow-up notification to everyone that participated in the pre-release embargo period once the release process is finished. Vulnerability reporters and Perl redistributors should not publish their own announcements or fixes until the Perl security team's release process is complete.
###
Publicly known and zero-day security issues
The security team's vulnerability remediation workflow assumes that issues are reported privately and kept secret until they are resolved. This isn't always the case and information occasionally leaks out before a fix is ready.
In these situations the team must decide whether operating in secret increases or decreases the risk to users of Perl. In some cases being open about the risk a security issue creates will allow users to defend against it, in other cases calling attention to an unresolved security issue will make it more likely to be misused.
####
Zero-day security issues
If an unresolved critical security issue in Perl is being actively abused to attack systems the security team will send out announcements as rapidly as possible with any mitigations the team has available.
Perl's public defect tracker will be used to handle the issue so that additional information, fixes, and CVE IDs are visible to affected users as rapidly as possible.
####
Other leaks of security issue information
Depending on the prominence of the information revealed about a security issue and the issue's risk of becoming a zero-day attack, the security team may skip all or part of its normal remediation workflow.
If the security team learns of a significant security issue after it has been identified and resolved in Perl's public issue tracker, the team will request a CVE ID and send an announcement to inform users.
###
Vulnerability credit and bounties
The Perl project appreciates the effort security researchers invest in making Perl safe and secure.
Since much of this work is hidden from the public, crediting researchers publicly is an important part of the vulnerability remediation process.
####
Credits in vulnerability announcements
When security issues are fixed we will attempt to credit the specific researcher(s) that discovered the flaw in our announcements.
Credits are announced using the researcher's preferred full name.
If the researcher's contributions were funded by a specific company or part of an organized vulnerability research project, we will include a short name for this group at the researcher's request.
Perl's announcements are written in the English language using the 7bit ASCII character set to be reproducible in a variety of formats. We do not include hyperlinks, domain names or marketing material with these acknowledgments.
In the event that proper credit for vulnerability discovery cannot be established or there is a disagreement between the Perl security team and the researcher about how the credit should be given, it will be omitted from announcements.
####
Bounties for Perl vulnerabilities
The Perl project is a non-profit volunteer effort. We do not provide any monetary rewards for reporting security issues in Perl.
The [Internet Bug Bounty](https://internetbugbounty.org/) offers monetary rewards for some Perl security issues after they are fully resolved. The terms of this program are available at [HackerOne](https://hackerone.com/ibb-perl).
This program is not run by the Perl project or the Perl security team.
| programming_docs |
perl Locale::Maketext Locale::Maketext
================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [QUICK OVERVIEW](#QUICK-OVERVIEW)
* [METHODS](#METHODS)
+ [Construction Methods](#Construction-Methods)
+ [The "maketext" Method](#The-%22maketext%22-Method)
+ [Utility Methods](#Utility-Methods)
+ [Language Handle Attributes and Internals](#Language-Handle-Attributes-and-Internals)
* [LANGUAGE CLASS HIERARCHIES](#LANGUAGE-CLASS-HIERARCHIES)
* [ENTRIES IN EACH LEXICON](#ENTRIES-IN-EACH-LEXICON)
* [BRACKET NOTATION](#BRACKET-NOTATION)
* [BRACKET NOTATION SECURITY](#BRACKET-NOTATION-SECURITY)
* [AUTO LEXICONS](#AUTO-LEXICONS)
* [READONLY LEXICONS](#READONLY-LEXICONS)
* [CONTROLLING LOOKUP FAILURE](#CONTROLLING-LOOKUP-FAILURE)
* [HOW TO USE MAKETEXT](#HOW-TO-USE-MAKETEXT)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMER](#COPYRIGHT-AND-DISCLAIMER)
* [AUTHOR](#AUTHOR)
NAME
----
Locale::Maketext - framework for localization
SYNOPSIS
--------
```
package MyProgram;
use strict;
use MyProgram::L10N;
# ...which inherits from Locale::Maketext
my $lh = MyProgram::L10N->get_handle() || die "What language?";
...
# And then any messages your program emits, like:
warn $lh->maketext( "Can't open file [_1]: [_2]\n", $f, $! );
...
```
DESCRIPTION
-----------
It is a common feature of applications (whether run directly, or via the Web) for them to be "localized" -- i.e., for them to a present an English interface to an English-speaker, a German interface to a German-speaker, and so on for all languages it's programmed with. Locale::Maketext is a framework for software localization; it provides you with the tools for organizing and accessing the bits of text and text-processing code that you need for producing localized applications.
In order to make sense of Maketext and how all its components fit together, you should probably go read <Locale::Maketext::TPJ13>, and *then* read the following documentation.
You may also want to read over the source for `File::Findgrep` and its constituent modules -- they are a complete (if small) example application that uses Maketext.
QUICK OVERVIEW
---------------
The basic design of Locale::Maketext is object-oriented, and Locale::Maketext is an abstract base class, from which you derive a "project class". The project class (with a name like "TkBocciBall::Localize", which you then use in your module) is in turn the base class for all the "language classes" for your project (with names "TkBocciBall::Localize::it", "TkBocciBall::Localize::en", "TkBocciBall::Localize::fr", etc.).
A language class is a class containing a lexicon of phrases as class data, and possibly also some methods that are of use in interpreting phrases in the lexicon, or otherwise dealing with text in that language.
An object belonging to a language class is called a "language handle"; it's typically a flyweight object.
The normal course of action is to call:
```
use TkBocciBall::Localize; # the localization project class
$lh = TkBocciBall::Localize->get_handle();
# Depending on the user's locale, etc., this will
# make a language handle from among the classes available,
# and any defaults that you declare.
die "Couldn't make a language handle??" unless $lh;
```
From then on, you use the `maketext` function to access entries in whatever lexicon(s) belong to the language handle you got. So, this:
```
print $lh->maketext("You won!"), "\n";
```
...emits the right text for this language. If the object in `$lh` belongs to class "TkBocciBall::Localize::fr" and %TkBocciBall::Localize::fr::Lexicon contains `("You won!" => "Tu as gagné!")`, then the above code happily tells the user "Tu as gagné!".
METHODS
-------
Locale::Maketext offers a variety of methods, which fall into three categories:
* Methods to do with constructing language handles.
* `maketext` and other methods to do with accessing %Lexicon data for a given language handle.
* Methods that you may find it handy to use, from routines of yours that you put in %Lexicon entries.
These are covered in the following section.
###
Construction Methods
These are to do with constructing a language handle:
* $lh = YourProjClass->get\_handle( ...langtags... ) || die "lg-handle?";
This tries loading classes based on the language-tags you give (like `("en-US", "sk", "kon", "es-MX", "ja", "i-klingon")`, and for the first class that succeeds, returns YourProjClass::*language*->new().
If it runs thru the entire given list of language-tags, and finds no classes for those exact terms, it then tries "superordinate" language classes. So if no "en-US" class (i.e., YourProjClass::en\_us) was found, nor classes for anything else in that list, we then try its superordinate, "en" (i.e., YourProjClass::en), and so on thru the other language-tags in the given list: "es". (The other language-tags in our example list: happen to have no superordinates.)
If none of those language-tags leads to loadable classes, we then try classes derived from YourProjClass->fallback\_languages() and then if nothing comes of that, we use classes named by YourProjClass->fallback\_language\_classes(). Then in the (probably quite unlikely) event that that fails, we just return undef.
* $lh = YourProjClass->get\_handle**()** || die "lg-handle?";
When `get_handle` is called with an empty parameter list, magic happens:
If `get_handle` senses that it's running in program that was invoked as a CGI, then it tries to get language-tags out of the environment variable "HTTP\_ACCEPT\_LANGUAGE", and it pretends that those were the languages passed as parameters to `get_handle`.
Otherwise (i.e., if not a CGI), this tries various OS-specific ways to get the language-tags for the current locale/language, and then pretends that those were the value(s) passed to `get_handle`.
Currently this OS-specific stuff consists of looking in the environment variables "LANG" and "LANGUAGE"; and on MSWin machines (where those variables are typically unused), this also tries using the module Win32::Locale to get a language-tag for whatever language/locale is currently selected in the "Regional Settings" (or "International"?) Control Panel. I welcome further suggestions for making this do the Right Thing under other operating systems that support localization.
If you're using localization in an application that keeps a configuration file, you might consider something like this in your project class:
```
sub get_handle_via_config {
my $class = $_[0];
my $chosen_language = $Config_settings{'language'};
my $lh;
if($chosen_language) {
$lh = $class->get_handle($chosen_language)
|| die "No language handle for \"$chosen_language\""
. " or the like";
} else {
# Config file missing, maybe?
$lh = $class->get_handle()
|| die "Can't get a language handle";
}
return $lh;
}
```
* $lh = YourProjClass::langname->new();
This constructs a language handle. You usually **don't** call this directly, but instead let `get_handle` find a language class to `use` and to then call ->new on.
* $lh->init();
This is called by ->new to initialize newly-constructed language handles. If you define an init method in your class, remember that it's usually considered a good idea to call $lh->SUPER::init in it (presumably at the beginning), so that all classes get a chance to initialize a new object however they see fit.
* YourProjClass->fallback\_languages()
`get_handle` appends the return value of this to the end of whatever list of languages you pass `get_handle`. Unless you override this method, your project class will inherit Locale::Maketext's `fallback_languages`, which currently returns `('i-default', 'en', 'en-US')`. ("i-default" is defined in RFC 2277).
This method (by having it return the name of a language-tag that has an existing language class) can be used for making sure that `get_handle` will always manage to construct a language handle (assuming your language classes are in an appropriate @INC directory). Or you can use the next method:
* YourProjClass->fallback\_language\_classes()
`get_handle` appends the return value of this to the end of the list of classes it will try using. Unless you override this method, your project class will inherit Locale::Maketext's `fallback_language_classes`, which currently returns an empty list, `()`. By setting this to some value (namely, the name of a loadable language class), you can be sure that `get_handle` will always manage to construct a language handle.
###
The "maketext" Method
This is the most important method in Locale::Maketext:
```
$text = $lh->maketext(I<key>, ...parameters for this phrase...);
```
This looks in the %Lexicon of the language handle $lh and all its superclasses, looking for an entry whose key is the string *key*. Assuming such an entry is found, various things then happen, depending on the value found:
If the value is a scalarref, the scalar is dereferenced and returned (and any parameters are ignored).
If the value is a coderef, we return &$value($lh, ...parameters...).
If the value is a string that *doesn't* look like it's in Bracket Notation, we return it (after replacing it with a scalarref, in its %Lexicon).
If the value *does* look like it's in Bracket Notation, then we compile it into a sub, replace the string in the %Lexicon with the new coderef, and then we return &$new\_sub($lh, ...parameters...).
Bracket Notation is discussed in a later section. Note that trying to compile a string into Bracket Notation can throw an exception if the string is not syntactically valid (say, by not balancing brackets right.)
Also, calling &$coderef($lh, ...parameters...) can throw any sort of exception (if, say, code in that sub tries to divide by zero). But a very common exception occurs when you have Bracket Notation text that says to call a method "foo", but there is no such method. (E.g., "You have [qua**tn**,\_1,ball]." will throw an exception on trying to call $lh->qua**tn**($\_[1],'ball') -- you presumably meant "quant".) `maketext` catches these exceptions, but only to make the error message more readable, at which point it rethrows the exception.
An exception *may* be thrown if *key* is not found in any of $lh's %Lexicon hashes. What happens if a key is not found, is discussed in a later section, "Controlling Lookup Failure".
Note that you might find it useful in some cases to override the `maketext` method with an "after method", if you want to translate encodings, or even scripts:
```
package YrProj::zh_cn; # Chinese with PRC-style glyphs
use base ('YrProj::zh_tw'); # Taiwan-style
sub maketext {
my $self = shift(@_);
my $value = $self->maketext(@_);
return Chineeze::taiwan2mainland($value);
}
```
Or you may want to override it with something that traps any exceptions, if that's critical to your program:
```
sub maketext {
my($lh, @stuff) = @_;
my $out;
eval { $out = $lh->SUPER::maketext(@stuff) };
return $out unless $@;
...otherwise deal with the exception...
}
```
Other than those two situations, I don't imagine that it's useful to override the `maketext` method. (If you run into a situation where it is useful, I'd be interested in hearing about it.)
$lh->fail\_with *or* $lh->fail\_with(*PARAM*)
$lh->failure\_handler\_auto These two methods are discussed in the section "Controlling Lookup Failure".
$lh->denylist(@list) <or> $lh->blacklist(@list)
$lh->allowlist(@list) <or> $lh->whitelist(@list) These methods are discussed in the section "Bracket Notation Security".
###
Utility Methods
These are methods that you may find it handy to use, generally from %Lexicon routines of yours (whether expressed as Bracket Notation or not).
$language->quant($number, $singular)
$language->quant($number, $singular, $plural)
$language->quant($number, $singular, $plural, $negative) This is generally meant to be called from inside Bracket Notation (which is discussed later), as in
```
"Your search matched [quant,_1,document]!"
```
It's for *quantifying* a noun (i.e., saying how much of it there is, while giving the correct form of it). The behavior of this method is handy for English and a few other Western European languages, and you should override it for languages where it's not suitable. You can feel free to read the source, but the current implementation is basically as this pseudocode describes:
```
if $number is 0 and there's a $negative,
return $negative;
elsif $number is 1,
return "1 $singular";
elsif there's a $plural,
return "$number $plural";
else
return "$number " . $singular . "s";
#
# ...except that we actually call numf to
# stringify $number before returning it.
```
So for English (with Bracket Notation) `"...[quant,_1,file]..."` is fine (for 0 it returns "0 files", for 1 it returns "1 file", and for more it returns "2 files", etc.)
But for "directory", you'd want `"[quant,_1,directory,directories]"` so that our elementary `quant` method doesn't think that the plural of "directory" is "directorys". And you might find that the output may sound better if you specify a negative form, as in:
```
"[quant,_1,file,files,No files] matched your query.\n"
```
Remember to keep in mind verb agreement (or adjectives too, in other languages), as in:
```
"[quant,_1,document] were matched.\n"
```
Because if \_1 is one, you get "1 document **were** matched". An acceptable hack here is to do something like this:
```
"[quant,_1,document was, documents were] matched.\n"
```
$language->numf($number) This returns the given number formatted nicely according to this language's conventions. Maketext's default method is mostly to just take the normal string form of the number (applying sprintf "%G" for only very large numbers), and then to add commas as necessary. (Except that we apply `tr/,./.,/` if $language->{'numf\_comma'} is true; that's a bit of a hack that's useful for languages that express two million as "2.000.000" and not as "2,000,000").
If you want anything fancier, consider overriding this with something that uses <Number::Format>, or does something else entirely.
Note that numf is called by quant for stringifying all quantifying numbers.
$language->numerate($number, $singular, $plural, $negative) This returns the given noun form which is appropriate for the quantity `$number` according to this language's conventions. `numerate` is used internally by `quant` to quantify nouns. Use it directly -- usually from bracket notation -- to avoid `quant`'s implicit call to `numf` and output of a numeric quantity.
$language->sprintf($format, @items) This is just a wrapper around Perl's normal `sprintf` function. It's provided so that you can use "sprintf" in Bracket Notation:
```
"Couldn't access datanode [sprintf,%10x=~[%s~],_1,_2]!\n"
```
returning...
```
Couldn't access datanode Stuff=[thangamabob]!
```
$language->language\_tag() Currently this just takes the last bit of `ref($language)`, turns underscores to dashes, and returns it. So if $language is an object of class Hee::HOO::Haw::en\_us, $language->language\_tag() returns "en-us". (Yes, the usual representation for that language tag is "en-US", but case is *never* considered meaningful in language-tag comparison.)
You may override this as you like; Maketext doesn't use it for anything.
$language->encoding() Currently this isn't used for anything, but it's provided (with default value of `(ref($language) && $language->{'encoding'})) or "iso-8859-1"` ) as a sort of suggestion that it may be useful/necessary to associate encodings with your language handles (whether on a per-class or even per-handle basis.)
###
Language Handle Attributes and Internals
A language handle is a flyweight object -- i.e., it doesn't (necessarily) carry any data of interest, other than just being a member of whatever class it belongs to.
A language handle is implemented as a blessed hash. Subclasses of yours can store whatever data you want in the hash. Currently the only hash entry used by any crucial Maketext method is "fail", so feel free to use anything else as you like.
**Remember: Don't be afraid to read the Maketext source if there's any point on which this documentation is unclear.** This documentation is vastly longer than the module source itself.
LANGUAGE CLASS HIERARCHIES
---------------------------
These are Locale::Maketext's assumptions about the class hierarchy formed by all your language classes:
* You must have a project base class, which you load, and which you then use as the first argument in the call to YourProjClass->get\_handle(...). It should derive (whether directly or indirectly) from Locale::Maketext. It **doesn't matter** how you name this class, although assuming this is the localization component of your Super Mega Program, good names for your project class might be SuperMegaProgram::Localization, SuperMegaProgram::L10N, SuperMegaProgram::I18N, SuperMegaProgram::International, or even SuperMegaProgram::Languages or SuperMegaProgram::Messages.
* Language classes are what YourProjClass->get\_handle will try to load. It will look for them by taking each language-tag (**skipping** it if it doesn't look like a language-tag or locale-tag!), turning it to all lowercase, turning dashes to underscores, and appending it to YourProjClass . "::". So this:
```
$lh = YourProjClass->get_handle(
'en-US', 'fr', 'kon', 'i-klingon', 'i-klingon-romanized'
);
```
will try loading the classes YourProjClass::en\_us (note lowercase!), YourProjClass::fr, YourProjClass::kon, YourProjClass::i\_klingon and YourProjClass::i\_klingon\_romanized. (And it'll stop at the first one that actually loads.)
* I assume that each language class derives (directly or indirectly) from your project class, and also defines its @ISA, its %Lexicon, or both. But I anticipate no dire consequences if these assumptions do not hold.
* Language classes may derive from other language classes (although they should have "use *Thatclassname*" or "use base qw(*...classes...*)"). They may derive from the project class. They may derive from some other class altogether. Or via multiple inheritance, it may derive from any mixture of these.
* I foresee no problems with having multiple inheritance in your hierarchy of language classes. (As usual, however, Perl will complain bitterly if you have a cycle in the hierarchy: i.e., if any class is its own ancestor.)
ENTRIES IN EACH LEXICON
------------------------
A typical %Lexicon entry is meant to signify a phrase, taking some number (0 or more) of parameters. An entry is meant to be accessed by via a string *key* in $lh->maketext(*key*, ...parameters...), which should return a string that is generally meant for be used for "output" to the user -- regardless of whether this actually means printing to STDOUT, writing to a file, or putting into a GUI widget.
While the key must be a string value (since that's a basic restriction that Perl places on hash keys), the value in the lexicon can currently be of several types: a defined scalar, scalarref, or coderef. The use of these is explained above, in the section 'The "maketext" Method', and Bracket Notation for strings is discussed in the next section.
While you can use arbitrary unique IDs for lexicon keys (like "\_min\_larger\_max\_error"), it is often useful for if an entry's key is itself a valid value, like this example error message:
```
"Minimum ([_1]) is larger than maximum ([_2])!\n",
```
Compare this code that uses an arbitrary ID...
```
die $lh->maketext( "_min_larger_max_error", $min, $max )
if $min > $max;
```
...to this code that uses a key-as-value:
```
die $lh->maketext(
"Minimum ([_1]) is larger than maximum ([_2])!\n",
$min, $max
) if $min > $max;
```
The second is, in short, more readable. In particular, it's obvious that the number of parameters you're feeding to that phrase (two) is the number of parameters that it *wants* to be fed. (Since you see \_1 and a \_2 being used in the key there.)
Also, once a project is otherwise complete and you start to localize it, you can scrape together all the various keys you use, and pass it to a translator; and then the translator's work will go faster if what he's presented is this:
```
"Minimum ([_1]) is larger than maximum ([_2])!\n",
=> "", # fill in something here, Jacques!
```
rather than this more cryptic mess:
```
"_min_larger_max_error"
=> "", # fill in something here, Jacques
```
I think that keys as lexicon values makes the completed lexicon entries more readable:
```
"Minimum ([_1]) is larger than maximum ([_2])!\n",
=> "Le minimum ([_1]) est plus grand que le maximum ([_2])!\n",
```
Also, having valid values as keys becomes very useful if you set up an \_AUTO lexicon. \_AUTO lexicons are discussed in a later section.
I almost always use keys that are themselves valid lexicon values. One notable exception is when the value is quite long. For example, to get the screenful of data that a command-line program might return when given an unknown switch, I often just use a brief, self-explanatory key such as "\_USAGE\_MESSAGE". At that point I then go and immediately to define that lexicon entry in the ProjectClass::L10N::en lexicon (since English is always my "project language"):
```
'_USAGE_MESSAGE' => <<'EOSTUFF',
...long long message...
EOSTUFF
```
and then I can use it as:
```
getopt('oDI', \%opts) or die $lh->maketext('_USAGE_MESSAGE');
```
Incidentally, note that each class's `%Lexicon` inherits-and-extends the lexicons in its superclasses. This is not because these are special hashes *per se*, but because you access them via the `maketext` method, which looks for entries across all the `%Lexicon` hashes in a language class *and* all its ancestor classes. (This is because the idea of "class data" isn't directly implemented in Perl, but is instead left to individual class-systems to implement as they see fit..)
Note that you may have things stored in a lexicon besides just phrases for output: for example, if your program takes input from the keyboard, asking a "(Y/N)" question, you probably need to know what the equivalent of "Y[es]/N[o]" is in whatever language. You probably also need to know what the equivalents of the answers "y" and "n" are. You can store that information in the lexicon (say, under the keys "~answer\_y" and "~answer\_n", and the long forms as "~answer\_yes" and "~answer\_no", where "~" is just an ad-hoc character meant to indicate to programmers/translators that these are not phrases for output).
Or instead of storing this in the language class's lexicon, you can (and, in some cases, really should) represent the same bit of knowledge as code in a method in the language class. (That leaves a tidy distinction between the lexicon as the things we know how to *say*, and the rest of the things in the lexicon class as things that we know how to *do*.) Consider this example of a processor for responses to French "oui/non" questions:
```
sub y_or_n {
return undef unless defined $_[1] and length $_[1];
my $answer = lc $_[1]; # smash case
return 1 if $answer eq 'o' or $answer eq 'oui';
return 0 if $answer eq 'n' or $answer eq 'non';
return undef;
}
```
...which you'd then call in a construct like this:
```
my $response;
until(defined $response) {
print $lh->maketext("Open the pod bay door (y/n)? ");
$response = $lh->y_or_n( get_input_from_keyboard_somehow() );
}
if($response) { $pod_bay_door->open() }
else { $pod_bay_door->leave_closed() }
```
Other data worth storing in a lexicon might be things like filenames for language-targetted resources:
```
...
"_main_splash_png"
=> "/styles/en_us/main_splash.png",
"_main_splash_imagemap"
=> "/styles/en_us/main_splash.incl",
"_general_graphics_path"
=> "/styles/en_us/",
"_alert_sound"
=> "/styles/en_us/hey_there.wav",
"_forward_icon"
=> "left_arrow.png",
"_backward_icon"
=> "right_arrow.png",
# In some other languages, left equals
# BACKwards, and right is FOREwards.
...
```
You might want to do the same thing for expressing key bindings or the like (since hardwiring "q" as the binding for the function that quits a screen/menu/program is useful only if your language happens to associate "q" with "quit"!)
BRACKET NOTATION
-----------------
Bracket Notation is a crucial feature of Locale::Maketext. I mean Bracket Notation to provide a replacement for the use of sprintf formatting. Everything you do with Bracket Notation could be done with a sub block, but bracket notation is meant to be much more concise.
Bracket Notation is a like a miniature "template" system (in the sense of <Text::Template>, not in the sense of C++ templates), where normal text is passed thru basically as is, but text in special regions is specially interpreted. In Bracket Notation, you use square brackets ("[...]"), not curly braces ("{...}") to note sections that are specially interpreted.
For example, here all the areas that are taken literally are underlined with a "^", and all the in-bracket special regions are underlined with an X:
```
"Minimum ([_1]) is larger than maximum ([_2])!\n",
^^^^^^^^^ XX ^^^^^^^^^^^^^^^^^^^^^^^^^^ XX ^^^^
```
When that string is compiled from bracket notation into a real Perl sub, it's basically turned into:
```
sub {
my $lh = $_[0];
my @params = @_;
return join '',
"Minimum (",
...some code here...
") is larger than maximum (",
...some code here...
")!\n",
}
# to be called by $lh->maketext(KEY, params...)
```
In other words, text outside bracket groups is turned into string literals. Text in brackets is rather more complex, and currently follows these rules:
* Bracket groups that are empty, or which consist only of whitespace, are ignored. (Examples: "[]", "[ ]", or a [ and a ] with returns and/or tabs and/or spaces between them.
Otherwise, each group is taken to be a comma-separated group of items, and each item is interpreted as follows:
* An item that is "\_*digits*" or "\_-*digits*" is interpreted as $\_[*value*]. I.e., "\_1" becomes with $\_[1], and "\_-3" is interpreted as $\_[-3] (in which case @\_ should have at least three elements in it). Note that $\_[0] is the language handle, and is typically not named directly.
* An item "\_\*" is interpreted to mean "all of @\_ except $\_[0]". I.e., `@_[1..$#_]`. Note that this is an empty list in the case of calls like $lh->maketext(*key*) where there are no parameters (except $\_[0], the language handle).
* Otherwise, each item is interpreted as a string literal.
The group as a whole is interpreted as follows:
* If the first item in a bracket group looks like a method name, then that group is interpreted like this:
```
$lh->that_method_name(
...rest of items in this group...
),
```
* If the first item in a bracket group is "\*", it's taken as shorthand for the so commonly called "quant" method. Similarly, if the first item in a bracket group is "#", it's taken to be shorthand for "numf".
* If the first item in a bracket group is the empty-string, or "\_\*" or "\_*digits*" or "\_-*digits*", then that group is interpreted as just the interpolation of all its items:
```
join('',
...rest of items in this group...
),
```
Examples: "[\_1]" and "[,\_1]", which are synonymous; and "`[,ID-(,_4,-,_2,)]`", which compiles as `join "", "ID-(", $_[4], "-", $_[2], ")"`.
* Otherwise this bracket group is invalid. For example, in the group "[!@#,whatever]", the first item `"!@#"` is neither the empty-string, "\_*number*", "\_-*number*", "\_\*", nor a valid method name; and so Locale::Maketext will throw an exception of you try compiling an expression containing this bracket group.
Note, incidentally, that items in each group are comma-separated, not `/\s*,\s*/`-separated. That is, you might expect that this bracket group:
```
"Hoohah [foo, _1 , bar ,baz]!"
```
would compile to this:
```
sub {
my $lh = $_[0];
return join '',
"Hoohah ",
$lh->foo( $_[1], "bar", "baz"),
"!",
}
```
But it actually compiles as this:
```
sub {
my $lh = $_[0];
return join '',
"Hoohah ",
$lh->foo(" _1 ", " bar ", "baz"), # note the <space> in " bar "
"!",
}
```
In the notation discussed so far, the characters "[" and "]" are given special meaning, for opening and closing bracket groups, and "," has a special meaning inside bracket groups, where it separates items in the group. This begs the question of how you'd express a literal "[" or "]" in a Bracket Notation string, and how you'd express a literal comma inside a bracket group. For this purpose I've adopted "~" (tilde) as an escape character: "~[" means a literal '[' character anywhere in Bracket Notation (i.e., regardless of whether you're in a bracket group or not), and ditto for "~]" meaning a literal ']', and "~," meaning a literal comma. (Altho "," means a literal comma outside of bracket groups -- it's only inside bracket groups that commas are special.)
And on the off chance you need a literal tilde in a bracket expression, you get it with "~~".
Currently, an unescaped "~" before a character other than a bracket or a comma is taken to mean just a "~" and that character. I.e., "~X" means the same as "~~X" -- i.e., one literal tilde, and then one literal "X". However, by using "~X", you are assuming that no future version of Maketext will use "~X" as a magic escape sequence. In practice this is not a great problem, since first off you can just write "~~X" and not worry about it; second off, I doubt I'll add lots of new magic characters to bracket notation; and third off, you aren't likely to want literal "~" characters in your messages anyway, since it's not a character with wide use in natural language text.
Brackets must be balanced -- every openbracket must have one matching closebracket, and vice versa. So these are all **invalid**:
```
"I ate [quant,_1,rhubarb pie."
"I ate [quant,_1,rhubarb pie[."
"I ate quant,_1,rhubarb pie]."
"I ate quant,_1,rhubarb pie[."
```
Currently, bracket groups do not nest. That is, you **cannot** say:
```
"Foo [bar,baz,[quux,quuux]]\n";
```
If you need a notation that's that powerful, use normal Perl:
```
%Lexicon = (
...
"some_key" => sub {
my $lh = $_[0];
join '',
"Foo ",
$lh->bar('baz', $lh->quux('quuux')),
"\n",
},
...
);
```
Or write the "bar" method so you don't need to pass it the output from calling quux.
I do not anticipate that you will need (or particularly want) to nest bracket groups, but you are welcome to email me with convincing (real-life) arguments to the contrary.
BRACKET NOTATION SECURITY
--------------------------
Locale::Maketext does not use any special syntax to differentiate bracket notation methods from normal class or object methods. This design makes it vulnerable to format string attacks whenever it is used to process strings provided by untrusted users.
Locale::Maketext does support denylist and allowlist functionality to limit which methods may be called as bracket notation methods.
By default, Locale::Maketext denies all methods in the Locale::Maketext namespace that begin with the '\_' character, and all methods which include Perl's namespace separator characters.
The default denylist for Locale::Maketext also prevents use of the following methods in bracket notation:
```
denylist
encoding
fail_with
failure_handler_auto
fallback_language_classes
fallback_languages
get_handle
init
language_tag
maketext
new
allowlist
whitelist
blacklist
```
This list can be extended by either deny-listing additional "known bad" methods, or allow-listing only "known good" methods.
To prevent specific methods from being called in bracket notation, use the denylist() method:
```
my $lh = MyProgram::L10N->get_handle();
$lh->denylist(qw{my_internal_method my_other_method});
$lh->maketext('[my_internal_method]'); # dies
```
To limit the allowed bracked notation methods to a specific list, use the allowlist() method:
```
my $lh = MyProgram::L10N->get_handle();
$lh->allowlist('numerate', 'numf');
$lh->maketext('[_1] [numerate, _1,shoe,shoes]', 12); # works
$lh->maketext('[my_internal_method]'); # dies
```
The denylist() and allowlist() methods extend their internal lists whenever they are called. To reset the denylist or allowlist, create a new maketext object.
```
my $lh = MyProgram::L10N->get_handle();
$lh->denylist('numerate');
$lh->denylist('numf');
$lh->maketext('[_1] [numerate,_1,shoe,shoes]', 12); # dies
```
For lexicons that use an internal cache, translations which have already been cached in their compiled form are not affected by subsequent changes to the allowlist or denylist settings. Lexicons that use an external cache will have their cache cleared whenever the allowlist or denylist settings change. The difference between the two types of caching is explained in the "Readonly Lexicons" section.
Methods disallowed by the denylist cannot be permitted by the allowlist.
NOTE: denylist() is the preferred method name to use instead of the historical and non-inclusive method blacklist(). blacklist() may be removed in a future release of this package and so it's use should be removed from usage.
NOTE: allowlist() is the preferred method name to use instead of the historical and non-inclusive method whitelist(). whitelist() may be removed in a future release of this package and so it's use should be removed from usage.
AUTO LEXICONS
--------------
If maketext goes to look in an individual %Lexicon for an entry for *key* (where *key* does not start with an underscore), and sees none, **but does see** an entry of "\_AUTO" => *some\_true\_value*, then we actually define $Lexicon{*key*} = *key* right then and there, and then use that value as if it had been there all along. This happens before we even look in any superclass %Lexicons!
(This is meant to be somewhat like the AUTOLOAD mechanism in Perl's function call system -- or, looked at another way, like the [AutoLoader](autoloader) module.)
I can picture all sorts of circumstances where you just do not want lookup to be able to fail (since failing normally means that maketext throws a `die`, although see the next section for greater control over that). But here's one circumstance where \_AUTO lexicons are meant to be *especially* useful:
As you're writing an application, you decide as you go what messages you need to emit. Normally you'd go to write this:
```
if(-e $filename) {
go_process_file($filename)
} else {
print qq{Couldn't find file "$filename"!\n};
}
```
but since you anticipate localizing this, you write:
```
use ThisProject::I18N;
my $lh = ThisProject::I18N->get_handle();
# For the moment, assume that things are set up so
# that we load class ThisProject::I18N::en
# and that that's the class that $lh belongs to.
...
if(-e $filename) {
go_process_file($filename)
} else {
print $lh->maketext(
qq{Couldn't find file "[_1]"!\n}, $filename
);
}
```
Now, right after you've just written the above lines, you'd normally have to go open the file ThisProject/I18N/en.pm, and immediately add an entry:
```
"Couldn't find file \"[_1]\"!\n"
=> "Couldn't find file \"[_1]\"!\n",
```
But I consider that somewhat of a distraction from the work of getting the main code working -- to say nothing of the fact that I often have to play with the program a few times before I can decide exactly what wording I want in the messages (which in this case would require me to go changing three lines of code: the call to maketext with that key, and then the two lines in ThisProject/I18N/en.pm).
However, if you set "\_AUTO => 1" in the %Lexicon in, ThisProject/I18N/en.pm (assuming that English (en) is the language that all your programmers will be using for this project's internal message keys), then you don't ever have to go adding lines like this
```
"Couldn't find file \"[_1]\"!\n"
=> "Couldn't find file \"[_1]\"!\n",
```
to ThisProject/I18N/en.pm, because if \_AUTO is true there, then just looking for an entry with the key "Couldn't find file \"[\_1]\"!\n" in that lexicon will cause it to be added, with that value!
Note that the reason that keys that start with "\_" are immune to \_AUTO isn't anything generally magical about the underscore character -- I just wanted a way to have most lexicon keys be autoable, except for possibly a few, and I arbitrarily decided to use a leading underscore as a signal to distinguish those few.
READONLY LEXICONS
------------------
If your lexicon is a tied hash the simple act of caching the compiled value can be fatal.
For example a [GDBM\_File](gdbm_file) GDBM\_READER tied hash will die with something like:
```
gdbm store returned -1, errno 2, key "..." at ...
```
All you need to do is turn on caching outside of the lexicon hash itself like so:
```
sub init {
my ($lh) = @_;
...
$lh->{'use_external_lex_cache'} = 1;
...
}
```
And then instead of storing the compiled value in the lexicon hash it will store it in $lh->{'\_external\_lex\_cache'}
CONTROLLING LOOKUP FAILURE
---------------------------
If you call $lh->maketext(*key*, ...parameters...), and there's no entry *key* in $lh's class's %Lexicon, nor in the superclass %Lexicon hash, *and* if we can't auto-make *key* (because either it starts with a "\_", or because none of its lexicons have `_AUTO => 1,`), then we have failed to find a normal way to maketext *key*. What then happens in these failure conditions, depends on the $lh object's "fail" attribute.
If the language handle has no "fail" attribute, maketext will simply throw an exception (i.e., it calls `die`, mentioning the *key* whose lookup failed, and naming the line number where the calling $lh->maketext(*key*,...) was.
If the language handle has a "fail" attribute whose value is a coderef, then $lh->maketext(*key*,...params...) gives up and calls:
```
return $that_subref->($lh, $key, @params);
```
Otherwise, the "fail" attribute's value should be a string denoting a method name, so that $lh->maketext(*key*,...params...) can give up with:
```
return $lh->$that_method_name($phrase, @params);
```
The "fail" attribute can be accessed with the `fail_with` method:
```
# Set to a coderef:
$lh->fail_with( \&failure_handler );
# Set to a method name:
$lh->fail_with( 'failure_method' );
# Set to nothing (i.e., so failure throws a plain exception)
$lh->fail_with( undef );
# Get the current value
$handler = $lh->fail_with();
```
Now, as to what you may want to do with these handlers: Maybe you'd want to log what key failed for what class, and then die. Maybe you don't like `die` and instead you want to send the error message to STDOUT (or wherever) and then merely `exit()`.
Or maybe you don't want to `die` at all! Maybe you could use a handler like this:
```
# Make all lookups fall back onto an English value,
# but only after we log it for later fingerpointing.
my $lh_backup = ThisProject->get_handle('en');
open(LEX_FAIL_LOG, ">>wherever/lex.log") || die "GNAARGH $!";
sub lex_fail {
my($failing_lh, $key, $params) = @_;
print LEX_FAIL_LOG scalar(localtime), "\t",
ref($failing_lh), "\t", $key, "\n";
return $lh_backup->maketext($key,@params);
}
```
Some users have expressed that they think this whole mechanism of having a "fail" attribute at all, seems a rather pointless complication. But I want Locale::Maketext to be usable for software projects of *any* scale and type; and different software projects have different ideas of what the right thing is to do in failure conditions. I could simply say that failure always throws an exception, and that if you want to be careful, you'll just have to wrap every call to $lh->maketext in an eval { }. However, I want programmers to reserve the right (via the "fail" attribute) to treat lookup failure as something other than an exception of the same level of severity as a config file being unreadable, or some essential resource being inaccessible.
One possibly useful value for the "fail" attribute is the method name "failure\_handler\_auto". This is a method defined in the class Locale::Maketext itself. You set it with:
```
$lh->fail_with('failure_handler_auto');
```
Then when you call $lh->maketext(*key*, ...parameters...) and there's no *key* in any of those lexicons, maketext gives up with
```
return $lh->failure_handler_auto($key, @params);
```
But failure\_handler\_auto, instead of dying or anything, compiles $key, caching it in
```
$lh->{'failure_lex'}{$key} = $compiled
```
and then calls the compiled value, and returns that. (I.e., if $key looks like bracket notation, $compiled is a sub, and we return &{$compiled}(@params); but if $key is just a plain string, we just return that.)
The effect of using "failure\_auto\_handler" is like an AUTO lexicon, except that it 1) compiles $key even if it starts with "\_", and 2) you have a record in the new hashref $lh->{'failure\_lex'} of all the keys that have failed for this object. This should avoid your program dying -- as long as your keys aren't actually invalid as bracket code, and as long as they don't try calling methods that don't exist.
"failure\_auto\_handler" may not be exactly what you want, but I hope it at least shows you that maketext failure can be mitigated in any number of very flexible ways. If you can formalize exactly what you want, you should be able to express that as a failure handler. You can even make it default for every object of a given class, by setting it in that class's init:
```
sub init {
my $lh = $_[0]; # a newborn handle
$lh->SUPER::init();
$lh->fail_with('my_clever_failure_handler');
return;
}
sub my_clever_failure_handler {
...you clever things here...
}
```
HOW TO USE MAKETEXT
--------------------
Here is a brief checklist on how to use Maketext to localize applications:
* Decide what system you'll use for lexicon keys. If you insist, you can use opaque IDs (if you're nostalgic for `catgets`), but I have better suggestions in the section "Entries in Each Lexicon", above. Assuming you opt for meaningful keys that double as values (like "Minimum ([\_1]) is larger than maximum ([\_2])!\n"), you'll have to settle on what language those should be in. For the sake of argument, I'll call this English, specifically American English, "en-US".
* Create a class for your localization project. This is the name of the class that you'll use in the idiom:
```
use Projname::L10N;
my $lh = Projname::L10N->get_handle(...) || die "Language?";
```
Assuming you call your class Projname::L10N, create a class consisting minimally of:
```
package Projname::L10N;
use base qw(Locale::Maketext);
...any methods you might want all your languages to share...
# And, assuming you want the base class to be an _AUTO lexicon,
# as is discussed a few sections up:
1;
```
* Create a class for the language your internal keys are in. Name the class after the language-tag for that language, in lowercase, with dashes changed to underscores. Assuming your project's first language is US English, you should call this Projname::L10N::en\_us. It should consist minimally of:
```
package Projname::L10N::en_us;
use base qw(Projname::L10N);
%Lexicon = (
'_AUTO' => 1,
);
1;
```
(For the rest of this section, I'll assume that this "first language class" of Projname::L10N::en\_us has \_AUTO lexicon.)
* Go and write your program. Everywhere in your program where you would say:
```
print "Foobar $thing stuff\n";
```
instead do it thru maketext, using no variable interpolation in the key:
```
print $lh->maketext("Foobar [_1] stuff\n", $thing);
```
If you get tired of constantly saying `print $lh->maketext`, consider making a functional wrapper for it, like so:
```
use Projname::L10N;
our $lh;
$lh = Projname::L10N->get_handle(...) || die "Language?";
sub pmt (@) { print( $lh->maketext(@_)) }
# "pmt" is short for "Print MakeText"
$Carp::Verbose = 1;
# so if maketext fails, we see made the call to pmt
```
Besides whole phrases meant for output, anything language-dependent should be put into the class Projname::L10N::en\_us, whether as methods, or as lexicon entries -- this is discussed in the section "Entries in Each Lexicon", above.
* Once the program is otherwise done, and once its localization for the first language works right (via the data and methods in Projname::L10N::en\_us), you can get together the data for translation. If your first language lexicon isn't an \_AUTO lexicon, then you already have all the messages explicitly in the lexicon (or else you'd be getting exceptions thrown when you call $lh->maketext to get messages that aren't in there). But if you were (advisedly) lazy and are using an \_AUTO lexicon, then you've got to make a list of all the phrases that you've so far been letting \_AUTO generate for you. There are very many ways to assemble such a list. The most straightforward is to simply grep the source for every occurrence of "maketext" (or calls to wrappers around it, like the above `pmt` function), and to log the following phrase.
* You may at this point want to consider whether your base class (Projname::L10N), from which all lexicons inherit from (Projname::L10N::en, Projname::L10N::es, etc.), should be an \_AUTO lexicon. It may be true that in theory, all needed messages will be in each language class; but in the presumably unlikely or "impossible" case of lookup failure, you should consider whether your program should throw an exception, emit text in English (or whatever your project's first language is), or some more complex solution as described in the section "Controlling Lookup Failure", above.
* Submit all messages/phrases/etc. to translators.
(You may, in fact, want to start with localizing to *one* other language at first, if you're not sure that you've properly abstracted the language-dependent parts of your code.)
Translators may request clarification of the situation in which a particular phrase is found. For example, in English we are entirely happy saying "*n* files found", regardless of whether we mean "I looked for files, and found *n* of them" or the rather distinct situation of "I looked for something else (like lines in files), and along the way I saw *n* files." This may involve rethinking things that you thought quite clear: should "Edit" on a toolbar be a noun ("editing") or a verb ("to edit")? Is there already a conventionalized way to express that menu option, separate from the target language's normal word for "to edit"?
In all cases where the very common phenomenon of quantification (saying "*N* files", for **any** value of N) is involved, each translator should make clear what dependencies the number causes in the sentence. In many cases, dependency is limited to words adjacent to the number, in places where you might expect them ("I found the-?PLURAL *N* empty-?PLURAL directory-?PLURAL"), but in some cases there are unexpected dependencies ("I found-?PLURAL ..."!) as well as long-distance dependencies "The *N* directory-?PLURAL could not be deleted-?PLURAL"!).
Remind the translators to consider the case where N is 0: "0 files found" isn't exactly natural-sounding in any language, but it may be unacceptable in many -- or it may condition special kinds of agreement (similar to English "I didN'T find ANY files").
Remember to ask your translators about numeral formatting in their language, so that you can override the `numf` method as appropriate. Typical variables in number formatting are: what to use as a decimal point (comma? period?); what to use as a thousands separator (space? nonbreaking space? comma? period? small middot? prime? apostrophe?); and even whether the so-called "thousands separator" is actually for every third digit -- I've heard reports of two hundred thousand being expressible as "2,00,000" for some Indian (Subcontinental) languages, besides the less surprising "200 000", "200.000", "200,000", and "200'000". Also, using a set of numeral glyphs other than the usual ASCII "0"-"9" might be appreciated, as via `tr/0-9/\x{0966}-\x{096F}/` for getting digits in Devanagari script (for Hindi, Konkani, others).
The basic `quant` method that Locale::Maketext provides should be good for many languages. For some languages, it might be useful to modify it (or its constituent `numerate` method) to take a plural form in the two-argument call to `quant` (as in "[quant,\_1,files]") if it's all-around easier to infer the singular form from the plural, than to infer the plural form from the singular.
But for other languages (as is discussed at length in <Locale::Maketext::TPJ13>), simple `quant`/`numf` is not enough. For the particularly problematic Slavic languages, what you may need is a method which you provide with the number, the citation form of the noun to quantify, and the case and gender that the sentence's syntax projects onto that noun slot. The method would then be responsible for determining what grammatical number that numeral projects onto its noun phrase, and what case and gender it may override the normal case and gender with; and then it would look up the noun in a lexicon providing all needed inflected forms.
* You may also wish to discuss with the translators the question of how to relate different subforms of the same language tag, considering how this reacts with `get_handle`'s treatment of these. For example, if a user accepts interfaces in "en, fr", and you have interfaces available in "en-US" and "fr", what should they get? You may wish to resolve this by establishing that "en" and "en-US" are effectively synonymous, by having one class zero-derive from the other.
For some languages this issue may never come up (Danish is rarely expressed as "da-DK", but instead is just "da"). And for other languages, the whole concept of a "generic" form may verge on being uselessly vague, particularly for interfaces involving voice media in forms of Arabic or Chinese.
* Once you've localized your program/site/etc. for all desired languages, be sure to show the result (whether live, or via screenshots) to the translators. Once they approve, make every effort to have it then checked by at least one other speaker of that language. This holds true even when (or especially when) the translation is done by one of your own programmers. Some kinds of systems may be harder to find testers for than others, depending on the amount of domain-specific jargon and concepts involved -- it's easier to find people who can tell you whether they approve of your translation for "delete this message" in an email-via-Web interface, than to find people who can give you an informed opinion on your translation for "attribute value" in an XML query tool's interface.
SEE ALSO
---------
I recommend reading all of these:
<Locale::Maketext::TPJ13> -- my *The Perl Journal* article about Maketext. It explains many important concepts underlying Locale::Maketext's design, and some insight into why Maketext is better than the plain old approach of having message catalogs that are just databases of sprintf formats.
<File::Findgrep> is a sample application/module that uses Locale::Maketext to localize its messages. For a larger internationalized system, see also <Apache::MP3>.
<I18N::LangTags>.
<Win32::Locale>.
RFC 3066, *Tags for the Identification of Languages*, as at <http://sunsite.dk/RFC/rfc/rfc3066.html>
RFC 2277, *IETF Policy on Character Sets and Languages* is at <http://sunsite.dk/RFC/rfc/rfc2277.html> -- much of it is just things of interest to protocol designers, but it explains some basic concepts, like the distinction between locales and language-tags.
The manual for GNU `gettext`. The gettext dist is available in `<ftp://prep.ai.mit.edu/pub/gnu/>` -- get a recent gettext tarball and look in its "doc/" directory, there's an easily browsable HTML version in there. The gettext documentation asks lots of questions worth thinking about, even if some of their answers are sometimes wonky, particularly where they start talking about pluralization.
The Locale/Maketext.pm source. Observe that the module is much shorter than its documentation!
COPYRIGHT AND DISCLAIMER
-------------------------
Copyright (c) 1999-2004 Sean M. Burke. All rights reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Sean M. Burke `[email protected]`
| programming_docs |
perl perlthrtut perlthrtut
==========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [What Is A Thread Anyway?](#What-Is-A-Thread-Anyway?)
* [Threaded Program Models](#Threaded-Program-Models)
+ [Boss/Worker](#Boss/Worker)
+ [Work Crew](#Work-Crew)
+ [Pipeline](#Pipeline)
* [What kind of threads are Perl threads?](#What-kind-of-threads-are-Perl-threads?)
* [Thread-Safe Modules](#Thread-Safe-Modules)
* [Thread Basics](#Thread-Basics)
+ [Basic Thread Support](#Basic-Thread-Support)
+ [A Note about the Examples](#A-Note-about-the-Examples)
+ [Creating Threads](#Creating-Threads)
+ [Waiting For A Thread To Exit](#Waiting-For-A-Thread-To-Exit)
+ [Ignoring A Thread](#Ignoring-A-Thread)
+ [Process and Thread Termination](#Process-and-Thread-Termination)
* [Threads And Data](#Threads-And-Data)
+ [Shared And Unshared Data](#Shared-And-Unshared-Data)
+ [Thread Pitfalls: Races](#Thread-Pitfalls:-Races)
* [Synchronization and control](#Synchronization-and-control)
+ [Controlling access: lock()](#Controlling-access:-lock())
+ [A Thread Pitfall: Deadlocks](#A-Thread-Pitfall:-Deadlocks)
+ [Queues: Passing Data Around](#Queues:-Passing-Data-Around)
+ [Semaphores: Synchronizing Data Access](#Semaphores:-Synchronizing-Data-Access)
+ [Basic semaphores](#Basic-semaphores)
+ [Advanced Semaphores](#Advanced-Semaphores)
+ [Waiting for a Condition](#Waiting-for-a-Condition)
+ [Giving up control](#Giving-up-control)
* [General Thread Utility Routines](#General-Thread-Utility-Routines)
+ [What Thread Am I In?](#What-Thread-Am-I-In?)
+ [Thread IDs](#Thread-IDs)
+ [Are These Threads The Same?](#Are-These-Threads-The-Same?)
+ [What Threads Are Running?](#What-Threads-Are-Running?)
* [A Complete Example](#A-Complete-Example)
* [Different implementations of threads](#Different-implementations-of-threads)
* [Performance considerations](#Performance-considerations)
* [Process-scope Changes](#Process-scope-Changes)
* [Thread-Safety of System Libraries](#Thread-Safety-of-System-Libraries)
* [Conclusion](#Conclusion)
* [SEE ALSO](#SEE-ALSO)
* [Bibliography](#Bibliography)
+ [Introductory Texts](#Introductory-Texts)
+ [OS-Related References](#OS-Related-References)
+ [Other References](#Other-References)
* [Acknowledgements](#Acknowledgements)
* [AUTHOR](#AUTHOR)
* [Copyrights](#Copyrights)
NAME
----
perlthrtut - Tutorial on threads in Perl
DESCRIPTION
-----------
This tutorial describes the use of Perl interpreter threads (sometimes referred to as *ithreads*). In this model, each thread runs in its own Perl interpreter, and any data sharing between threads must be explicit. The user-level interface for *ithreads* uses the <threads> class.
**NOTE**: There was another older Perl threading flavor called the 5.005 model that used the <threads> class. This old model was known to have problems, is deprecated, and was removed for release 5.10. You are strongly encouraged to migrate any existing 5.005 threads code to the new model as soon as possible.
You can see which (or neither) threading flavour you have by running `perl -V` and looking at the `Platform` section. If you have `useithreads=define` you have ithreads, if you have `use5005threads=define` you have 5.005 threads. If you have neither, you don't have any thread support built in. If you have both, you are in trouble.
The <threads> and <threads::shared> modules are included in the core Perl distribution. Additionally, they are maintained as a separate modules on CPAN, so you can check there for any updates.
What Is A Thread Anyway?
-------------------------
A thread is a flow of control through a program with a single execution point.
Sounds an awful lot like a process, doesn't it? Well, it should. Threads are one of the pieces of a process. Every process has at least one thread and, up until now, every process running Perl had only one thread. With 5.8, though, you can create extra threads. We're going to show you how, when, and why.
Threaded Program Models
------------------------
There are three basic ways that you can structure a threaded program. Which model you choose depends on what you need your program to do. For many non-trivial threaded programs, you'll need to choose different models for different pieces of your program.
###
Boss/Worker
The boss/worker model usually has one *boss* thread and one or more *worker* threads. The boss thread gathers or generates tasks that need to be done, then parcels those tasks out to the appropriate worker thread.
This model is common in GUI and server programs, where a main thread waits for some event and then passes that event to the appropriate worker threads for processing. Once the event has been passed on, the boss thread goes back to waiting for another event.
The boss thread does relatively little work. While tasks aren't necessarily performed faster than with any other method, it tends to have the best user-response times.
###
Work Crew
In the work crew model, several threads are created that do essentially the same thing to different pieces of data. It closely mirrors classical parallel processing and vector processors, where a large array of processors do the exact same thing to many pieces of data.
This model is particularly useful if the system running the program will distribute multiple threads across different processors. It can also be useful in ray tracing or rendering engines, where the individual threads can pass on interim results to give the user visual feedback.
### Pipeline
The pipeline model divides up a task into a series of steps, and passes the results of one step on to the thread processing the next. Each thread does one thing to each piece of data and passes the results to the next thread in line.
This model makes the most sense if you have multiple processors so two or more threads will be executing in parallel, though it can often make sense in other contexts as well. It tends to keep the individual tasks small and simple, as well as allowing some parts of the pipeline to block (on I/O or system calls, for example) while other parts keep going. If you're running different parts of the pipeline on different processors you may also take advantage of the caches on each processor.
This model is also handy for a form of recursive programming where, rather than having a subroutine call itself, it instead creates another thread. Prime and Fibonacci generators both map well to this form of the pipeline model. (A version of a prime number generator is presented later on.)
What kind of threads are Perl threads?
---------------------------------------
If you have experience with other thread implementations, you might find that things aren't quite what you expect. It's very important to remember when dealing with Perl threads that *Perl Threads Are Not X Threads* for all values of X. They aren't POSIX threads, or DecThreads, or Java's Green threads, or Win32 threads. There are similarities, and the broad concepts are the same, but if you start looking for implementation details you're going to be either disappointed or confused. Possibly both.
This is not to say that Perl threads are completely different from everything that's ever come before. They're not. Perl's threading model owes a lot to other thread models, especially POSIX. Just as Perl is not C, though, Perl threads are not POSIX threads. So if you find yourself looking for mutexes, or thread priorities, it's time to step back a bit and think about what you want to do and how Perl can do it.
However, it is important to remember that Perl threads cannot magically do things unless your operating system's threads allow it. So if your system blocks the entire process on `sleep()`, Perl usually will, as well.
**Perl Threads Are Different.**
Thread-Safe Modules
--------------------
The addition of threads has changed Perl's internals substantially. There are implications for people who write modules with XS code or external libraries. However, since Perl data is not shared among threads by default, Perl modules stand a high chance of being thread-safe or can be made thread-safe easily. Modules that are not tagged as thread-safe should be tested or code reviewed before being used in production code.
Not all modules that you might use are thread-safe, and you should always assume a module is unsafe unless the documentation says otherwise. This includes modules that are distributed as part of the core. Threads are a relatively new feature, and even some of the standard modules aren't thread-safe.
Even if a module is thread-safe, it doesn't mean that the module is optimized to work well with threads. A module could possibly be rewritten to utilize the new features in threaded Perl to increase performance in a threaded environment.
If you're using a module that's not thread-safe for some reason, you can protect yourself by using it from one, and only one thread at all. If you need multiple threads to access such a module, you can use semaphores and lots of programming discipline to control access to it. Semaphores are covered in ["Basic semaphores"](#Basic-semaphores).
See also ["Thread-Safety of System Libraries"](#Thread-Safety-of-System-Libraries).
Thread Basics
--------------
The <threads> module provides the basic functions you need to write threaded programs. In the following sections, we'll cover the basics, showing you what you need to do to create a threaded program. After that, we'll go over some of the features of the <threads> module that make threaded programming easier.
###
Basic Thread Support
Thread support is a Perl compile-time option. It's something that's turned on or off when Perl is built at your site, rather than when your programs are compiled. If your Perl wasn't compiled with thread support enabled, then any attempt to use threads will fail.
Your programs can use the Config module to check whether threads are enabled. If your program can't run without them, you can say something like:
```
use Config;
$Config{useithreads} or
die('Recompile Perl with threads to run this program.');
```
A possibly-threaded program using a possibly-threaded module might have code like this:
```
use Config;
use MyMod;
BEGIN {
if ($Config{useithreads}) {
# We have threads
require MyMod_threaded;
import MyMod_threaded;
} else {
require MyMod_unthreaded;
import MyMod_unthreaded;
}
}
```
Since code that runs both with and without threads is usually pretty messy, it's best to isolate the thread-specific code in its own module. In our example above, that's what `MyMod_threaded` is, and it's only imported if we're running on a threaded Perl.
###
A Note about the Examples
In a real situation, care should be taken that all threads are finished executing before the program exits. That care has **not** been taken in these examples in the interest of simplicity. Running these examples *as is* will produce error messages, usually caused by the fact that there are still threads running when the program exits. You should not be alarmed by this.
###
Creating Threads
The <threads> module provides the tools you need to create new threads. Like any other module, you need to tell Perl that you want to use it; `use threads;` imports all the pieces you need to create basic threads.
The simplest, most straightforward way to create a thread is with `create()`:
```
use threads;
my $thr = threads->create(\&sub1);
sub sub1 {
print("In the thread\n");
}
```
The `create()` method takes a reference to a subroutine and creates a new thread that starts executing in the referenced subroutine. Control then passes both to the subroutine and the caller.
If you need to, your program can pass parameters to the subroutine as part of the thread startup. Just include the list of parameters as part of the `threads->create()` call, like this:
```
use threads;
my $Param3 = 'foo';
my $thr1 = threads->create(\&sub1, 'Param 1', 'Param 2', $Param3);
my @ParamList = (42, 'Hello', 3.14);
my $thr2 = threads->create(\&sub1, @ParamList);
my $thr3 = threads->create(\&sub1, qw(Param1 Param2 Param3));
sub sub1 {
my @InboundParameters = @_;
print("In the thread\n");
print('Got parameters >', join('<>',@InboundParameters), "<\n");
}
```
The last example illustrates another feature of threads. You can spawn off several threads using the same subroutine. Each thread executes the same subroutine, but in a separate thread with a separate environment and potentially separate arguments.
`new()` is a synonym for `create()`.
###
Waiting For A Thread To Exit
Since threads are also subroutines, they can return values. To wait for a thread to exit and extract any values it might return, you can use the `join()` method:
```
use threads;
my ($thr) = threads->create(\&sub1);
my @ReturnData = $thr->join();
print('Thread returned ', join(', ', @ReturnData), "\n");
sub sub1 { return ('Fifty-six', 'foo', 2); }
```
In the example above, the `join()` method returns as soon as the thread ends. In addition to waiting for a thread to finish and gathering up any values that the thread might have returned, `join()` also performs any OS cleanup necessary for the thread. That cleanup might be important, especially for long-running programs that spawn lots of threads. If you don't want the return values and don't want to wait for the thread to finish, you should call the `detach()` method instead, as described next.
NOTE: In the example above, the thread returns a list, thus necessitating that the thread creation call be made in list context (i.e., `my ($thr)`). See ["$thr->join()" in threads](threads#%24thr-%3Ejoin%28%29) and ["THREAD CONTEXT" in threads](threads#THREAD-CONTEXT) for more details on thread context and return values.
###
Ignoring A Thread
`join()` does three things: it waits for a thread to exit, cleans up after it, and returns any data the thread may have produced. But what if you're not interested in the thread's return values, and you don't really care when the thread finishes? All you want is for the thread to get cleaned up after when it's done.
In this case, you use the `detach()` method. Once a thread is detached, it'll run until it's finished; then Perl will clean up after it automatically.
```
use threads;
my $thr = threads->create(\&sub1); # Spawn the thread
$thr->detach(); # Now we officially don't care any more
sleep(15); # Let thread run for awhile
sub sub1 {
my $count = 0;
while (1) {
$count++;
print("\$count is $count\n");
sleep(1);
}
}
```
Once a thread is detached, it may not be joined, and any return data that it might have produced (if it was done and waiting for a join) is lost.
`detach()` can also be called as a class method to allow a thread to detach itself:
```
use threads;
my $thr = threads->create(\&sub1);
sub sub1 {
threads->detach();
# Do more work
}
```
###
Process and Thread Termination
With threads one must be careful to make sure they all have a chance to run to completion, assuming that is what you want.
An action that terminates a process will terminate *all* running threads. die() and exit() have this property, and perl does an exit when the main thread exits, perhaps implicitly by falling off the end of your code, even if that's not what you want.
As an example of this case, this code prints the message "Perl exited with active threads: 2 running and unjoined":
```
use threads;
my $thr1 = threads->new(\&thrsub, "test1");
my $thr2 = threads->new(\&thrsub, "test2");
sub thrsub {
my ($message) = @_;
sleep 1;
print "thread $message\n";
}
```
But when the following lines are added at the end:
```
$thr1->join();
$thr2->join();
```
it prints two lines of output, a perhaps more useful outcome.
Threads And Data
-----------------
Now that we've covered the basics of threads, it's time for our next topic: Data. Threading introduces a couple of complications to data access that non-threaded programs never need to worry about.
###
Shared And Unshared Data
The biggest difference between Perl *ithreads* and the old 5.005 style threading, or for that matter, to most other threading systems out there, is that by default, no data is shared. When a new Perl thread is created, all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread! This is similar in feel to what happens when a Unix process forks, except that in this case, the data is just copied to a different part of memory within the same process rather than a real fork taking place.
To make use of threading, however, one usually wants the threads to share at least some data between themselves. This is done with the <threads::shared> module and the `:shared` attribute:
```
use threads;
use threads::shared;
my $foo :shared = 1;
my $bar = 1;
threads->create(sub { $foo++; $bar++; })->join();
print("$foo\n"); # Prints 2 since $foo is shared
print("$bar\n"); # Prints 1 since $bar is not shared
```
In the case of a shared array, all the array's elements are shared, and for a shared hash, all the keys and values are shared. This places restrictions on what may be assigned to shared array and hash elements: only simple values or references to shared variables are allowed - this is so that a private variable can't accidentally become shared. A bad assignment will cause the thread to die. For example:
```
use threads;
use threads::shared;
my $var = 1;
my $svar :shared = 2;
my %hash :shared;
... create some threads ...
$hash{a} = 1; # All threads see exists($hash{a})
# and $hash{a} == 1
$hash{a} = $var; # okay - copy-by-value: same effect as previous
$hash{a} = $svar; # okay - copy-by-value: same effect as previous
$hash{a} = \$svar; # okay - a reference to a shared variable
$hash{a} = \$var; # This will die
delete($hash{a}); # okay - all threads will see !exists($hash{a})
```
Note that a shared variable guarantees that if two or more threads try to modify it at the same time, the internal state of the variable will not become corrupted. However, there are no guarantees beyond this, as explained in the next section.
###
Thread Pitfalls: Races
While threads bring a new set of useful tools, they also bring a number of pitfalls. One pitfall is the race condition:
```
use threads;
use threads::shared;
my $x :shared = 1;
my $thr1 = threads->create(\&sub1);
my $thr2 = threads->create(\&sub2);
$thr1->join();
$thr2->join();
print("$x\n");
sub sub1 { my $foo = $x; $x = $foo + 1; }
sub sub2 { my $bar = $x; $x = $bar + 1; }
```
What do you think `$x` will be? The answer, unfortunately, is *it depends*. Both `sub1()` and `sub2()` access the global variable `$x`, once to read and once to write. Depending on factors ranging from your thread implementation's scheduling algorithm to the phase of the moon, `$x` can be 2 or 3.
Race conditions are caused by unsynchronized access to shared data. Without explicit synchronization, there's no way to be sure that nothing has happened to the shared data between the time you access it and the time you update it. Even this simple code fragment has the possibility of error:
```
use threads;
my $x :shared = 2;
my $y :shared;
my $z :shared;
my $thr1 = threads->create(sub { $y = $x; $x = $y + 1; });
my $thr2 = threads->create(sub { $z = $x; $x = $z + 1; });
$thr1->join();
$thr2->join();
```
Two threads both access `$x`. Each thread can potentially be interrupted at any point, or be executed in any order. At the end, `$x` could be 3 or 4, and both `$y` and `$z` could be 2 or 3.
Even `$x += 5` or `$x++` are not guaranteed to be atomic.
Whenever your program accesses data or resources that can be accessed by other threads, you must take steps to coordinate access or risk data inconsistency and race conditions. Note that Perl will protect its internals from your race conditions, but it won't protect you from you.
Synchronization and control
----------------------------
Perl provides a number of mechanisms to coordinate the interactions between themselves and their data, to avoid race conditions and the like. Some of these are designed to resemble the common techniques used in thread libraries such as `pthreads`; others are Perl-specific. Often, the standard techniques are clumsy and difficult to get right (such as condition waits). Where possible, it is usually easier to use Perlish techniques such as queues, which remove some of the hard work involved.
###
Controlling access: lock()
The `lock()` function takes a shared variable and puts a lock on it. No other thread may lock the variable until the variable is unlocked by the thread holding the lock. Unlocking happens automatically when the locking thread exits the block that contains the call to the `lock()` function. Using `lock()` is straightforward: This example has several threads doing some calculations in parallel, and occasionally updating a running total:
```
use threads;
use threads::shared;
my $total :shared = 0;
sub calc {
while (1) {
my $result;
# (... do some calculations and set $result ...)
{
lock($total); # Block until we obtain the lock
$total += $result;
} # Lock implicitly released at end of scope
last if $result == 0;
}
}
my $thr1 = threads->create(\&calc);
my $thr2 = threads->create(\&calc);
my $thr3 = threads->create(\&calc);
$thr1->join();
$thr2->join();
$thr3->join();
print("total=$total\n");
```
`lock()` blocks the thread until the variable being locked is available. When `lock()` returns, your thread can be sure that no other thread can lock that variable until the block containing the lock exits.
It's important to note that locks don't prevent access to the variable in question, only lock attempts. This is in keeping with Perl's longstanding tradition of courteous programming, and the advisory file locking that `flock()` gives you.
You may lock arrays and hashes as well as scalars. Locking an array, though, will not block subsequent locks on array elements, just lock attempts on the array itself.
Locks are recursive, which means it's okay for a thread to lock a variable more than once. The lock will last until the outermost `lock()` on the variable goes out of scope. For example:
```
my $x :shared;
doit();
sub doit {
{
{
lock($x); # Wait for lock
lock($x); # NOOP - we already have the lock
{
lock($x); # NOOP
{
lock($x); # NOOP
lockit_some_more();
}
}
} # *** Implicit unlock here ***
}
}
sub lockit_some_more {
lock($x); # NOOP
} # Nothing happens here
```
Note that there is no `unlock()` function - the only way to unlock a variable is to allow it to go out of scope.
A lock can either be used to guard the data contained within the variable being locked, or it can be used to guard something else, like a section of code. In this latter case, the variable in question does not hold any useful data, and exists only for the purpose of being locked. In this respect, the variable behaves like the mutexes and basic semaphores of traditional thread libraries.
###
A Thread Pitfall: Deadlocks
Locks are a handy tool to synchronize access to data, and using them properly is the key to safe shared data. Unfortunately, locks aren't without their dangers, especially when multiple locks are involved. Consider the following code:
```
use threads;
my $x :shared = 4;
my $y :shared = 'foo';
my $thr1 = threads->create(sub {
lock($x);
sleep(20);
lock($y);
});
my $thr2 = threads->create(sub {
lock($y);
sleep(20);
lock($x);
});
```
This program will probably hang until you kill it. The only way it won't hang is if one of the two threads acquires both locks first. A guaranteed-to-hang version is more complicated, but the principle is the same.
The first thread will grab a lock on `$x`, then, after a pause during which the second thread has probably had time to do some work, try to grab a lock on `$y`. Meanwhile, the second thread grabs a lock on `$y`, then later tries to grab a lock on `$x`. The second lock attempt for both threads will block, each waiting for the other to release its lock.
This condition is called a deadlock, and it occurs whenever two or more threads are trying to get locks on resources that the others own. Each thread will block, waiting for the other to release a lock on a resource. That never happens, though, since the thread with the resource is itself waiting for a lock to be released.
There are a number of ways to handle this sort of problem. The best way is to always have all threads acquire locks in the exact same order. If, for example, you lock variables `$x`, `$y`, and `$z`, always lock `$x` before `$y`, and `$y` before `$z`. It's also best to hold on to locks for as short a period of time to minimize the risks of deadlock.
The other synchronization primitives described below can suffer from similar problems.
###
Queues: Passing Data Around
A queue is a special thread-safe object that lets you put data in one end and take it out the other without having to worry about synchronization issues. They're pretty straightforward, and look like this:
```
use threads;
use Thread::Queue;
my $DataQueue = Thread::Queue->new();
my $thr = threads->create(sub {
while (my $DataElement = $DataQueue->dequeue()) {
print("Popped $DataElement off the queue\n");
}
});
$DataQueue->enqueue(12);
$DataQueue->enqueue("A", "B", "C");
sleep(10);
$DataQueue->enqueue(undef);
$thr->join();
```
You create the queue with `Thread::Queue->new()`. Then you can add lists of scalars onto the end with `enqueue()`, and pop scalars off the front of it with `dequeue()`. A queue has no fixed size, and can grow as needed to hold everything pushed on to it.
If a queue is empty, `dequeue()` blocks until another thread enqueues something. This makes queues ideal for event loops and other communications between threads.
###
Semaphores: Synchronizing Data Access
Semaphores are a kind of generic locking mechanism. In their most basic form, they behave very much like lockable scalars, except that they can't hold data, and that they must be explicitly unlocked. In their advanced form, they act like a kind of counter, and can allow multiple threads to have the *lock* at any one time.
###
Basic semaphores
Semaphores have two methods, `down()` and `up()`: `down()` decrements the resource count, while `up()` increments it. Calls to `down()` will block if the semaphore's current count would decrement below zero. This program gives a quick demonstration:
```
use threads;
use Thread::Semaphore;
my $semaphore = Thread::Semaphore->new();
my $GlobalVariable :shared = 0;
$thr1 = threads->create(\&sample_sub, 1);
$thr2 = threads->create(\&sample_sub, 2);
$thr3 = threads->create(\&sample_sub, 3);
sub sample_sub {
my $SubNumber = shift(@_);
my $TryCount = 10;
my $LocalCopy;
sleep(1);
while ($TryCount--) {
$semaphore->down();
$LocalCopy = $GlobalVariable;
print("$TryCount tries left for sub $SubNumber "
."(\$GlobalVariable is $GlobalVariable)\n");
sleep(2);
$LocalCopy++;
$GlobalVariable = $LocalCopy;
$semaphore->up();
}
}
$thr1->join();
$thr2->join();
$thr3->join();
```
The three invocations of the subroutine all operate in sync. The semaphore, though, makes sure that only one thread is accessing the global variable at once.
###
Advanced Semaphores
By default, semaphores behave like locks, letting only one thread `down()` them at a time. However, there are other uses for semaphores.
Each semaphore has a counter attached to it. By default, semaphores are created with the counter set to one, `down()` decrements the counter by one, and `up()` increments by one. However, we can override any or all of these defaults simply by passing in different values:
```
use threads;
use Thread::Semaphore;
my $semaphore = Thread::Semaphore->new(5);
# Creates a semaphore with the counter set to five
my $thr1 = threads->create(\&sub1);
my $thr2 = threads->create(\&sub1);
sub sub1 {
$semaphore->down(5); # Decrements the counter by five
# Do stuff here
$semaphore->up(5); # Increment the counter by five
}
$thr1->detach();
$thr2->detach();
```
If `down()` attempts to decrement the counter below zero, it blocks until the counter is large enough. Note that while a semaphore can be created with a starting count of zero, any `up()` or `down()` always changes the counter by at least one, and so `$semaphore->down(0)` is the same as `$semaphore->down(1)`.
The question, of course, is why would you do something like this? Why create a semaphore with a starting count that's not one, or why decrement or increment it by more than one? The answer is resource availability. Many resources that you want to manage access for can be safely used by more than one thread at once.
For example, let's take a GUI driven program. It has a semaphore that it uses to synchronize access to the display, so only one thread is ever drawing at once. Handy, but of course you don't want any thread to start drawing until things are properly set up. In this case, you can create a semaphore with a counter set to zero, and up it when things are ready for drawing.
Semaphores with counters greater than one are also useful for establishing quotas. Say, for example, that you have a number of threads that can do I/O at once. You don't want all the threads reading or writing at once though, since that can potentially swamp your I/O channels, or deplete your process's quota of filehandles. You can use a semaphore initialized to the number of concurrent I/O requests (or open files) that you want at any one time, and have your threads quietly block and unblock themselves.
Larger increments or decrements are handy in those cases where a thread needs to check out or return a number of resources at once.
###
Waiting for a Condition
The functions `cond_wait()` and `cond_signal()` can be used in conjunction with locks to notify co-operating threads that a resource has become available. They are very similar in use to the functions found in `pthreads`. However for most purposes, queues are simpler to use and more intuitive. See <threads::shared> for more details.
###
Giving up control
There are times when you may find it useful to have a thread explicitly give up the CPU to another thread. You may be doing something processor-intensive and want to make sure that the user-interface thread gets called frequently. Regardless, there are times that you might want a thread to give up the processor.
Perl's threading package provides the `yield()` function that does this. `yield()` is pretty straightforward, and works like this:
```
use threads;
sub loop {
my $thread = shift;
my $foo = 50;
while($foo--) { print("In thread $thread\n"); }
threads->yield();
$foo = 50;
while($foo--) { print("In thread $thread\n"); }
}
my $thr1 = threads->create(\&loop, 'first');
my $thr2 = threads->create(\&loop, 'second');
my $thr3 = threads->create(\&loop, 'third');
```
It is important to remember that `yield()` is only a hint to give up the CPU, it depends on your hardware, OS and threading libraries what actually happens. **On many operating systems, yield() is a no-op.** Therefore it is important to note that one should not build the scheduling of the threads around `yield()` calls. It might work on your platform but it won't work on another platform.
General Thread Utility Routines
--------------------------------
We've covered the workhorse parts of Perl's threading package, and with these tools you should be well on your way to writing threaded code and packages. There are a few useful little pieces that didn't really fit in anyplace else.
###
What Thread Am I In?
The `threads->self()` class method provides your program with a way to get an object representing the thread it's currently in. You can use this object in the same way as the ones returned from thread creation.
###
Thread IDs
`tid()` is a thread object method that returns the thread ID of the thread the object represents. Thread IDs are integers, with the main thread in a program being 0. Currently Perl assigns a unique TID to every thread ever created in your program, assigning the first thread to be created a TID of 1, and increasing the TID by 1 for each new thread that's created. When used as a class method, `threads->tid()` can be used by a thread to get its own TID.
###
Are These Threads The Same?
The `equal()` method takes two thread objects and returns true if the objects represent the same thread, and false if they don't.
Thread objects also have an overloaded `==` comparison so that you can do comparison on them as you would with normal objects.
###
What Threads Are Running?
`threads->list()` returns a list of thread objects, one for each thread that's currently running and not detached. Handy for a number of things, including cleaning up at the end of your program (from the main Perl thread, of course):
```
# Loop through all the threads
foreach my $thr (threads->list()) {
$thr->join();
}
```
If some threads have not finished running when the main Perl thread ends, Perl will warn you about it and die, since it is impossible for Perl to clean up itself while other threads are running.
NOTE: The main Perl thread (thread 0) is in a *detached* state, and so does not appear in the list returned by `threads->list()`.
A Complete Example
-------------------
Confused yet? It's time for an example program to show some of the things we've covered. This program finds prime numbers using threads.
```
1 #!/usr/bin/perl
2 # prime-pthread, courtesy of Tom Christiansen
3
4 use v5.36;
5
6 use threads;
7 use Thread::Queue;
8
9 sub check_num ($upstream, $cur_prime) {
10 my $kid;
11 my $downstream = Thread::Queue->new();
12 while (my $num = $upstream->dequeue()) {
13 next unless ($num % $cur_prime);
14 if ($kid) {
15 $downstream->enqueue($num);
16 } else {
17 print("Found prime: $num\n");
18 $kid = threads->create(\&check_num, $downstream, $num);
19 if (! $kid) {
20 warn("Sorry. Ran out of threads.\n");
21 last;
22 }
23 }
24 }
25 if ($kid) {
26 $downstream->enqueue(undef);
27 $kid->join();
28 }
29 }
30
31 my $stream = Thread::Queue->new(3..1000, undef);
32 check_num($stream, 2);
```
This program uses the pipeline model to generate prime numbers. Each thread in the pipeline has an input queue that feeds numbers to be checked, a prime number that it's responsible for, and an output queue into which it funnels numbers that have failed the check. If the thread has a number that's failed its check and there's no child thread, then the thread must have found a new prime number. In that case, a new child thread is created for that prime and stuck on the end of the pipeline.
This probably sounds a bit more confusing than it really is, so let's go through this program piece by piece and see what it does. (For those of you who might be trying to remember exactly what a prime number is, it's a number that's only evenly divisible by itself and 1.)
The bulk of the work is done by the `check_num()` subroutine, which takes a reference to its input queue and a prime number that it's responsible for. We create a new queue (line 11) and reserve a scalar for the thread that we're likely to create later (line 10).
The while loop from line 12 to line 24 grabs a scalar off the input queue and checks against the prime this thread is responsible for. Line 13 checks to see if there's a remainder when we divide the number to be checked by our prime. If there is one, the number must not be evenly divisible by our prime, so we need to either pass it on to the next thread if we've created one (line 15) or create a new thread if we haven't.
The new thread creation is line 18. We pass on to it a reference to the queue we've created, and the prime number we've found. In lines 19 through 22, we check to make sure that our new thread got created, and if not, we stop checking any remaining numbers in the queue.
Finally, once the loop terminates (because we got a 0 or `undef` in the queue, which serves as a note to terminate), we pass on the notice to our child, and wait for it to exit if we've created a child (lines 25 and 28).
Meanwhile, back in the main thread, we first create a queue (line 31) and queue up all the numbers from 3 to 1000 for checking, plus a termination notice. Then all we have to do to get the ball rolling is pass the queue and the first prime to the `check_num()` subroutine (line 32).
That's how it works. It's pretty simple; as with many Perl programs, the explanation is much longer than the program.
Different implementations of threads
-------------------------------------
Some background on thread implementations from the operating system viewpoint. There are three basic categories of threads: user-mode threads, kernel threads, and multiprocessor kernel threads.
User-mode threads are threads that live entirely within a program and its libraries. In this model, the OS knows nothing about threads. As far as it's concerned, your process is just a process.
This is the easiest way to implement threads, and the way most OSes start. The big disadvantage is that, since the OS knows nothing about threads, if one thread blocks they all do. Typical blocking activities include most system calls, most I/O, and things like `sleep()`.
Kernel threads are the next step in thread evolution. The OS knows about kernel threads, and makes allowances for them. The main difference between a kernel thread and a user-mode thread is blocking. With kernel threads, things that block a single thread don't block other threads. This is not the case with user-mode threads, where the kernel blocks at the process level and not the thread level.
This is a big step forward, and can give a threaded program quite a performance boost over non-threaded programs. Threads that block performing I/O, for example, won't block threads that are doing other things. Each process still has only one thread running at once, though, regardless of how many CPUs a system might have.
Since kernel threading can interrupt a thread at any time, they will uncover some of the implicit locking assumptions you may make in your program. For example, something as simple as `$x = $x + 2` can behave unpredictably with kernel threads if `$x` is visible to other threads, as another thread may have changed `$x` between the time it was fetched on the right hand side and the time the new value is stored.
Multiprocessor kernel threads are the final step in thread support. With multiprocessor kernel threads on a machine with multiple CPUs, the OS may schedule two or more threads to run simultaneously on different CPUs.
This can give a serious performance boost to your threaded program, since more than one thread will be executing at the same time. As a tradeoff, though, any of those nagging synchronization issues that might not have shown with basic kernel threads will appear with a vengeance.
In addition to the different levels of OS involvement in threads, different OSes (and different thread implementations for a particular OS) allocate CPU cycles to threads in different ways.
Cooperative multitasking systems have running threads give up control if one of two things happen. If a thread calls a yield function, it gives up control. It also gives up control if the thread does something that would cause it to block, such as perform I/O. In a cooperative multitasking implementation, one thread can starve all the others for CPU time if it so chooses.
Preemptive multitasking systems interrupt threads at regular intervals while the system decides which thread should run next. In a preemptive multitasking system, one thread usually won't monopolize the CPU.
On some systems, there can be cooperative and preemptive threads running simultaneously. (Threads running with realtime priorities often behave cooperatively, for example, while threads running at normal priorities behave preemptively.)
Most modern operating systems support preemptive multitasking nowadays.
Performance considerations
---------------------------
The main thing to bear in mind when comparing Perl's *ithreads* to other threading models is the fact that for each new thread created, a complete copy of all the variables and data of the parent thread has to be taken. Thus, thread creation can be quite expensive, both in terms of memory usage and time spent in creation. The ideal way to reduce these costs is to have a relatively short number of long-lived threads, all created fairly early on (before the base thread has accumulated too much data). Of course, this may not always be possible, so compromises have to be made. However, after a thread has been created, its performance and extra memory usage should be little different than ordinary code.
Also note that under the current implementation, shared variables use a little more memory and are a little slower than ordinary variables.
Process-scope Changes
----------------------
Note that while threads themselves are separate execution threads and Perl data is thread-private unless explicitly shared, the threads can affect process-scope state, affecting all the threads.
The most common example of this is changing the current working directory using `chdir()`. One thread calls `chdir()`, and the working directory of all the threads changes.
Even more drastic example of a process-scope change is `chroot()`: the root directory of all the threads changes, and no thread can undo it (as opposed to `chdir()`).
Further examples of process-scope changes include `umask()` and changing uids and gids.
Thinking of mixing `fork()` and threads? Please lie down and wait until the feeling passes. Be aware that the semantics of `fork()` vary between platforms. For example, some Unix systems copy all the current threads into the child process, while others only copy the thread that called `fork()`. You have been warned!
Similarly, mixing signals and threads may be problematic. Implementations are platform-dependent, and even the POSIX semantics may not be what you expect (and Perl doesn't even give you the full POSIX API). For example, there is no way to guarantee that a signal sent to a multi-threaded Perl application will get intercepted by any particular thread. (However, a recently added feature does provide the capability to send signals between threads. See ["THREAD SIGNALLING" in threads](threads#THREAD-SIGNALLING) for more details.)
Thread-Safety of System Libraries
----------------------------------
Whether various library calls are thread-safe is outside the control of Perl. Calls often suffering from not being thread-safe include: `localtime()`, `gmtime()`, functions fetching user, group and network information (such as `getgrent()`, `gethostent()`, `getnetent()` and so on), `readdir()`, `rand()`, and `srand()`. In general, calls that depend on some global external state.
If the system Perl is compiled in has thread-safe variants of such calls, they will be used. Beyond that, Perl is at the mercy of the thread-safety or -unsafety of the calls. Please consult your C library call documentation.
On some platforms the thread-safe library interfaces may fail if the result buffer is too small (for example the user group databases may be rather large, and the reentrant interfaces may have to carry around a full snapshot of those databases). Perl will start with a small buffer, but keep retrying and growing the result buffer until the result fits. If this limitless growing sounds bad for security or memory consumption reasons you can recompile Perl with `PERL_REENTRANT_MAXSIZE` defined to the maximum number of bytes you will allow.
Conclusion
----------
A complete thread tutorial could fill a book (and has, many times), but with what we've covered in this introduction, you should be well on your way to becoming a threaded Perl expert.
SEE ALSO
---------
Annotated POD for <threads>: <https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads>
Latest version of <threads> on CPAN: <https://metacpan.org/pod/threads>
Annotated POD for <threads::shared>: <https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads%3A%3Ashared>
Latest version of <threads::shared> on CPAN: <https://metacpan.org/pod/threads::shared>
Perl threads mailing list: <https://lists.perl.org/list/ithreads.html>
Bibliography
------------
Here's a short bibliography courtesy of Jürgen Christoffel:
###
Introductory Texts
Birrell, Andrew D. An Introduction to Programming with Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report #35 online as <https://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-35.pdf> (highly recommended)
Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A Guide to Concurrency, Communication, and Multithreading. Prentice-Hall, 1996.
Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written introduction to threads).
Nelson, Greg (editor). Systems Programming with Modula-3. Prentice Hall, 1991, ISBN 0-13-590464-1.
Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell. Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1 (covers POSIX threads).
###
OS-Related References
Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN 0-201-52739-1.
Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall, 1995, ISBN 0-13-219908-4 (great textbook).
Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts, 4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
###
Other References
Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.
comp.programming.threads FAQ, <http://www.serpentine.com/~bos/threads-faq/>
Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage Collection on Virtually Shared Memory Architectures" in Memory Management: Proc. of the International Workshop IWMM 92, St. Malo, France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992, ISBN 3540-55940-X (real-life thread applications).
Artur Bergman, "Where Wizards Fear To Tread", June 11, 2002, <http://www.perl.com/pub/a/2002/06/11/threads.html>
Acknowledgements
----------------
Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua Pritikin, and Alan Burlison, for their help in reality-checking and polishing this article. Big thanks to Tom Christiansen for his rewrite of the prime number generator.
AUTHOR
------
Dan Sugalski <[email protected]>
Slightly modified by Arthur Bergman to fit the new thread model/module.
Reworked slightly by Jörg Walter <[email protected]> to be more concise about thread-safety of Perl code.
Rearranged slightly by Elizabeth Mattijsen <[email protected]> to put less emphasis on yield().
Copyrights
----------
The original version of this article originally appeared in The Perl Journal #10, and is copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal. This document may be distributed under the same terms as Perl itself.
| programming_docs |
perl DBM_Filter::null DBM\_Filter::null
=================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter::null - filter for DBM\_Filter
SYNOPSIS
--------
```
use SDBM_File; # or DB_File, GDBM_File, NDBM_File, or ODBM_File
use DBM_Filter ;
$db = tie %hash, ...
$db->Filter_Push('null');
```
DESCRIPTION
-----------
This filter ensures that all data written to the DBM file is null terminated. This is useful when you have a perl script that needs to interoperate with a DBM file that a C program also uses. A fairly common issue is for the C application to include the terminating null in a string when it writes to the DBM file. This filter will ensure that all data written to the DBM file can be read by the C application.
SEE ALSO
---------
[DBM\_Filter](dbm_filter), <perldbmfilter>
AUTHOR
------
Paul Marquess [email protected]
perl Test2::EventFacet Test2::EventFacet
=================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::EventFacet - Base class for all event facets.
DESCRIPTION
-----------
Base class for all event facets.
METHODS
-------
$key = $facet\_class->facet\_key() This will return the key for the facet in the facet data hash.
$bool = $facet\_class->is\_list() This will return true if the facet should be in a list instead of a single item.
$clone = $facet->clone()
$clone = $facet->clone(%replace) This will make a shallow clone of the facet. You may specify fields to override as arguments.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl perlintro perlintro
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [What is Perl?](#What-is-Perl?)
+ [Running Perl programs](#Running-Perl-programs)
+ [Safety net](#Safety-net)
+ [Basic syntax overview](#Basic-syntax-overview)
+ [Perl variable types](#Perl-variable-types)
+ [Variable scoping](#Variable-scoping)
+ [Conditional and looping constructs](#Conditional-and-looping-constructs)
+ [Builtin operators and functions](#Builtin-operators-and-functions)
+ [Files and I/O](#Files-and-I/O)
+ [Regular expressions](#Regular-expressions)
+ [Writing subroutines](#Writing-subroutines)
+ [OO Perl](#OO-Perl)
+ [Using Perl modules](#Using-Perl-modules)
* [AUTHOR](#AUTHOR)
NAME
----
perlintro - a brief introduction and overview of Perl
DESCRIPTION
-----------
This document is intended to give you a quick overview of the Perl programming language, along with pointers to further documentation. It is intended as a "bootstrap" guide for those who are new to the language, and provides just enough information for you to be able to read other peoples' Perl and understand roughly what it's doing, or write your own simple scripts.
This introductory document does not aim to be complete. It does not even aim to be entirely accurate. In some cases perfection has been sacrificed in the goal of getting the general idea across. You are *strongly* advised to follow this introduction with more information from the full Perl manual, the table of contents to which can be found in <perltoc>.
Throughout this document you'll see references to other parts of the Perl documentation. You can read that documentation using the `perldoc` command or whatever method you're using to read this document.
Throughout Perl's documentation, you'll find numerous examples intended to help explain the discussed features. Please keep in mind that many of them are code fragments rather than complete programs.
These examples often reflect the style and preference of the author of that piece of the documentation, and may be briefer than a corresponding line of code in a real program. Except where otherwise noted, you should assume that `use strict` and `use warnings` statements appear earlier in the "program", and that any variables used have already been declared, even if those declarations have been omitted to make the example easier to read.
Do note that the examples have been written by many different authors over a period of several decades. Styles and techniques will therefore differ, although some effort has been made to not vary styles too widely in the same sections. Do not consider one style to be better than others - "There's More Than One Way To Do It" is one of Perl's mottos. After all, in your journey as a programmer, you are likely to encounter different styles.
###
What is Perl?
Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.
The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world's most impressive collections of third-party modules.
Different definitions of Perl are given in <perl>, <perlfaq1> and no doubt other places. From this we can determine that Perl is different things to different people, but that lots of people think it's at least worth writing about.
###
Running Perl programs
To run a Perl program from the Unix command line:
```
perl progname.pl
```
Alternatively, put this as the first line of your script:
```
#!/usr/bin/env perl
```
... and run the script as */path/to/script.pl*. Of course, it'll need to be executable first, so `chmod 755 script.pl` (under Unix).
(This start line assumes you have the **env** program. You can also put directly the path to your perl executable, like in `#!/usr/bin/perl`).
For more information, including instructions for other platforms such as Windows, read <perlrun>.
###
Safety net
Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines:
```
#!/usr/bin/perl
use strict;
use warnings;
```
The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by `use strict;` will cause your code to stop immediately when it is encountered, while `use warnings;` will merely give a warning (like the command-line switch **-w**) and let your code run. To read more about them, check their respective manual pages at <strict> and <warnings>.
A `[use v5.35](perlfunc#use-VERSION)` (or higher) declaration will enable both `strict` and `warnings`:
```
#!/usr/bin/perl
use v5.35;
```
In addition to enabling the `strict` and `warnings` pragmata, this declaration will also activate a ["feature bundle"](feature#FEATURE-BUNDLES); a collection of named features that enable many of the more recent additions and changes to the language, as well as occasionally removing older features found to have been mistakes in design and discouraged.
###
Basic syntax overview
A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a `main()` function or anything of that kind.
Perl statements end in a semi-colon:
```
print "Hello, world";
```
Comments start with a hash symbol and run to the end of the line
```
# This is a comment
```
Whitespace is irrelevant:
```
print
"Hello, world"
;
```
... except inside quoted strings:
```
# this would print with a linebreak in the middle
print "Hello
world";
```
Double quotes or single quotes may be used around literal strings:
```
print "Hello, world";
print 'Hello, world';
```
However, only double quotes "interpolate" variables and special characters such as newlines (`\n`):
```
print "Hello, $name\n"; # works fine
print 'Hello, $name\n'; # prints $name\n literally
```
Numbers don't need quotes around them:
```
print 42;
```
You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence.
```
print("Hello, world\n");
print "Hello, world\n";
```
More detailed information about Perl syntax can be found in <perlsyn>.
###
Perl variable types
Perl has three main variable types: scalars, arrays, and hashes.
Scalars A scalar represents a single value:
```
my $animal = "camel";
my $answer = 42;
```
Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. You have to declare them using the `my` keyword the first time you use them. (This is one of the requirements of `use strict;`.)
Scalar values can be used in various ways:
```
print $animal;
print "The animal is $animal\n";
print "The square of $answer is ", $answer * $answer, "\n";
```
Perl defines a number of special scalars with short names, often single punctuation marks or digits. These variables are used for all kinds of purposes, and are documented in <perlvar>. The only one you need to know about for now is `$_` which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs.
```
print; # prints contents of $_ by default
```
Arrays An array represents a list of values:
```
my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed = ("camel", 42, 1.23);
```
Arrays are zero-indexed. Here's how you get at elements in an array:
```
print $animals[0]; # prints "camel"
print $animals[1]; # prints "llama"
```
The special variable `$#array` tells you the index of the last element of an array:
```
print $mixed[$#mixed]; # last element, prints 1.23
```
You might be tempted to use `$#array + 1` to tell you how many items there are in an array. Don't bother. As it happens, using `@array` where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array:
```
if (@animals < 5) { ... }
```
The elements we're getting from the array start with a `$` because we're getting just a single value out of the array; you ask for a scalar, you get a scalar.
To get multiple values from an array:
```
@animals[0,1]; # gives ("camel", "llama");
@animals[0..2]; # gives ("camel", "llama", "owl");
@animals[1..$#animals]; # gives all except the first element
```
This is called an "array slice".
You can do various useful things to lists:
```
my @sorted = sort @animals;
my @backwards = reverse @numbers;
```
There are a couple of special arrays too, such as `@ARGV` (the command line arguments to your script) and `@_` (the arguments passed to a subroutine). These are documented in <perlvar>.
Hashes A hash represents a set of key/value pairs:
```
my %fruit_color = ("apple", "red", "banana", "yellow");
```
You can use whitespace and the `=>` operator to lay them out more nicely:
```
my %fruit_color = (
apple => "red",
banana => "yellow",
);
```
To get at hash elements:
```
$fruit_color{"apple"}; # gives "red"
```
You can get at lists of keys and values with `keys()` and `values()`.
```
my @fruits = keys %fruit_color;
my @colors = values %fruit_color;
```
Hashes have no particular internal order, though you can sort the keys and loop through them.
Just like special scalars and arrays, there are also special hashes. The most well known of these is `%ENV` which contains environment variables. Read all about it (and other special variables) in <perlvar>.
Scalars, arrays and hashes are documented more fully in <perldata>.
More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes.
A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references.
```
my $variables = {
scalar => {
description => "single item",
sigil => '$',
},
array => {
description => "ordered list of items",
sigil => '@',
},
hash => {
description => "key/value pairs",
sigil => '%',
},
};
print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
```
Exhaustive information on the topic of references can be found in <perlreftut>, <perllol>, <perlref> and <perldsc>.
###
Variable scoping
Throughout the previous section all the examples have used the syntax:
```
my $var = "value";
```
The `my` is actually not required; you could just use:
```
$var = "value";
```
However, the above usage will create global variables throughout your program, which is bad programming practice. `my` creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined.
```
my $x = "foo";
my $some_condition = 1;
if ($some_condition) {
my $y = "bar";
print $x; # prints "foo"
print $y; # prints "bar"
}
print $x; # prints "foo"
print $y; # prints nothing; $y has fallen out of scope
```
Using `my` in combination with a `use strict;` at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final `print $y` would cause a compile-time error and prevent you from running the program. Using `strict` is highly recommended.
###
Conditional and looping constructs
Perl has most of the usual conditional and looping constructs.
The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements.
if
```
if ( condition ) {
...
} elsif ( other condition ) {
...
} else {
...
}
```
There's also a negated version of it:
```
unless ( condition ) {
...
}
```
This is provided as a more readable version of `if (!*condition*)`.
Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:
```
# the traditional way
if ($zippy) {
print "Yow!";
}
# the Perlish post-condition way
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
```
while
```
while ( condition ) {
...
}
```
There's also a negated version, for the same reason we have `unless`:
```
until ( condition ) {
...
}
```
You can also use `while` in a post-condition:
```
print "LA LA LA\n" while 1; # loops forever
```
for Exactly like C:
```
for ($i = 0; $i <= $max; $i++) {
...
}
```
The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning `foreach` loop.
foreach
```
foreach (@array) {
print "This element is $_\n";
}
print $list[$_] foreach 0 .. $max;
# you don't have to use the default $_ either...
foreach my $key (keys %hash) {
print "The value of $key is $hash{$key}\n";
}
```
The `foreach` keyword is actually a synonym for the `for` keyword. See `["Foreach Loops" in perlsyn](perlsyn#Foreach-Loops)`.
For more detail on looping constructs (and some that weren't mentioned in this overview) see <perlsyn>.
###
Builtin operators and functions
Perl comes with a wide selection of builtin functions. Some of the ones we've already seen include `print`, `sort` and `reverse`. A list of them is given at the start of <perlfunc> and you can easily read about any given function by using `perldoc -f *functionname*`.
Perl operators are documented in full in <perlop>, but here are a few of the most common ones:
Arithmetic
```
+ addition
- subtraction
* multiplication
/ division
```
Numeric comparison
```
== equality
!= inequality
< less than
> greater than
<= less than or equal
>= greater than or equal
```
String comparison
```
eq equality
ne inequality
lt less than
gt greater than
le less than or equal
ge greater than or equal
```
(Why do we have separate numeric and string comparisons? Because we don't have special variable types, and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).
Boolean logic
```
&& and
|| or
! not
```
(`and`, `or` and `not` aren't just in the above table as descriptions of the operators. They're also supported as operators in their own right. They're more readable than the C-style operators, but have different precedence to `&&` and friends. Check <perlop> for more detail.)
Miscellaneous
```
= assignment
. string concatenation
x string multiplication (repeats strings)
.. range operator (creates a list of numbers or strings)
```
Many operators can be combined with a `=` as follows:
```
$a += 1; # same as $a = $a + 1
$a -= 1; # same as $a = $a - 1
$a .= "\n"; # same as $a = $a . "\n";
```
###
Files and I/O
You can open a file for input or output using the `open()` function. It's documented in extravagant detail in <perlfunc> and <perlopentut>, but in short:
```
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
```
You can read from an open filehandle using the `<>` operator. In scalar context it reads a single line from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list:
```
my $line = <$in>;
my @lines = <$in>;
```
Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl's looping constructs.
The `<>` operator is most often seen in a `while` loop:
```
while (<$in>) { # assigns each line in turn to $_
print "Just read in this line: $_";
}
```
We've already seen how to print to standard output using `print()`. However, `print()` can also take an optional first argument specifying which filehandle to print to:
```
print STDERR "This is your final warning.\n";
print $out $record;
print $log $logmessage;
```
When you're done with your filehandles, you should `close()` them (though to be honest, Perl will clean up after you if you forget):
```
close $in or die "$in: $!";
```
###
Regular expressions
Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in <perlrequick>, <perlretut>, and elsewhere. However, in short:
Simple matching
```
if (/foo/) { ... } # true if $_ contains "foo"
if ($a =~ /foo/) { ... } # true if $a contains "foo"
```
The `//` matching operator is documented in <perlop>. It operates on `$_` by default, or can be bound to another variable using the `=~` binding operator (also documented in <perlop>).
Simple substitution
```
s/foo/bar/; # replaces foo with bar in $_
$a =~ s/foo/bar/; # replaces foo with bar in $a
$a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar
# in $a
```
The `s///` substitution operator is documented in <perlop>.
More complex regular expressions You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. These are documented at great length in <perlre>, but for the meantime, here's a quick cheat sheet:
```
. a single character
\s a whitespace character (space, tab, newline,
...)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given
set
(foo|bar|baz) matches any of the alternatives specified
^ start of string
$ end of string
```
Quantifiers can be used to specify how many of the previous thing you want to match on, where "thing" means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses.
```
* zero or more of the previous thing
+ one or more of the previous thing
? zero or one of the previous thing
{3} matches exactly 3 of the previous thing
{3,6} matches between 3 and 6 of the previous thing
{3,} matches 3 or more of the previous thing
```
Some brief examples:
```
/^\d+/ string starts with one or more digits
/^$/ nothing in the string (start and end are
adjacent)
/(\d\s){3}/ three digits, each followed by a whitespace
character (eg "3 4 5 ")
/(a.)+/ matches a string in which every odd-numbered
letter is a (eg "abacadaf")
# This loop reads from STDIN, and prints non-blank lines:
while (<>) {
next if /^$/;
print;
}
```
Parentheses for capturing As well as grouping, parentheses serve a second purpose. They can be used to capture the results of parts of the regexp match for later use. The results end up in `$1`, `$2` and so on.
```
# a cheap and nasty way to break an email address up into parts
if ($email =~ /([^@]+)@(.+)/) {
print "Username is $1\n";
print "Hostname is $2\n";
}
```
Other regexp features Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in <perlrequick>, <perlretut>, and <perlre>.
###
Writing subroutines
Writing subroutines is easy:
```
sub logger {
my $logmessage = shift;
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
print $logfile $logmessage;
}
```
Now we can use the subroutine just as any other built-in function:
```
logger("We have a logger subroutine!");
```
What's that `shift`? Well, the arguments to a subroutine are available to us as a special array called `@_` (see <perlvar> for more on that). The default argument to the `shift` function just happens to be `@_`. So `my $logmessage = shift;` shifts the first item off the list of arguments and assigns it to `$logmessage`.
We can manipulate `@_` in other ways too:
```
my ($logmessage, $priority) = @_; # common
my $logmessage = $_[0]; # uncommon, and ugly
```
Subroutines can also return values:
```
sub square {
my $num = shift;
my $result = $num * $num;
return $result;
}
```
Then use it like:
```
$sq = square(8);
```
For more information on writing subroutines, see <perlsub>.
###
OO Perl
OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl's concept of packages. However, OO Perl is largely beyond the scope of this document. Read <perlootut> and <perlobj>.
As a beginning Perl programmer, your most common use of OO Perl will be in using third-party modules, which are documented below.
###
Using Perl modules
Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( <http://www.cpan.org/> ). A number of popular modules are included with the Perl distribution itself.
Categories of modules range from text manipulation to network protocols to database integration to graphics. A categorized list of modules is also available from CPAN.
To learn how to install modules you download from CPAN, read <perlmodinstall>.
To learn how to use a particular module, use `perldoc *Module::Name*`. Typically you will want to `use *Module::Name*`, which will then give you access to exported functions or an OO interface to the module.
<perlfaq> contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.
<perlmod> describes Perl modules in general. <perlmodlib> lists the modules which came with your Perl installation.
If you feel the urge to write Perl modules, <perlnewmod> will give you good advice.
AUTHOR
------
Kirrily "Skud" Robert <[email protected]>
| programming_docs |
perl Config::Perl::V Config::Perl::V
===============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [$conf = myconfig ()](#%24conf-=-myconfig-())
+ [$conf = plv2hash ($text [, ...])](#%24conf-=-plv2hash-(%24text-%5B,-...%5D))
+ [$info = summary ([$conf])](#%24info-=-summary-(%5B%24conf%5D))
+ [$md5 = signature ([$conf])](#%24md5-=-signature-(%5B%24conf%5D))
+ [The hash structure](#The-hash-structure)
* [REASONING](#REASONING)
* [BUGS](#BUGS)
* [TODO](#TODO)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
Config::Perl::V - Structured data retrieval of perl -V output
SYNOPSIS
--------
```
use Config::Perl::V;
my $local_config = Config::Perl::V::myconfig ();
print $local_config->{config}{osname};
```
DESCRIPTION
-----------
###
$conf = myconfig ()
This function will collect the data described in ["The hash structure"](#The-hash-structure) below, and return that as a hash reference. It optionally accepts an option to include more entries from %ENV. See ["environment"](#environment) below.
Note that this will not work on uninstalled perls when called with `-I/path/to/uninstalled/perl/lib`, but it works when that path is in `$PERL5LIB` or in `$PERL5OPT`, as paths passed using `-I` are not known when the `-V` information is collected.
###
$conf = plv2hash ($text [, ...])
Convert a sole 'perl -V' text block, or list of lines, to a complete myconfig hash. All unknown entries are defaulted.
###
$info = summary ([$conf])
Return an arbitrary selection of the information. If no `$conf` is given, `myconfig ()` is used instead.
###
$md5 = signature ([$conf])
Return the MD5 of the info returned by `summary ()` without the `config_args` entry.
If `Digest::MD5` is not available, it return a string with only `0`'s.
###
The hash structure
The returned hash consists of 4 parts:
build This information is extracted from the second block that is emitted by `perl -V`, and usually looks something like
```
Characteristics of this binary (from libperl):
Compile-time options: DEBUGGING USE_64_BIT_INT USE_LARGE_FILES
Locally applied patches:
defined-or
MAINT24637
Built under linux
Compiled at Jun 13 2005 10:44:20
@INC:
/usr/lib/perl5/5.8.7/i686-linux-64int
/usr/lib/perl5/5.8.7
/usr/lib/perl5/site_perl/5.8.7/i686-linux-64int
/usr/lib/perl5/site_perl/5.8.7
/usr/lib/perl5/site_perl
.
```
or
```
Characteristics of this binary (from libperl):
Compile-time options: DEBUGGING MULTIPLICITY
PERL_DONT_CREATE_GVSV PERL_IMPLICIT_CONTEXT
PERL_MALLOC_WRAP PERL_TRACK_MEMPOOL
PERL_USE_SAFE_PUTENV USE_ITHREADS
USE_LARGE_FILES USE_PERLIO
USE_REENTRANT_API
Built under linux
Compiled at Jan 28 2009 15:26:59
```
This information is not available anywhere else, including `%Config`, but it is the information that is only known to the perl binary.
The extracted information is stored in 5 entries in the `build` hash:
osname This is most likely the same as `$Config{osname}`, and was the name known when perl was built. It might be different if perl was cross-compiled.
The default for this field, if it cannot be extracted, is to copy `$Config{osname}`. The two may be differing in casing (OpenBSD vs openbsd).
stamp This is the time string for which the perl binary was compiled. The default value is 0.
options This is a hash with all the known defines as keys. The value is either 0, which means unknown or unset, or 1, which means defined.
derived As some variables are reported by a different name in the output of `perl -V` than their actual name in `%Config`, I decided to leave the `config` entry as close to reality as possible, and put in the entries that might have been guessed by the printed output in a separate block.
patches This is a list of optionally locally applied patches. Default is an empty list.
environment By default this hash is only filled with the environment variables out of %ENV that start with `PERL`, but you can pass the `env` option to myconfig to get more
```
my $conf = Config::Perl::V::myconfig ({ env => qr/^ORACLE/ });
my $conf = Config::Perl::V::myconfig ([ env => qr/^ORACLE/ ]);
```
config This hash is filled with the variables that `perl -V` fills its report with, and it has the same variables that `Config::myconfig` returns from `%Config`.
inc This is the list of default @INC.
REASONING
---------
This module was written to be able to return the configuration for the currently used perl as deeply as needed for the CPANTESTERS framework. Up until now they used the output of myconfig as a single text blob, and so it was missing the vital binary characteristics of the running perl and the optional applied patches.
BUGS
----
Please feedback what is wrong
TODO
----
```
* Implement retrieval functions/methods
* Documentation
* Error checking
* Tests
```
AUTHOR
------
H.Merijn Brand <[email protected]>
COPYRIGHT AND LICENSE
----------------------
Copyright (C) 2009-2020 H.Merijn Brand
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl perlfaq perlfaq
=======
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [Where to find the perlfaq](#Where-to-find-the-perlfaq)
+ [How to use the perlfaq](#How-to-use-the-perlfaq)
+ [How to contribute to the perlfaq](#How-to-contribute-to-the-perlfaq)
+ [What if my question isn't answered in the FAQ?](#What-if-my-question-isn't-answered-in-the-FAQ?)
* [TABLE OF CONTENTS](#TABLE-OF-CONTENTS)
* [THE QUESTIONS](#THE-QUESTIONS)
+ [perlfaq1: General Questions About Perl](#perlfaq1:-General-Questions-About-Perl)
+ [perlfaq2: Obtaining and Learning about Perl](#perlfaq2:-Obtaining-and-Learning-about-Perl)
+ [perlfaq3: Programming Tools](#perlfaq3:-Programming-Tools)
+ [perlfaq4: Data Manipulation](#perlfaq4:-Data-Manipulation)
+ [perlfaq5: Files and Formats](#perlfaq5:-Files-and-Formats)
+ [perlfaq6: Regular Expressions](#perlfaq6:-Regular-Expressions)
+ [perlfaq7: General Perl Language Issues](#perlfaq7:-General-Perl-Language-Issues)
+ [perlfaq8: System Interaction](#perlfaq8:-System-Interaction)
+ [perlfaq9: Web, Email and Networking](#perlfaq9:-Web,-Email-and-Networking)
* [CREDITS](#CREDITS)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq - Frequently asked questions about Perl
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
The perlfaq comprises several documents that answer the most commonly asked questions about Perl and Perl programming. It's divided by topic into nine major sections outlined in this document.
###
Where to find the perlfaq
The perlfaq is an evolving document. Read the latest version at <https://perldoc.perl.org/perlfaq>. It is also included in the standard Perl distribution.
###
How to use the perlfaq
The `perldoc` command line tool is part of the standard Perl distribution. To read the perlfaq:
```
$ perldoc perlfaq
```
To search the perlfaq question headings:
```
$ perldoc -q open
```
###
How to contribute to the perlfaq
Review <https://github.com/perl-doc-cats/perlfaq/wiki>. If you don't find your suggestion create an issue or pull request against <https://github.com/perl-doc-cats/perlfaq>.
Once approved, changes will be distributed with the next Perl release and subsequently appear at <https://perldoc.perl.org/perlfaq>.
###
What if my question isn't answered in the FAQ?
Try the resources in <perlfaq2>.
TABLE OF CONTENTS
------------------
perlfaq1 - General Questions About Perl
perlfaq2 - Obtaining and Learning about Perl
perlfaq3 - Programming Tools
perlfaq4 - Data Manipulation
perlfaq5 - Files and Formats
perlfaq6 - Regular Expressions
perlfaq7 - General Perl Language Issues
perlfaq8 - System Interaction
perlfaq9 - Web, Email and Networking
THE QUESTIONS
--------------
###
<perlfaq1>: General Questions About Perl
This section of the FAQ answers very general, high-level questions about Perl.
* What is Perl?
* Who supports Perl? Who develops it? Why is it free?
* Which version of Perl should I use?
* What are Perl 4, Perl 5, or Raku (Perl 6)?
* What is Raku (Perl 6)?
* How stable is Perl?
* How often are new versions of Perl released?
* Is Perl difficult to learn?
* How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?
* Can I do [task] in Perl?
* When shouldn't I program in Perl?
* What's the difference between "perl" and "Perl"?
* What is a JAPH?
* How can I convince others to use Perl?
###
<perlfaq2>: Obtaining and Learning about Perl
This section of the FAQ answers questions about where to find source and documentation for Perl, support, and related matters.
* What machines support Perl? Where do I get it?
* How can I get a binary version of Perl?
* I don't have a C compiler. How can I build my own Perl interpreter?
* I copied the Perl binary from one machine to another, but scripts don't work.
* I grabbed the sources and tried to compile but gdbm/dynamic loading/malloc/linking/... failed. How do I make it work?
* What modules and extensions are available for Perl? What is CPAN?
* Where can I get information on Perl?
* What is perl.com? Perl Mongers? pm.org? perl.org? cpan.org?
* Where can I post questions?
* Perl Books
* Which magazines have Perl content?
* Which Perl blogs should I read?
* What mailing lists are there for Perl?
* Where can I buy a commercial version of Perl?
* Where do I send bug reports?
###
<perlfaq3>: Programming Tools
This section of the FAQ answers questions related to programmer tools and programming support.
* How do I do (anything)?
* How can I use Perl interactively?
* How do I find which modules are installed on my system?
* How do I debug my Perl programs?
* How do I profile my Perl programs?
* How do I cross-reference my Perl programs?
* Is there a pretty-printer (formatter) for Perl?
* Is there an IDE or Windows Perl Editor?
* Where can I get Perl macros for vi?
* Where can I get perl-mode or cperl-mode for emacs?
* How can I use curses with Perl?
* How can I write a GUI (X, Tk, Gtk, etc.) in Perl?
* How can I make my Perl program run faster?
* How can I make my Perl program take less memory?
* Is it safe to return a reference to local or lexical data?
* How can I free an array or hash so my program shrinks?
* How can I make my CGI script more efficient?
* How can I hide the source for my Perl program?
* How can I compile my Perl program into byte code or C?
* How can I get `#!perl` to work on [MS-DOS,NT,...]?
* Can I write useful Perl programs on the command line?
* Why don't Perl one-liners work on my DOS/Mac/VMS system?
* Where can I learn about CGI or Web programming in Perl?
* Where can I learn about object-oriented Perl programming?
* Where can I learn about linking C with Perl?
* I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?
* When I tried to run my script, I got this message. What does it mean?
* What's MakeMaker?
###
<perlfaq4>: Data Manipulation
This section of the FAQ answers questions related to manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
* Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?
* Why is int() broken?
* Why isn't my octal data interpreted correctly?
* Does Perl have a round() function? What about ceil() and floor()? Trig functions?
* How do I convert between numeric representations/bases/radixes?
* Why doesn't & work the way I want it to?
* How do I multiply matrices?
* How do I perform an operation on a series of integers?
* How can I output Roman numerals?
* Why aren't my random numbers random?
* How do I get a random number between X and Y?
* How do I find the day or week of the year?
* How do I find the current century or millennium?
* How can I compare two dates and find the difference?
* How can I take a string and turn it into epoch seconds?
* How can I find the Julian Day?
* How do I find yesterday's date?
* Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?
* How do I validate input?
* How do I unescape a string?
* How do I remove consecutive pairs of characters?
* How do I expand function calls in a string?
* How do I find matching/nesting anything?
* How do I reverse a string?
* How do I expand tabs in a string?
* How do I reformat a paragraph?
* How can I access or change N characters of a string?
* How do I change the Nth occurrence of something?
* How can I count the number of occurrences of a substring within a string?
* How do I capitalize all the words on one line?
* How can I split a [character]-delimited string except when inside [character]?
* How do I strip blank space from the beginning/end of a string?
* How do I pad a string with blanks or pad a number with zeroes?
* How do I extract selected columns from a string?
* How do I find the soundex value of a string?
* How can I expand variables in text strings?
* Does Perl have anything like Ruby's #{} or Python's f string?
* What's wrong with always quoting "$vars"?
* Why don't my <<HERE documents work?
* What is the difference between a list and an array?
* What is the difference between $array[1] and @array[1]?
* How can I remove duplicate elements from a list or array?
* How can I tell whether a certain element is contained in a list or array?
* How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
* How do I test whether two arrays or hashes are equal?
* How do I find the first array element for which a condition is true?
* How do I handle linked lists?
* How do I handle circular lists?
* How do I shuffle an array randomly?
* How do I process/modify each element of an array?
* How do I select a random element from an array?
* How do I permute N elements of a list?
* How do I sort an array by (anything)?
* How do I manipulate arrays of bits?
* Why does defined() return true on empty arrays and hashes?
* How do I process an entire hash?
* How do I merge two hashes?
* What happens if I add or remove keys from a hash while iterating over it?
* How do I look up a hash element by value?
* How can I know how many entries are in a hash?
* How do I sort a hash (optionally by value instead of key)?
* How can I always keep my hash sorted?
* What's the difference between "delete" and "undef" with hashes?
* Why don't my tied hashes make the defined/exists distinction?
* How do I reset an each() operation part-way through?
* How can I get the unique keys from two hashes?
* How can I store a multidimensional array in a DBM file?
* How can I make my hash remember the order I put elements into it?
* Why does passing a subroutine an undefined element in a hash create it?
* How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?
* How can I use a reference as a hash key?
* How can I check if a key exists in a multilevel hash?
* How can I prevent addition of unwanted keys into a hash?
* How do I handle binary data correctly?
* How do I determine whether a scalar is a number/whole/integer/float?
* How do I keep persistent data across program calls?
* How do I print out or copy a recursive data structure?
* How do I define methods for every class/object?
* How do I verify a credit card checksum?
* How do I pack arrays of doubles or floats for XS code?
###
<perlfaq5>: Files and Formats
This section deals with I/O and the "f" issues: filehandles, flushing, formats, and footers.
* How do I flush/unbuffer an output filehandle? Why must I do this?
* How do I change, delete, or insert a line in a file, or append to the beginning of a file?
* How do I count the number of lines in a file?
* How do I delete the last N lines from a file?
* How can I use Perl's `-i` option from within a program?
* How can I copy a file?
* How do I make a temporary file name?
* How can I manipulate fixed-record-length files?
* How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles?
* How can I use a filehandle indirectly?
* How can I open a filehandle to a string?
* How can I set up a footer format to be used with write()?
* How can I write() into a string?
* How can I output my numbers with commas added?
* How can I translate tildes (~) in a filename?
* How come when I open a file read-write it wipes it out?
* Why do I sometimes get an "Argument list too long" when I use <\*>?
* How can I open a file named with a leading ">" or trailing blanks?
* How can I reliably rename a file?
* How can I lock a file?
* Why can't I just open(FH, ">file.lock")?
* I still don't get locking. I just want to increment the number in the file. How can I do this?
* All I want to do is append a small amount of text to the end of a file. Do I still have to use locking?
* How do I randomly update a binary file?
* How do I get a file's timestamp in perl?
* How do I set a file's timestamp in perl?
* How do I print to more than one file at once?
* How can I read in an entire file all at once?
* How can I read in a file by paragraphs?
* How can I read a single character from a file? From the keyboard?
* How can I tell whether there's a character waiting on a filehandle?
* How do I do a `tail -f` in perl?
* How do I dup() a filehandle in Perl?
* How do I close a file descriptor by number?
* Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
* Why doesn't glob("\*.\*") get all the files?
* Why does Perl let me delete read-only files? Why does `-i` clobber protected files? Isn't this a bug in Perl?
* How do I select a random line from a file?
* Why do I get weird spaces when I print an array of lines?
* How do I traverse a directory tree?
* How do I delete a directory tree?
* How do I copy an entire directory?
###
<perlfaq6>: Regular Expressions
This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number can be handled with regular expressions, but those answers are found elsewhere in this document (in perlfaq9 : "How do I decode or create those %-encodings on the web" and perlfaq4 : "How do I determine whether a scalar is a number/whole/integer/float", to be precise).
* How can I hope to use regular expressions without creating illegible and unmaintainable code?
* I'm having trouble matching over more than one line. What's wrong?
* How can I pull out lines between two patterns that are themselves on different lines?
* How do I match XML, HTML, or other nasty, ugly things with a regex?
* I put a regular expression into $/ but it didn't work. What's wrong?
* How do I substitute case-insensitively on the LHS while preserving case on the RHS?
* How can I make `\w` match national character sets?
* How can I match a locale-smart version of `/[a-zA-Z]/` ?
* How can I quote a variable to use in a regex?
* What is `/o` really for?
* How do I use a regular expression to strip C-style comments from a file?
* Can I use Perl regular expressions to match balanced text?
* What does it mean that regexes are greedy? How can I get around it?
* How do I process each word on each line?
* How can I print out a word-frequency or line-frequency summary?
* How can I do approximate matching?
* How do I efficiently match many regular expressions at once?
* Why don't word-boundary searches with `\b` work for me?
* Why does using $&, $`, or $' slow my program down?
* What good is `\G` in a regular expression?
* Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
* What's wrong with using grep in a void context?
* How can I match strings with multibyte characters?
* How do I match a regular expression that's in a variable?
###
<perlfaq7>: General Perl Language Issues
This section deals with general Perl language issues that don't clearly fit into any of the other sections.
* Can I get a BNF/yacc/RE for the Perl language?
* What are all these $@%&\* punctuation signs, and how do I know when to use them?
* Do I always/never have to quote my strings or use semicolons and commas?
* How do I skip some return values?
* How do I temporarily block warnings?
* What's an extension?
* Why do Perl operators have different precedence than C operators?
* How do I declare/create a structure?
* How do I create a module?
* How do I adopt or take over a module already on CPAN?
* How do I create a class?
* How can I tell if a variable is tainted?
* What's a closure?
* What is variable suicide and how can I prevent it?
* How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?
* How do I create a static variable?
* What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
* How can I access a dynamic variable while a similarly named lexical is in scope?
* What's the difference between deep and shallow binding?
* Why doesn't "my($foo) = <$fh>;" work right?
* How do I redefine a builtin function, operator, or method?
* What's the difference between calling a function as &foo and foo()?
* How do I create a switch or case statement?
* How can I catch accesses to undefined variables, functions, or methods?
* Why can't a method included in this same file be found?
* How can I find out my current or calling package?
* How can I comment out a large block of Perl code?
* How do I clear a package?
* How can I use a variable as a variable name?
* What does "bad interpreter" mean?
* Do I need to recompile XS modules when there is a change in the C library?
###
<perlfaq8>: System Interaction
This section of the Perl FAQ covers questions involving operating system interaction. Topics include interprocess communication (IPC), control over the user-interface (keyboard, screen and pointing devices), and most anything else not related to data manipulation.
* How do I find out which operating system I'm running under?
* How come exec() doesn't return?
* How do I do fancy stuff with the keyboard/screen/mouse?
* How do I print something out in color?
* How do I read just one key without waiting for a return key?
* How do I check whether input is ready on the keyboard?
* How do I clear the screen?
* How do I get the screen size?
* How do I ask the user for a password?
* How do I read and write the serial port?
* How do I decode encrypted password files?
* How do I start a process in the background?
* How do I trap control characters/signals?
* How do I modify the shadow password file on a Unix system?
* How do I set the time and date?
* How can I sleep() or alarm() for under a second?
* How can I measure time under a second?
* How can I do an atexit() or setjmp()/longjmp()? (Exception handling)
* Why doesn't my sockets program work under System V (Solaris)? What does the error message "Protocol not supported" mean?
* How can I call my system's unique C functions from Perl?
* Where do I get the include files to do ioctl() or syscall()?
* Why do setuid perl scripts complain about kernel problems?
* How can I open a pipe both to and from a command?
* Why can't I get the output of a command with system()?
* How can I capture STDERR from an external command?
* Why doesn't open() return an error when a pipe open fails?
* What's wrong with using backticks in a void context?
* How can I call backticks without shell processing?
* Why can't my script read from STDIN after I gave it EOF (^D on Unix, ^Z on MS-DOS)?
* How can I convert my shell script to perl?
* Can I use perl to run a telnet or ftp session?
* How can I write expect in Perl?
* Is there a way to hide perl's command line from programs such as "ps"?
* I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?
* How do I close a process's filehandle without waiting for it to complete?
* How do I fork a daemon process?
* How do I find out if I'm running interactively or not?
* How do I timeout a slow event?
* How do I set CPU limits?
* How do I avoid zombies on a Unix system?
* How do I use an SQL database?
* How do I make a system() exit on control-C?
* How do I open a file without blocking?
* How do I tell the difference between errors from the shell and perl?
* How do I install a module from CPAN?
* What's the difference between require and use?
* How do I keep my own module/library directory?
* How do I add the directory my program lives in to the module/library search path?
* How do I add a directory to my include path (@INC) at runtime?
* Where are modules installed?
* What is socket.ph and where do I get it?
###
<perlfaq9>: Web, Email and Networking
This section deals with questions related to running web sites, sending and receiving email as well as general networking.
* Should I use a web framework?
* Which web framework should I use?
* What is Plack and PSGI?
* How do I remove HTML from a string?
* How do I extract URLs?
* How do I fetch an HTML file?
* How do I automate an HTML form submission?
* How do I decode or create those %-encodings on the web?
* How do I redirect to another page?
* How do I put a password on my web pages?
* How do I make sure users can't enter values into a form that causes my CGI script to do bad things?
* How do I parse a mail header?
* How do I check a valid mail address?
* How do I decode a MIME/BASE64 string?
* How do I find the user's mail address?
* How do I send email?
* How do I use MIME to make an attachment to a mail message?
* How do I read email?
* How do I find out my hostname, domainname, or IP address?
* How do I fetch/put an (S)FTP file?
* How can I do RPC in Perl?
CREDITS
-------
Tom Christiansen wrote the original perlfaq then expanded it with the help of Nat Torkington. brian d foy substantially edited and expanded the perlfaq. perlfaq-workers and others have also supplied feedback, patches and corrections over the years.
AUTHOR AND COPYRIGHT
---------------------
Tom Christiansen wrote the original version of this document. brian d foy `<[email protected]>` wrote this version. See the individual perlfaq documents for additional copyright information.
This document is available under the same terms as Perl itself. Code examples in all the perlfaq documents are in the public domain. Use them as you see fit (and at your own risk with no warranty from anyone).
| programming_docs |
perl Text::Tabs Text::Tabs
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXPORTS](#EXPORTS)
* [EXAMPLE](#EXAMPLE)
* [BUGS](#BUGS)
* [LICENSE](#LICENSE)
NAME
----
Text::Tabs - expand and unexpand tabs like unix expand(1) and unexpand(1)
SYNOPSIS
--------
```
use Text::Tabs;
$tabstop = 4; # default = 8
@lines_without_tabs = expand(@lines_with_tabs);
@lines_with_tabs = unexpand(@lines_without_tabs);
```
DESCRIPTION
-----------
Text::Tabs does most of what the unix utilities expand(1) and unexpand(1) do. Given a line with tabs in it, `expand` replaces those tabs with the appropriate number of spaces. Given a line with or without tabs in it, `unexpand` adds tabs when it can save bytes by doing so, like the `unexpand -a` command.
Unlike the old unix utilities, this module correctly accounts for any Unicode combining characters (such as diacriticals) that may occur in each line for both expansion and unexpansion. These are overstrike characters that do not increment the logical position. Make sure you have the appropriate Unicode settings enabled.
EXPORTS
-------
The following are exported:
expand unexpand
$tabstop The `$tabstop` variable controls how many column positions apart each tabstop is. The default is 8.
Please note that `local($tabstop)` doesn't do the right thing and if you want to use `local` to override `$tabstop`, you need to use `local($Text::Tabs::tabstop)`.
EXAMPLE
-------
```
#!perl
# unexpand -a
use Text::Tabs;
while (<>) {
print unexpand $_;
}
```
Instead of the shell's `expand` command, use:
```
perl -MText::Tabs -n -e 'print expand $_'
```
Instead of the shell's `unexpand -a` command, use:
```
perl -MText::Tabs -n -e 'print unexpand $_'
```
BUGS
----
Text::Tabs handles only tabs (`"\t"`) and combining characters (`/\pM/`). It doesn't count backwards for backspaces (`"\t"`), omit other non-printing control characters (`/\pC/`), or otherwise deal with any other zero-, half-, and full-width characters.
LICENSE
-------
Copyright (C) 1996-2002,2005,2006 David Muir Sharnoff. Copyright (C) 2005 Aristotle Pagaltzis Copyright (C) 2012-2013 Google, Inc. This module may be modified, used, copied, and redistributed at your own risk. Although allowed by the preceding license, please do not publicly redistribute modified versions of this code with the name "Text::Tabs" unless it passes the unmodified Text::Tabs test suite.
perl AnyDBM_File AnyDBM\_File
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [DBM Comparisons](#DBM-Comparisons)
* [SEE ALSO](#SEE-ALSO)
NAME
----
AnyDBM\_File - provide framework for multiple DBMs
NDBM\_File, DB\_File, GDBM\_File, SDBM\_File, ODBM\_File - various DBM implementations
SYNOPSIS
--------
```
use AnyDBM_File;
```
DESCRIPTION
-----------
This module is a "pure virtual base class"--it has nothing of its own. It's just there to inherit from one of the various DBM packages. It prefers ndbm for compatibility reasons with Perl 4, then Berkeley DB (See [DB\_File](db_file)), GDBM, SDBM (which is always there--it comes with Perl), and finally ODBM. This way old programs that used to use NDBM via dbmopen() can still do so, but new ones can reorder @ISA:
```
BEGIN { @AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File) }
use AnyDBM_File;
```
Having multiple DBM implementations makes it trivial to copy database formats:
```
use Fcntl; use NDBM_File; use DB_File;
tie %newhash, 'DB_File', $new_filename, O_CREAT|O_RDWR;
tie %oldhash, 'NDBM_File', $old_filename, 1, 0;
%newhash = %oldhash;
```
###
DBM Comparisons
Here's a partial table of features the different packages offer:
```
odbm ndbm sdbm gdbm bsd-db
---- ---- ---- ---- ------
Linkage comes w/ perl yes yes yes yes yes
Src comes w/ perl no no yes no no
Comes w/ many unix os yes yes[0] no no no
Builds ok on !unix ? ? yes yes ?
Code Size ? ? small big big
Database Size ? ? small big? ok[1]
Speed ? ? slow ok fast
FTPable no no yes yes yes
Easy to build N/A N/A yes yes ok[2]
Size limits 1k 4k 1k[3] none none
Byte-order independent no no no no yes
Licensing restrictions ? ? no yes no
```
[0] on mixed universe machines, may be in the bsd compat library, which is often shunned.
[1] Can be trimmed if you compile for one access method.
[2] See [DB\_File](db_file). Requires symbolic links.
[3] By default, but can be redefined.
SEE ALSO
---------
dbm(3), ndbm(3), DB\_File(3), <perldbmfilter>
perl IPC::SharedMem IPC::SharedMem
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
IPC::SharedMem - SysV Shared Memory IPC object class
SYNOPSIS
--------
```
use IPC::SysV qw(IPC_PRIVATE S_IRUSR S_IWUSR);
use IPC::SharedMem;
$shm = IPC::SharedMem->new(IPC_PRIVATE, 8, S_IRWXU);
$shm->write(pack("S", 4711), 2, 2);
$data = $shm->read(0, 2);
$ds = $shm->stat;
$shm->remove;
```
DESCRIPTION
-----------
A class providing an object based interface to SysV IPC shared memory.
METHODS
-------
new ( KEY , SIZE , FLAGS ) Creates a new shared memory segment of `SIZE` bytes size associated with `KEY`. A new segment is created if
* `KEY` is equal to `IPC_PRIVATE`
* `KEY` does not already have a shared memory segment associated with it, and `*FLAGS* & IPC_CREAT` is true.
On creation of a new shared memory segment `FLAGS` is used to set the permissions. Be careful not to set any flags that the Sys V IPC implementation does not allow: in some systems setting execute bits makes the operations fail.
id Returns the shared memory identifier.
read ( POS, SIZE ) Read `SIZE` bytes from the shared memory segment at `POS`. Returns the string read, or `undef` if there was an error. The return value becomes tainted. See <shmread>.
write ( STRING, POS, SIZE ) Write `SIZE` bytes to the shared memory segment at `POS`. Returns true if successful, or false if there is an error. See <shmwrite>.
remove Remove the shared memory segment from the system or mark it as removed as long as any processes are still attached to it.
is\_removed Returns true if the shared memory segment has been removed or marked for removal.
stat Returns an object of type `IPC::SharedMem::stat` which is a sub-class of `Class::Struct`. It provides the following fields. For a description of these fields see you system documentation.
```
uid
gid
cuid
cgid
mode
segsz
lpid
cpid
nattch
atime
dtime
ctime
```
attach ( [FLAG] ) Permanently attach to the shared memory segment. When a `IPC::SharedMem` object is attached, it will use <memread> and <memwrite> instead of <shmread> and <shmwrite> for accessing the shared memory segment. Returns true if successful, or false on error. See [shmat(2)](http://man.he.net/man2/shmat).
detach Detach from the shared memory segment that previously has been attached to. Returns true if successful, or false on error. See [shmdt(2)](http://man.he.net/man2/shmdt).
addr Returns the address of the shared memory that has been attached to in a format suitable for use with `pack('P')`. Returns `undef` if the shared memory has not been attached.
SEE ALSO
---------
<IPC::SysV>, <Class::Struct>
AUTHORS
-------
Marcus Holland-Moritz <[email protected]>
COPYRIGHT
---------
Version 2.x, Copyright (C) 2007-2013, Marcus Holland-Moritz.
Version 1.x, Copyright (c) 1997, Graham Barr.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Test2::Hub::Subtest Test2::Hub::Subtest
===================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [TOGGLES](#TOGGLES)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Hub::Subtest - Hub used by subtests
DESCRIPTION
-----------
Subtests make use of this hub to route events.
TOGGLES
-------
$bool = $hub->manual\_skip\_all
$hub->set\_manual\_skip\_all($bool) The default is false.
Normally a skip-all plan event will cause a subtest to stop executing. This is accomplished via `last LABEL` to a label inside the subtest code. Most of the time this is perfectly fine. There are times however where this flow control causes bad things to happen.
This toggle lets you turn off the abort logic for the hub. When this is toggled to true **you** are responsible for ensuring no additional events are generated.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Thread::Semaphore Thread::Semaphore
=================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [METHODS](#METHODS)
* [NOTES](#NOTES)
* [SEE ALSO](#SEE-ALSO)
* [MAINTAINER](#MAINTAINER)
* [LICENSE](#LICENSE)
NAME
----
Thread::Semaphore - Thread-safe semaphores
VERSION
-------
This document describes Thread::Semaphore version 2.13
SYNOPSIS
--------
```
use Thread::Semaphore;
my $s = Thread::Semaphore->new();
$s->down(); # Also known as the semaphore P operation.
# The guarded section is here
$s->up(); # Also known as the semaphore V operation.
# Decrement the semaphore only if it would immediately succeed.
if ($s->down_nb()) {
# The guarded section is here
$s->up();
}
# Forcefully decrement the semaphore even if its count goes below 0.
$s->down_force();
# The default value for semaphore operations is 1
my $s = Thread::Semaphore->new($initial_value);
$s->down($down_value);
$s->up($up_value);
if ($s->down_nb($down_value)) {
...
$s->up($up_value);
}
$s->down_force($down_value);
```
DESCRIPTION
-----------
Semaphores provide a mechanism to regulate access to resources. Unlike locks, semaphores aren't tied to particular scalars, and so may be used to control access to anything you care to use them for.
Semaphores don't limit their values to zero and one, so they can be used to control access to some resource that there may be more than one of (e.g., filehandles). Increment and decrement amounts aren't fixed at one either, so threads can reserve or return multiple resources at once.
METHODS
-------
->new()
->new(NUMBER) `new` creates a new semaphore, and initializes its count to the specified number (which must be an integer). If no number is specified, the semaphore's count defaults to 1.
->down()
->down(NUMBER) The `down` method decreases the semaphore's count by the specified number (which must be an integer >= 1), or by one if no number is specified.
If the semaphore's count would drop below zero, this method will block until such time as the semaphore's count is greater than or equal to the amount you're `down`ing the semaphore's count by.
This is the semaphore "P operation" (the name derives from the Dutch word "pak", which means "capture" -- the semaphore operations were named by the late Dijkstra, who was Dutch).
->down\_nb()
->down\_nb(NUMBER) The `down_nb` method attempts to decrease the semaphore's count by the specified number (which must be an integer >= 1), or by one if no number is specified.
If the semaphore's count would drop below zero, this method will return *false*, and the semaphore's count remains unchanged. Otherwise, the semaphore's count is decremented and this method returns *true*.
->down\_force()
->down\_force(NUMBER) The `down_force` method decreases the semaphore's count by the specified number (which must be an integer >= 1), or by one if no number is specified. This method does not block, and may cause the semaphore's count to drop below zero.
->down\_timed(TIMEOUT)
->down\_timed(TIMEOUT, NUMBER) The `down_timed` method attempts to decrease the semaphore's count by 1 or by the specified number within the specified timeout period given in seconds (which must be an integer >= 0).
If the semaphore's count would drop below zero, this method will block until either the semaphore's count is greater than or equal to the amount you're `down`ing the semaphore's count by, or until the timeout is reached.
If the timeout is reached, this method will return *false*, and the semaphore's count remains unchanged. Otherwise, the semaphore's count is decremented and this method returns *true*.
->up()
->up(NUMBER) The `up` method increases the semaphore's count by the number specified (which must be an integer >= 1), or by one if no number is specified.
This will unblock any thread that is blocked trying to `down` the semaphore if the `up` raises the semaphore's count above the amount that the `down` is trying to decrement it by. For example, if three threads are blocked trying to `down` a semaphore by one, and another thread `up`s the semaphore by two, then two of the blocked threads (which two is indeterminate) will become unblocked.
This is the semaphore "V operation" (the name derives from the Dutch word "vrij", which means "release").
NOTES
-----
Semaphores created by <Thread::Semaphore> can be used in both threaded and non-threaded applications. This allows you to write modules and packages that potentially make use of semaphores, and that will function in either environment.
SEE ALSO
---------
Thread::Semaphore on MetaCPAN: <https://metacpan.org/release/Thread-Semaphore>
Code repository for CPAN distribution: <https://github.com/Dual-Life/Thread-Semaphore>
<threads>, <threads::shared>
Sample code in the *examples* directory of this distribution on CPAN.
MAINTAINER
----------
Jerry D. Hedden, <jdhedden AT cpan DOT org>
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl IO::Uncompress::RawInflate IO::Uncompress::RawInflate
==========================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [Functional Interface](#Functional-Interface)
+ [rawinflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]](#rawinflate-%24input_filename_or_reference-=%3E-%24output_filename_or_reference-%5B,-OPTS%5D)
- [The $input\_filename\_or\_reference parameter](#The-%24input_filename_or_reference-parameter)
- [The $output\_filename\_or\_reference parameter](#The-%24output_filename_or_reference-parameter)
+ [Notes](#Notes)
+ [Optional Parameters](#Optional-Parameters)
+ [Examples](#Examples)
* [OO Interface](#OO-Interface)
+ [Constructor](#Constructor)
+ [Constructor Options](#Constructor-Options)
+ [Examples](#Examples1)
* [Methods](#Methods)
+ [read](#read)
+ [read](#read1)
+ [getline](#getline)
+ [getc](#getc)
+ [ungetc](#ungetc)
+ [inflateSync](#inflateSync)
+ [getHeaderInfo](#getHeaderInfo)
+ [tell](#tell)
+ [eof](#eof)
+ [seek](#seek)
+ [binmode](#binmode)
+ [opened](#opened)
+ [autoflush](#autoflush)
+ [input\_line\_number](#input_line_number)
+ [fileno](#fileno)
+ [close](#close)
+ [nextStream](#nextStream)
+ [trailingData](#trailingData)
* [Importing](#Importing)
* [EXAMPLES](#EXAMPLES)
+ [Working with Net::FTP](#Working-with-Net::FTP)
* [SUPPORT](#SUPPORT)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
* [MODIFICATION HISTORY](#MODIFICATION-HISTORY)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
NAME
----
IO::Uncompress::RawInflate - Read RFC 1951 files/buffers
SYNOPSIS
--------
```
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
my $status = rawinflate $input => $output [,OPTS]
or die "rawinflate failed: $RawInflateError\n";
my $z = IO::Uncompress::RawInflate->new( $input [OPTS] )
or die "rawinflate failed: $RawInflateError\n";
$status = $z->read($buffer)
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$line = $z->getline()
$char = $z->getc()
$char = $z->ungetc()
$char = $z->opened()
$status = $z->inflateSync()
$data = $z->trailingData()
$status = $z->nextStream()
$data = $z->getHeaderInfo()
$z->tell()
$z->seek($position, $whence)
$z->binmode()
$z->fileno()
$z->eof()
$z->close()
$RawInflateError ;
# IO::File mode
<$z>
read($z, $buffer);
read($z, $buffer, $length);
read($z, $buffer, $length, $offset);
tell($z)
seek($z, $position, $whence)
binmode($z)
fileno($z)
eof($z)
close($z)
```
DESCRIPTION
-----------
This module provides a Perl interface that allows the reading of files/buffers that conform to RFC 1951.
For writing RFC 1951 files/buffers, see the companion module IO::Compress::RawDeflate.
Functional Interface
---------------------
A top-level function, `rawinflate`, is provided to carry out "one-shot" uncompression between buffers and/or files. For finer control over the uncompression process, see the ["OO Interface"](#OO-Interface) section.
```
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
rawinflate $input_filename_or_reference => $output_filename_or_reference [,OPTS]
or die "rawinflate failed: $RawInflateError\n";
```
The functional interface needs Perl5.005 or better.
###
rawinflate $input\_filename\_or\_reference => $output\_filename\_or\_reference [, OPTS]
`rawinflate` expects at least two parameters, `$input_filename_or_reference` and `$output_filename_or_reference` and zero or more optional parameters (see ["Optional Parameters"](#Optional-Parameters))
####
The `$input_filename_or_reference` parameter
The parameter, `$input_filename_or_reference`, is used to define the source of the compressed data.
It can take one of the following forms:
A filename If the `$input_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it.
A filehandle If the `$input_filename_or_reference` parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input_filename_or_reference` is a scalar reference, the input data will be read from `$$input_filename_or_reference`.
An array reference If `$input_filename_or_reference` is an array reference, each element in the array must be a filename.
The input data will be read from each file in turn.
The complete array will be walked to ensure that it only contains valid filenames before any data is uncompressed.
An Input FileGlob string If `$input_filename_or_reference` is a string that is delimited by the characters "<" and ">" `rawinflate` will assume that it is an *input fileglob string*. The input is the list of files that match the fileglob.
See <File::GlobMapper> for more details.
If the `$input_filename_or_reference` parameter is any other type, `undef` will be returned.
####
The `$output_filename_or_reference` parameter
The parameter `$output_filename_or_reference` is used to control the destination of the uncompressed data. This parameter can take one of these forms.
A filename If the `$output_filename_or_reference` parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the uncompressed data will be written to it.
A filehandle If the `$output_filename_or_reference` parameter is a filehandle, the uncompressed data will be written to it. The string '-' can be used as an alias for standard output.
A scalar reference If `$output_filename_or_reference` is a scalar reference, the uncompressed data will be stored in `$$output_filename_or_reference`.
An Array Reference If `$output_filename_or_reference` is an array reference, the uncompressed data will be pushed onto the array.
An Output FileGlob If `$output_filename_or_reference` is a string that is delimited by the characters "<" and ">" `rawinflate` will assume that it is an *output fileglob string*. The output is the list of files that match the fileglob.
When `$output_filename_or_reference` is an fileglob string, `$input_filename_or_reference` must also be a fileglob string. Anything else is an error.
See <File::GlobMapper> for more details.
If the `$output_filename_or_reference` parameter is any other type, `undef` will be returned.
### Notes
When `$input_filename_or_reference` maps to multiple compressed files/buffers and `$output_filename_or_reference` is a single file/buffer, after uncompression `$output_filename_or_reference` will contain a concatenation of all the uncompressed data from each of the input files/buffers.
###
Optional Parameters
The optional parameters for the one-shot function `rawinflate` are (for the most part) identical to those used with the OO interface defined in the ["Constructor Options"](#Constructor-Options) section. The exceptions are listed below
`AutoClose => 0|1`
This option applies to any input or output data streams to `rawinflate` that are filehandles.
If `AutoClose` is specified, and the value is true, it will result in all input and/or output filehandles being closed once `rawinflate` has completed.
This parameter defaults to 0.
`BinModeOut => 0|1`
This option is now a no-op. All files will be written in binmode.
`Append => 0|1`
The behaviour of this option is dependent on the type of output data stream.
* A Buffer
If `Append` is enabled, all uncompressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any uncompressed data is written to it.
* A Filename
If `Append` is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any uncompressed data is written to it.
* A Filehandle
If `Append` is enabled, the filehandle will be positioned to the end of the file via a call to `seek` before any uncompressed data is written to it. Otherwise the file pointer will not be moved.
When `Append` is specified, and set to true, it will *append* all uncompressed data to the output data stream.
So when the output is a filehandle it will carry out a seek to the eof before writing any uncompressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all uncompressed data will be appended to the existing buffer.
Conversely when `Append` is not specified, or it is present and is set to false, it will operate as follows.
When the output is a filename, it will truncate the contents of the file before writing any uncompressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any uncompressed data is output.
Defaults to 0.
`MultiStream => 0|1`
This option is a no-op.
`TrailingData => $scalar`
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option.
### Examples
To read the contents of the file `file1.txt.1951` and write the uncompressed data to the file `file1.txt`.
```
use strict ;
use warnings ;
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
my $input = "file1.txt.1951";
my $output = "file1.txt";
rawinflate $input => $output
or die "rawinflate failed: $RawInflateError\n";
```
To read from an existing Perl filehandle, `$input`, and write the uncompressed data to a buffer, `$buffer`.
```
use strict ;
use warnings ;
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
use IO::File ;
my $input = IO::File->new( "<file1.txt.1951" )
or die "Cannot open 'file1.txt.1951': $!\n" ;
my $buffer ;
rawinflate $input => \$buffer
or die "rawinflate failed: $RawInflateError\n";
```
To uncompress all files in the directory "/my/home" that match "\*.txt.1951" and store the compressed data in the same directory
```
use strict ;
use warnings ;
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
rawinflate '</my/home/*.txt.1951>' => '</my/home/#1.txt>'
or die "rawinflate failed: $RawInflateError\n";
```
and if you want to compress each file one at a time, this will do the trick
```
use strict ;
use warnings ;
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
for my $input ( glob "/my/home/*.txt.1951" )
{
my $output = $input;
$output =~ s/.1951// ;
rawinflate $input => $output
or die "Error compressing '$input': $RawInflateError\n";
}
```
OO Interface
-------------
### Constructor
The format of the constructor for IO::Uncompress::RawInflate is shown below
```
my $z = IO::Uncompress::RawInflate->new( $input [OPTS] )
or die "IO::Uncompress::RawInflate failed: $RawInflateError\n";
```
Returns an `IO::Uncompress::RawInflate` object on success and undef on failure. The variable `$RawInflateError` will contain an error message on failure.
If you are running Perl 5.005 or better the object, `$z`, returned from IO::Uncompress::RawInflate can be used exactly like an <IO::File> filehandle. This means that all normal input file operations can be carried out with `$z`. For example, to read a line from a compressed file/buffer you can use either of these forms
```
$line = $z->getline();
$line = <$z>;
```
The mandatory parameter `$input` is used to determine the source of the compressed data. This parameter can take one of three forms.
A filename If the `$input` parameter is a scalar, it is assumed to be a filename. This file will be opened for reading and the compressed data will be read from it.
A filehandle If the `$input` parameter is a filehandle, the compressed data will be read from it. The string '-' can be used as an alias for standard input.
A scalar reference If `$input` is a scalar reference, the compressed data will be read from `$$input`.
###
Constructor Options
The option names defined below are case insensitive and can be optionally prefixed by a '-'. So all of the following are valid
```
-AutoClose
-autoclose
AUTOCLOSE
autoclose
```
OPTS is a combination of the following options:
`AutoClose => 0|1`
This option is only valid when the `$input` parameter is a filehandle. If specified, and the value is true, it will result in the file being closed once either the `close` method is called or the IO::Uncompress::RawInflate object is destroyed.
This parameter defaults to 0.
`MultiStream => 0|1`
Allows multiple concatenated compressed streams to be treated as a single compressed stream. Decompression will stop once either the end of the file/buffer is reached, an error is encountered (premature eof, corrupt compressed data) or the end of a stream is not immediately followed by the start of another stream.
This parameter defaults to 0.
`Prime => $string`
This option will uncompress the contents of `$string` before processing the input file/buffer.
This option can be useful when the compressed data is embedded in another file/data structure and it is not possible to work out where the compressed data begins without having to read the first few bytes. If this is the case, the uncompression can be *primed* with these bytes using this option.
`Transparent => 0|1`
If this option is set and the input file/buffer is not compressed data, the module will allow reading of it anyway.
In addition, if the input file/buffer does contain compressed data and there is non-compressed data immediately following it, setting this option will make this module treat the whole file/buffer as a single data stream.
This option defaults to 1.
`BlockSize => $num`
When reading the compressed input data, IO::Uncompress::RawInflate will read it in blocks of `$num` bytes.
This option defaults to 4096.
`InputLength => $size`
When present this option will limit the number of compressed bytes read from the input file/buffer to `$size`. This option can be used in the situation where there is useful data directly after the compressed data stream and you know beforehand the exact length of the compressed data stream.
This option is mostly used when reading from a filehandle, in which case the file pointer will be left pointing to the first byte directly after the compressed data stream.
This option defaults to off.
`Append => 0|1`
This option controls what the `read` method does with uncompressed data.
If set to 1, all uncompressed data will be appended to the output parameter of the `read` method.
If set to 0, the contents of the output parameter of the `read` method will be overwritten by the uncompressed data.
Defaults to 0.
`Strict => 0|1`
This option is a no-op.
### Examples
TODO
Methods
-------
### read
Usage is
```
$status = $z->read($buffer)
```
Reads a block of compressed data (the size of the compressed block is determined by the `Buffer` option in the constructor), uncompresses it and writes any uncompressed data into `$buffer`. If the `Append` parameter is set in the constructor, the uncompressed data will be appended to the `$buffer` parameter. Otherwise `$buffer` will be overwritten.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### read
Usage is
```
$status = $z->read($buffer, $length)
$status = $z->read($buffer, $length, $offset)
$status = read($z, $buffer, $length)
$status = read($z, $buffer, $length, $offset)
```
Attempt to read `$length` bytes of uncompressed data into `$buffer`.
The main difference between this form of the `read` method and the previous one, is that this one will attempt to return *exactly* `$length` bytes. The only circumstances that this function will not is if end-of-file or an IO error is encountered.
Returns the number of uncompressed bytes written to `$buffer`, zero if eof or a negative number on error.
### getline
Usage is
```
$line = $z->getline()
$line = <$z>
```
Reads a single line.
This method fully supports the use of the variable `$/` (or `$INPUT_RECORD_SEPARATOR` or `$RS` when `English` is in use) to determine what constitutes an end of line. Paragraph mode, record mode and file slurp mode are all supported.
### getc
Usage is
```
$char = $z->getc()
```
Read a single character.
### ungetc
Usage is
```
$char = $z->ungetc($string)
```
### inflateSync
Usage is
```
$status = $z->inflateSync()
```
TODO
### getHeaderInfo
Usage is
```
$hdr = $z->getHeaderInfo();
@hdrs = $z->getHeaderInfo();
```
This method returns either a hash reference (in scalar context) or a list or hash references (in array context) that contains information about each of the header fields in the compressed data stream(s).
### tell
Usage is
```
$z->tell()
tell $z
```
Returns the uncompressed file offset.
### eof
Usage is
```
$z->eof();
eof($z);
```
Returns true if the end of the compressed input stream has been reached.
### seek
```
$z->seek($position, $whence);
seek($z, $position, $whence);
```
Provides a sub-set of the `seek` functionality, with the restriction that it is only legal to seek forward in the input file/buffer. It is a fatal error to attempt to seek backward.
Note that the implementation of `seek` in this module does not provide true random access to a compressed file/buffer. It works by uncompressing data from the current offset in the file/buffer until it reaches the uncompressed offset specified in the parameters to `seek`. For very small files this may be acceptable behaviour. For large files it may cause an unacceptable delay.
The `$whence` parameter takes one the usual values, namely SEEK\_SET, SEEK\_CUR or SEEK\_END.
Returns 1 on success, 0 on failure.
### binmode
Usage is
```
$z->binmode
binmode $z ;
```
This is a noop provided for completeness.
### opened
```
$z->opened()
```
Returns true if the object currently refers to a opened file/buffer.
### autoflush
```
my $prev = $z->autoflush()
my $prev = $z->autoflush(EXPR)
```
If the `$z` object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If `EXPR` is present, and is non-zero, it will enable flushing after every write/print operation.
If `$z` is associated with a buffer, this method has no effect and always returns `undef`.
**Note** that the special variable `$|` **cannot** be used to set or retrieve the autoflush setting.
### input\_line\_number
```
$z->input_line_number()
$z->input_line_number(EXPR)
```
Returns the current uncompressed line number. If `EXPR` is present it has the effect of setting the line number. Note that setting the line number does not change the current position within the file/buffer being read.
The contents of `$/` are used to determine what constitutes a line terminator.
### fileno
```
$z->fileno()
fileno($z)
```
If the `$z` object is associated with a file or a filehandle, `fileno` will return the underlying file descriptor. Once the `close` method is called `fileno` will return `undef`.
If the `$z` object is associated with a buffer, this method will return `undef`.
### close
```
$z->close() ;
close $z ;
```
Closes the output file/buffer.
For most versions of Perl this method will be automatically invoked if the IO::Uncompress::RawInflate object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the `close` method will be called automatically, but not until global destruction of all live objects when the program is terminating.
Therefore, if you want your scripts to be able to run on all versions of Perl, you should call `close` explicitly and not rely on automatic closing.
Returns true on success, otherwise 0.
If the `AutoClose` option has been enabled when the IO::Uncompress::RawInflate object was created, and the object is associated with a file, the underlying file will also be closed.
### nextStream
Usage is
```
my $status = $z->nextStream();
```
Skips to the next compressed data stream in the input file/buffer. If a new compressed data stream is found, the eof marker will be cleared and `$.` will be reset to 0.
Returns 1 if a new stream was found, 0 if none was found, and -1 if an error was encountered.
### trailingData
Usage is
```
my $data = $z->trailingData();
```
Returns the data, if any, that is present immediately after the compressed data stream once uncompression is complete. It only makes sense to call this method once the end of the compressed data stream has been encountered.
This option can be used when there is useful information immediately following the compressed data stream, and you don't know the length of the compressed data stream.
If the input is a buffer, `trailingData` will return everything from the end of the compressed data stream to the end of the buffer.
If the input is a filehandle, `trailingData` will return the data that is left in the filehandle input buffer once the end of the compressed data stream has been reached. You can then use the filehandle to read the rest of the input file.
Don't bother using `trailingData` if the input is a filename.
If you know the length of the compressed data stream before you start uncompressing, you can avoid having to use `trailingData` by setting the `InputLength` option in the constructor.
Importing
---------
No symbolic constants are required by IO::Uncompress::RawInflate at present.
:all Imports `rawinflate` and `$RawInflateError`. Same as doing this
```
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
```
EXAMPLES
--------
###
Working with Net::FTP
See [IO::Compress::FAQ](IO::Compress::FAQ#Compressed-files-and-Net%3A%3AFTP)
SUPPORT
-------
General feedback/questions/bug reports should be sent to <https://github.com/pmqs/IO-Compress/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
SEE ALSO
---------
<Compress::Zlib>, <IO::Compress::Gzip>, <IO::Uncompress::Gunzip>, <IO::Compress::Deflate>, <IO::Uncompress::Inflate>, <IO::Compress::RawDeflate>, <IO::Compress::Bzip2>, <IO::Uncompress::Bunzip2>, <IO::Compress::Lzma>, <IO::Uncompress::UnLzma>, <IO::Compress::Xz>, <IO::Uncompress::UnXz>, <IO::Compress::Lzip>, <IO::Uncompress::UnLzip>, <IO::Compress::Lzop>, <IO::Uncompress::UnLzop>, <IO::Compress::Lzf>, <IO::Uncompress::UnLzf>, <IO::Compress::Zstd>, <IO::Uncompress::UnZstd>, <IO::Uncompress::AnyInflate>, <IO::Uncompress::AnyUncompress>
<IO::Compress::FAQ>
<File::GlobMapper>, <Archive::Zip>, <Archive::Tar>, <IO::Zlib>
For RFC 1950, 1951 and 1952 see <https://datatracker.ietf.org/doc/html/rfc1950>, <https://datatracker.ietf.org/doc/html/rfc1951> and <https://datatracker.ietf.org/doc/html/rfc1952>
The *zlib* compression library was written by Jean-loup Gailly `[email protected]` and Mark Adler `[email protected]`.
The primary site for the *zlib* compression library is <http://www.zlib.org>.
The primary site for gzip is <http://www.gzip.org>.
AUTHOR
------
This module was written by Paul Marquess, `[email protected]`.
MODIFICATION HISTORY
---------------------
See the Changes file.
COPYRIGHT AND LICENSE
----------------------
Copyright (c) 2005-2022 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl splain splain
======
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [The diagnostics Pragma](#The-diagnostics-Pragma)
+ [The splain Program](#The-splain-Program)
* [EXAMPLES](#EXAMPLES)
* [INTERNALS](#INTERNALS)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
NAME
----
diagnostics, splain - produce verbose warning diagnostics
SYNOPSIS
--------
Using the `diagnostics` pragma:
```
use diagnostics;
use diagnostics -verbose;
enable diagnostics;
disable diagnostics;
```
Using the `splain` standalone filter program:
```
perl program 2>diag.out
splain [-v] [-p] diag.out
```
Using diagnostics to get stack traces from a misbehaving script:
```
perl -Mdiagnostics=-traceonly my_script.pl
```
DESCRIPTION
-----------
###
The `diagnostics` Pragma
This module extends the terse diagnostics normally emitted by both the perl compiler and the perl interpreter (from running perl with a -w switch or `use warnings`), augmenting them with the more explicative and endearing descriptions found in <perldiag>. Like the other pragmata, it affects the compilation phase of your program rather than merely the execution phase.
To use in your program as a pragma, merely invoke
```
use diagnostics;
```
at the start (or near the start) of your program. (Note that this *does* enable perl's **-w** flag.) Your whole compilation will then be subject(ed :-) to the enhanced diagnostics. These still go out **STDERR**.
Due to the interaction between runtime and compiletime issues, and because it's probably not a very good idea anyway, you may not use `no diagnostics` to turn them off at compiletime. However, you may control their behaviour at runtime using the disable() and enable() methods to turn them off and on respectively.
The **-verbose** flag first prints out the <perldiag> introduction before any other diagnostics. The $diagnostics::PRETTY variable can generate nicer escape sequences for pagers.
Warnings dispatched from perl itself (or more accurately, those that match descriptions found in <perldiag>) are only displayed once (no duplicate descriptions). User code generated warnings a la warn() are unaffected, allowing duplicate user messages to be displayed.
This module also adds a stack trace to the error message when perl dies. This is useful for pinpointing what caused the death. The **-traceonly** (or just **-t**) flag turns off the explanations of warning messages leaving just the stack traces. So if your script is dieing, run it again with
```
perl -Mdiagnostics=-traceonly my_bad_script
```
to see the call stack at the time of death. By supplying the **-warntrace** (or just **-w**) flag, any warnings emitted will also come with a stack trace.
###
The *splain* Program
Another program, *splain* is actually nothing more than a link to the (executable) *diagnostics.pm* module, as well as a link to the *diagnostics.pod* documentation. The **-v** flag is like the `use diagnostics -verbose` directive. The **-p** flag is like the $diagnostics::PRETTY variable. Since you're post-processing with *splain*, there's no sense in being able to enable() or disable() processing.
Output from *splain* is directed to **STDOUT**, unlike the pragma.
EXAMPLES
--------
The following file is certain to trigger a few errors at both runtime and compiletime:
```
use diagnostics;
print NOWHERE "nothing\n";
print STDERR "\n\tThis message should be unadorned.\n";
warn "\tThis is a user warning";
print "\nDIAGNOSTIC TESTER: Please enter a <CR> here: ";
my $a, $b = scalar <STDIN>;
print "\n";
print $x/$y;
```
If you prefer to run your program first and look at its problem afterwards, do this:
```
perl -w test.pl 2>test.out
./splain < test.out
```
Note that this is not in general possible in shells of more dubious heritage, as the theoretical
```
(perl -w test.pl >/dev/tty) >& test.out
./splain < test.out
```
Because you just moved the existing **stdout** to somewhere else.
If you don't want to modify your source code, but still have on-the-fly warnings, do this:
```
exec 3>&1; perl -w test.pl 2>&1 1>&3 3>&- | splain 1>&2 3>&-
```
Nifty, eh?
If you want to control warnings on the fly, do something like this. Make sure you do the `use` first, or you won't be able to get at the enable() or disable() methods.
```
use diagnostics; # checks entire compilation phase
print "\ntime for 1st bogus diags: SQUAWKINGS\n";
print BOGUS1 'nada';
print "done with 1st bogus\n";
disable diagnostics; # only turns off runtime warnings
print "\ntime for 2nd bogus: (squelched)\n";
print BOGUS2 'nada';
print "done with 2nd bogus\n";
enable diagnostics; # turns back on runtime warnings
print "\ntime for 3rd bogus: SQUAWKINGS\n";
print BOGUS3 'nada';
print "done with 3rd bogus\n";
disable diagnostics;
print "\ntime for 4th bogus: (squelched)\n";
print BOGUS4 'nada';
print "done with 4th bogus\n";
```
INTERNALS
---------
Diagnostic messages derive from the *perldiag.pod* file when available at runtime. Otherwise, they may be embedded in the file itself when the splain package is built. See the *Makefile* for details.
If an extant $SIG{\_\_WARN\_\_} handler is discovered, it will continue to be honored, but only after the diagnostics::splainthis() function (the module's $SIG{\_\_WARN\_\_} interceptor) has had its way with your warnings.
There is a $diagnostics::DEBUG variable you may set if you're desperately curious what sorts of things are being intercepted.
```
BEGIN { $diagnostics::DEBUG = 1 }
```
BUGS
----
Not being able to say "no diagnostics" is annoying, but may not be insurmountable.
The `-pretty` directive is called too late to affect matters. You have to do this instead, and *before* you load the module.
```
BEGIN { $diagnostics::PRETTY = 1 }
```
I could start up faster by delaying compilation until it should be needed, but this gets a "panic: top\_level" when using the pragma form in Perl 5.001e.
While it's true that this documentation is somewhat subserious, if you use a program named *splain*, you should expect a bit of whimsy.
AUTHOR
------
Tom Christiansen <*[email protected]*>, 25 June 1995.
perl Test2::Event::Encoding Test2::Event::Encoding
======================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
* [METHODS](#METHODS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::Event::Encoding - Set the encoding for the output stream
DESCRIPTION
-----------
The encoding event is generated when a test file wants to specify the encoding to be used when formatting its output. This event is intended to be produced by formatter classes and used for interpreting test names, message contents, etc.
SYNOPSIS
--------
```
use Test2::API qw/context/;
use Test2::Event::Encoding;
my $ctx = context();
my $event = $ctx->send_event('Encoding', encoding => 'UTF-8');
```
METHODS
-------
Inherits from <Test2::Event>. Also defines:
$encoding = $e->encoding The encoding being specified.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl Pod::Simple::PullParserEndToken Pod::Simple::PullParserEndToken
===============================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [SUPPORT](#SUPPORT)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Simple::PullParserEndToken -- end-tokens from Pod::Simple::PullParser
SYNOPSIS
--------
(See <Pod::Simple::PullParser>)
DESCRIPTION
-----------
When you do $parser->get\_token on a <Pod::Simple::PullParser>, you might get an object of this class.
This is a subclass of <Pod::Simple::PullParserToken> and inherits all its methods, and adds these methods:
$token->tagname This returns the tagname for this end-token object. For example, parsing a "=head1 ..." line will give you a start-token with the tagname of "head1", token(s) for its content, and then an end-token with the tagname of "head1".
$token->tagname(*somestring*) This changes the tagname for this end-token object. You probably won't need to do this.
$token->tag(...) A shortcut for $token->tagname(...)
$token->is\_tag(*somestring*) or $token->is\_tagname(*somestring*) These are shortcuts for `$token->tag() eq *somestring*`
You're unlikely to ever need to construct an object of this class for yourself, but if you want to, call `Pod::Simple::PullParserEndToken->new( *tagname* )`
SEE ALSO
---------
<Pod::Simple::PullParserToken>, <Pod::Simple>, <Pod::Simple::Subclassing>
SUPPORT
-------
Questions or discussion about POD and Pod::Simple should be sent to the [email protected] mail list. Send an empty email to [email protected] to subscribe.
This module is managed in an open GitHub repository, <https://github.com/perl-pod/pod-simple/>. Feel free to fork and contribute, or to clone <git://github.com/perl-pod/pod-simple.git> and send patches!
Patches against Pod::Simple are welcome. Please send bug reports to <[email protected]>.
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Pod::Simple was created by Sean M. Burke <[email protected]>. But don't bother him, he's retired.
Pod::Simple is maintained by:
* Allison Randal `[email protected]`
* Hans Dieter Pearcey `[email protected]`
* David E. Wheeler `[email protected]`
perl CPAN::HandleConfig CPAN::HandleConfig
==================
CONTENTS
--------
* [NAME](#NAME)
+ [CLASS->safe\_quote ITEM](#CLASS-%3Esafe_quote-ITEM)
* [LICENSE](#LICENSE)
NAME
----
CPAN::HandleConfig - internal configuration handling for CPAN.pm
###
`CLASS->safe_quote ITEM`
Quotes an item to become safe against spaces in shell interpolation. An item is enclosed in double quotes if:
```
- the item contains spaces in the middle
- the item does not start with a quote
```
This happens to avoid shell interpolation problems when whitespace is present in directory names.
This method uses `commands_quote` to determine the correct quote. If `commands_quote` is a space, no quoting will take place.
if it starts and ends with the same quote character: leave it as it is
if it contains no whitespace: leave it as it is
if it contains whitespace, then
if it contains quotes: better leave it as it is
else: quote it with the correct quote type for the box we're on
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
perl Win32API::File Win32API::File
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Object Oriented/Tied Handle Interface](#Object-Oriented/Tied-Handle-Interface)
+ [Exports](#Exports)
* [BUGS](#BUGS)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Win32API::File - Low-level access to Win32 system API calls for files/dirs.
SYNOPSIS
--------
```
use Win32API::File 0.08 qw( :ALL );
MoveFile( $Source, $Destination )
or die "Can't move $Source to $Destination: ",fileLastError(),"\n";
MoveFileEx( $Source, $Destination, MOVEFILE_REPLACE_EXISTING() )
or die "Can't move $Source to $Destination: ",fileLastError(),"\n";
[...]
```
DESCRIPTION
-----------
This provides fairly low-level access to the Win32 System API calls dealing with files and directories.
To pass in `NULL` as the pointer to an optional buffer, pass in an empty list reference, `[]`.
Beyond raw access to the API calls and related constants, this module handles smart buffer allocation and translation of return codes.
All functions, unless otherwise noted, return a true value for success and a false value for failure and set `$^E` on failure.
###
Object Oriented/Tied Handle Interface
WARNING: this is new code, use at your own risk.
This version of `Win32API::File` can be used like an `IO::File` object:
```
my $file = Win32API::File->new("+> foo");
binmode $file;
print $file "hello there\n";
seek $file, 0, 0;
my $line = <$file>;
$file->close;
```
It also supports tying via a win32 handle (for example, from `createFile()`):
```
tie FILE, 'Win32API::File', $win32_handle;
print FILE "...";
```
It has not been extensively tested yet and buffered I/O is not yet implemented.
### Exports
Nothing is exported by default. The following tags can be used to have large sets of symbols exported: `":Func"`, `":FuncA"`, `":FuncW"`, `":Misc"`, `":DDD_"`, `":DRIVE_"`, `":FILE_"`, `":FILE_ATTRIBUTE_"`, `":FILE_FLAG_"`, `":FILE_SHARE_"`, `":FILE_TYPE_"`, `":FS_"`, `":FSCTL_"`, `":HANDLE_FLAG_"`, `":IOCTL_STORAGE_"`, `":IOCTL_DISK_"`, `":GENERIC_"`, `":MEDIA_TYPE"`, `":MOVEFILE_"`, `":SECURITY_"`, `":SEM_"`, and `":PARTITION_"`.
`":Func"`
The basic function names: `attrLetsToBits`, `createFile`, `fileConstant`, `fileLastError`, `getLogicalDrives`, `setFilePointer`, `getFileSize`, `CloseHandle`, `CopyFile`, `CreateFile`, `DefineDosDevice`, `DeleteFile`, `DeviceIoControl`, `FdGetOsFHandle`, `GetDriveType`, `GetFileAttributes`, `GetFileSize`, `GetFileType`, `GetHandleInformation`, `GetLogicalDrives`, `GetLogicalDriveStrings`, `GetOsFHandle`, `GetOverlappedResult`, `GetVolumeInformation`, `IsContainerPartition`, `IsRecognizedPartition`, `MoveFile`, `MoveFileEx`, `OsFHandleOpen`, `OsFHandleOpenFd`, `QueryDosDevice`, `ReadFile`, `SetErrorMode`, `SetFilePointer`, `SetHandleInformation`, and `WriteFile`.
attrLetsToBits
`$uBits= attrLetsToBits( $sAttributeLetters )`
Converts a string of file attribute letters into an unsigned value with the corresponding bits set. `$sAttributeLetters` should contain zero or more letters from `"achorst"`:
`"a"`
`FILE_ATTRIBUTE_ARCHIVE`
`"c"`
`FILE_ATTRIBUTE_COMPRESSED`
`"h"`
`FILE_ATTRIBUTE_HIDDEN`
`"o"`
`FILE_ATTRIBUTE_OFFLINE`
`"r"`
`FILE_ATTRIBUTE_READONLY`
`"s"`
`FILE_ATTRIBUTE_SYSTEM`
`"t"`
`FILE_ATTRIBUTE_TEMPORARY`
createFile
`$hObject= createFile( $sPath )`
`$hObject= createFile( $sPath, $rvhvOptions )`
`$hObject= createFile( $sPath, $svAccess )`
`$hObject= createFile( $sPath, $svAccess, $rvhvOptions )`
`$hObject= createFile( $sPath, $svAccess, $svShare )`
`$hObject= createFile( $sPath, $svAccess, $svShare, $rvhvOptions )`
This is a Perl-friendly wrapper around `CreateFile`.
On failure, `$hObject` gets set to a false value and `regLastError()` and `$^E` are set to the reason for the failure. Otherwise, `$hObject` gets set to a Win32 native file handle which is always a true value [returns `"0 but true"` in the impossible(?) case of the handle having a value of `0`].
`$sPath` is the path to the file [or device, etc.] to be opened. See `CreateFile` for more information on possible special values for `$sPath`.
`$svAccess` can be a number containing the bit mask representing the specific type(s) of access to the file that you desire. See the `$uAccess` parameter to `CreateFile` for more information on these values.
More likely, `$svAccess` is a string describing the generic type of access you desire and possibly the file creation options to use. In this case, `$svAccess` should contain zero or more characters from `"qrw"` [access desired], zero or one character each from `"ktn"` and `"ce"`, and optional white space. These letters stand for, respectively, "Query access", "Read access", "Write access", "Keep if exists", "Truncate if exists", "New file only", "Create if none", and "Existing file only". Case is ignored.
You can pass in `"?"` for `$svAccess` to have an error message displayed summarizing its possible values. This is very handy when doing on-the-fly programming using the Perl debugger:
```
Win32API::File::createFile: $svAccess can use the following:
One or more of the following:
q -- Query access (same as 0)
r -- Read access (GENERIC_READ)
w -- Write access (GENERIC_WRITE)
At most one of the following:
k -- Keep if exists
t -- Truncate if exists
n -- New file only (fail if file already exists)
At most one of the following:
c -- Create if doesn't exist
e -- Existing file only (fail if doesn't exist)
'' is the same as 'q k e'
'r' is the same as 'r k e'
'w' is the same as 'w t c'
'rw' is the same as 'rw k c'
'rt' or 'rn' implies 'c'.
Or $access can be numeric.
```
`$svAccess` is designed to be "do what I mean", so you can skip the rest of its explanation unless you are interested in the complex details. Note that, if you want write access to a device, you need to specify `"k"` [and perhaps `"e"`, as in `"w ke"` or `"rw ke"`] since Win32 suggests `OPEN_EXISTING` be used when opening a device.
`"q"`
Stands for "Query access". This is really a no-op since you always have query access when you open a file. You can specify `"q"` to document that you plan to query the file [or device, etc.]. This is especially helpful when you don't want read nor write access since something like `"q"` or `"q ke"` may be easier to understand than just `""` or `"ke"`.
`"r"`
Stands for "Read access". Sets the `GENERIC_READ` bit(s) in the `$uAccess` that is passed to `CreateFile`. This is the default access if the `$svAccess` parameter is missing [or if it is `undef` and `$rvhvOptions` doesn't specify an `"Access"` option].
`"w"`
Stands for "Write access". Sets the `GENERIC_WRITE` bit(s) in the `$uAccess` that is passed to `CreateFile`.
`"k"`
Stands for "Keep if exists". If the requested file exists, then it is opened. This is the default unless `GENERIC_WRITE` access has been requested but `GENERIC_READ` access has not been requested. Contrast with `"t"` and `"n"`.
`"t"`
Stands for "Truncate if exists". If the requested file exists, then it is truncated to zero length and then opened. This is the default if `GENERIC_WRITE` access has been requested and `GENERIC_READ` access has not been requested. Contrast with `"k"` and `"n"`.
`"n"`
Stands for "New file only". If the requested file exists, then it is not opened and the `createFile` call fails. Contrast with `"k"` and `"t"`. Can't be used with `"e"`.
`"c"`
Stands for "Create if none". If the requested file does not exist, then it is created and then opened. This is the default if `GENERIC_WRITE` access has been requested or if `"t"` or `"n"` was specified. Contrast with `"e"`.
`"e"`
Stands for "Existing file only". If the requested file does not exist, then nothing is opened and the `createFile` call fails. This is the default unless `GENERIC_WRITE` access has been requested or `"t"` or `"n"` was specified. Contrast with `"c"`. Can't be used with `"n"`.
The characters from `"ktn"` and `"ce"` are combined to determine the what value for `$uCreate` to pass to `CreateFile` [unless overridden by `$rvhvOptions`]:
`"kc"`
`OPEN_ALWAYS`
`"ke"`
`OPEN_EXISTING`
`"tc"`
`TRUNCATE_EXISTING`
`"te"`
`CREATE_ALWAYS`
`"nc"`
`CREATE_NEW`
`"ne"`
Illegal.
`$svShare` controls how the file is shared, that is, whether other processes can have read, write, and/or delete access to the file while we have it opened. `$svShare` will usually be a string containing zero or more characters from `"rwd"` but can also be a numeric bit mask.
`"r"` sets the `FILE_SHARE_READ` bit which allows other processes to have read access to the file. `"w"` sets the `FILE_SHARE_WRITE` bit which allows other processes to have write access to the file. `"d"` sets the `FILE_SHARE_DELETE` bit which allows other processes to have delete access to the file [ignored under Windows 95].
The default for `$svShare` is `"rw"` which provides the same sharing as using regular perl `open()`.
If another process currently has read, write, and/or delete access to the file and you don't allow that level of sharing, then your call to `createFile` will fail. If you requested read, write, and/or delete access and another process already has the file open but doesn't allow that level of sharing, then your call to `createFile` will fail. Once you have the file open, if another process tries to open it with read, write, and/or delete access and you don't allow that level of sharing, then that process won't be allowed to open the file.
`$rvhvOptions` is a reference to a hash where any keys must be from the list `qw( Access Create Share Attributes Flags Security Model )`. The meaning of the value depends on the key name, as described below. Any option values in `$rvhvOptions` override the settings from `$svAccess` and `$svShare` if they conflict.
Flags => $uFlags `$uFlags` is an unsigned value having any of the `FILE_FLAG_*` or `FILE_ATTRIBUTE_*` bits set. Any `FILE_ATTRIBUTE_*` bits set via the `Attributes` option are logically `or`ed with these bits. Defaults to `0`.
If opening the client side of a named pipe, then you can also specify `SECURITY_SQOS_PRESENT` along with one of the other `SECURITY_*` constants to specify the security quality of service to be used.
Attributes => $sAttributes A string of zero or more characters from `"achorst"` [see `attrLetsToBits` for more information] which are converted to `FILE_ATTRIBUTE_*` bits to be set in the `$uFlags` argument passed to `CreateFile`.
Security => $pSecurityAttributes `$pSecurityAttributes` should contain a `SECURITY_ATTRIBUTES` structure packed into a string or `[]` [the default].
Model => $hModelFile `$hModelFile` should contain a handle opened with `GENERIC_READ` access to a model file from which file attributes and extended attributes are to be copied. Or `$hModelFile` can be `0` [the default].
Access => $sAccess
Access => $uAccess `$sAccess` should be a string of zero or more characters from `"qrw"` specifying the type of access desired: "query" or `0`, "read" or `GENERIC_READ` [the default], or "write" or `GENERIC_WRITE`.
`$uAccess` should be an unsigned value containing bits set to indicate the type of access desired. `GENERIC_READ` is the default.
Create => $sCreate
Create => $uCreate `$sCreate` should be a string containing zero or one character from `"ktn"` and zero or one character from `"ce"`. These stand for "Keep if exists", "Truncate if exists", "New file only", "Create if none", and "Existing file only". These are translated into a `$uCreate` value.
`$uCreate` should be one of `OPEN_ALWAYS`, `OPEN_EXISTING`, `TRUNCATE_EXISTING`, `CREATE_ALWAYS`, or `CREATE_NEW`.
Share => $sShare
Share => $uShare `$sShare` should be a string with zero or more characters from `"rwd"` that is translated into a `$uShare` value. `"rw"` is the default.
`$uShare` should be an unsigned value having zero or more of the following bits set: `FILE_SHARE_READ`, `FILE_SHARE_WRITE`, and `FILE_SHARE_DELETE`. `FILE_SHARE_READ|FILE_SHARE_WRITE` is the default.
Examples:
```
$hFlop= createFile( "//./A:", "r", "r" )
or die "Can't prevent others from writing to floppy: $^E\n";
$hDisk= createFile( "//./C:", "rw ke", "" )
or die "Can't get exclusive access to C: $^E\n";
$hDisk= createFile( $sFilePath, "ke",
{ Access=>FILE_READ_ATTRIBUTES } )
or die "Can't read attributes of $sFilePath: $^E\n";
$hTemp= createFile( "$ENV{Temp}/temp.$$", "wn", "",
{ Attributes=>"hst", Flags=>FILE_FLAG_DELETE_ON_CLOSE() } )
or die "Can't create temporary file, temp.$$: $^E\n";
```
getLogicalDrives
`@roots= getLogicalDrives()`
Returns the paths to the root directories of all logical drives currently defined. This includes all types of drive letters, such as floppies, CD-ROMs, hard disks, and network shares. A typical return value on a poorly equipped computer would be `("A:\\","C:\\")`.
CloseHandle
`CloseHandle( $hObject )`
Closes a Win32 native handle, such as one opened via `CreateFile`. Like most routines, returns a true value if successful and a false value [and sets `$^E` and `regLastError()`] on failure.
CopyFile
`CopyFile( $sOldFileName, $sNewFileName, $bFailIfExists )`
`$sOldFileName` is the path to the file to be copied. `$sNewFileName` is the path to where the file should be copied. Note that you can **NOT** just specify a path to a directory in `$sNewFileName` to copy the file to that directory using the same file name.
If `$bFailIfExists` is true and `$sNewFileName` is the path to a file that already exists, then `CopyFile` will fail. If `$bFailIfExists` is false, then the copy of the `$sOldFileNmae` file will overwrite the `$sNewFileName` file if it already exists.
Like most routines, returns a true value if successful and a false value [and sets `$^E` and `regLastError()`] on failure.
CreateFile
`$hObject= CreateFile( $sPath, $uAccess, $uShare, $pSecAttr, $uCreate, $uFlags, $hModel )`
On failure, `$hObject` gets set to a false value and `$^E` and `fileLastError()` are set to the reason for the failure. Otherwise, `$hObject` gets set to a Win32 native file handle which is always a true value [returns `"0 but true"` in the impossible(?) case of the handle having a value of `0`].
`$sPath` is the path to the file [or device, etc.] to be opened.
`$sPath` can use `"/"` or `"\\"` as path delimiters and can even mix the two. We will usually only use `"/"` in our examples since using `"\\"` is usually harder to read.
Under Windows NT, `$sPath` can start with `"//?/"` to allow the use of paths longer than `MAX_PATH` [for UNC paths, replace the leading `"//"` with `"//?/UNC/"`, as in `"//?/UNC/Server/Share/Dir/File.Ext"`].
`$sPath` can start with `"//./"` to indicate that the rest of the path is the name of a "DOS device." You can use `QueryDosDevice` to list all current DOS devices and can add or delete them with `DefineDosDevice`. If you get the source-code distribution of this module from CPAN, then it includes an example script, *ex/ListDevs.plx* that will list all current DOS devices and their "native" definition. Again, note that this doesn't work under Win95 nor Win98.
The most common such DOS devices include:
`"//./PhysicalDrive0"`
Your entire first hard disk. Doesn't work under Windows 95. This allows you to read or write raw sectors of your hard disk and to use `DeviceIoControl` to perform miscellaneous queries and operations to the hard disk. Writing raw sectors and certain other operations can seriously damage your files or the function of your computer.
Locking this for exclusive access [by specifying `0` for `$uShare`] doesn't prevent access to the partitions on the disk nor their file systems. So other processes can still access any raw sectors within a partition and can use the file system on the disk as usual.
`"//./C:"`
Your *C:* partition. Doesn't work under Windows 95. This allows you to read or write raw sectors of that partition and to use `DeviceIoControl` to perform miscellaneous queries and operations to the partition. Writing raw sectors and certain other operations can seriously damage your files or the function of your computer.
Locking this for exclusive access doesn't prevent access to the physical drive that the partition is on so other processes can still access the raw sectors that way. Locking this for exclusive access **does** prevent other processes from opening the same raw partition and **does** prevent access to the file system on it. It even prevents the current process from accessing the file system on that partition.
`"//./A:"`
The raw floppy disk. Doesn't work under Windows 95. This allows you to read or write raw sectors of the floppy disk and to use `DeviceIoControl` to perform miscellaneous queries and operations to the floppy disk or drive.
Locking this for exclusive access prevents all access to the floppy.
`"//./PIPE/PipeName"`
A named pipe, created via `CreateNamedPipe`.
`$uAccess` is an unsigned value with bits set indicating the type of access desired. Usually either `0` ["query" access], `GENERIC_READ`, `GENERIC_WRITE`, `GENERIC_READ|GENERIC_WRITE`, or `GENERIC_ALL`. More specific types of access can be specified, such as `FILE_APPEND_DATA` or `FILE_READ_EA`.
`$uShare` controls how the file is shared, that is, whether other processes can have read, write, and/or delete access to the file while we have it opened. `$uShare` is an unsigned value with zero or more of these bits set: `FILE_SHARE_READ`, `FILE_SHARE_WRITE`, and `FILE_SHARE_DELETE`.
If another process currently has read, write, and/or delete access to the file and you don't allow that level of sharing, then your call to `CreateFile` will fail. If you requested read, write, and/or delete access and another process already has the file open but doesn't allow that level of sharing, then your call to `createFile` will fail. Once you have the file open, if another process tries to open it with read, write, and/or delete access and you don't allow that level of sharing, then that process won't be allowed to open the file.
`$pSecAttr` should either be `[]` [for `NULL`] or a `SECURITY_ATTRIBUTES` data structure packed into a string. For example, if `$pSecDesc` contains a `SECURITY_DESCRIPTOR` structure packed into a string, perhaps via:
```
RegGetKeySecurity( $key, 4, $pSecDesc, 1024 );
```
then you can set `$pSecAttr` via:
```
$pSecAttr= pack( "L P i", 12, $pSecDesc, $bInheritHandle );
```
`$uCreate` is one of the following values: `OPEN_ALWAYS`, `OPEN_EXISTING`, `TRUNCATE_EXISTING`, `CREATE_ALWAYS`, and `CREATE_NEW`.
`$uFlags` is an unsigned value with zero or more bits set indicating attributes to associate with the file [`FILE_ATTRIBUTE_*` values] or special options [`FILE_FLAG_*` values].
If opening the client side of a named pipe, then you can also set `$uFlags` to include `SECURITY_SQOS_PRESENT` along with one of the other `SECURITY_*` constants to specify the security quality of service to be used.
`$hModel` is `0` [or `[]`, both of which mean `NULL`] or a Win32 native handle opened with `GENERIC_READ` access to a model file from which file attributes and extended attributes are to be copied if a new file gets created.
Examples:
```
$hFlop= CreateFile( "//./A:", GENERIC_READ(),
FILE_SHARE_READ(), [], OPEN_EXISTING(), 0, [] )
or die "Can't prevent others from writing to floppy: $^E\n";
$hDisk= CreateFile( $sFilePath, FILE_READ_ATTRIBUTES(),
FILE_SHARE_READ()|FILE_SHARE_WRITE(), [], OPEN_EXISTING(), 0, [] )
or die "Can't read attributes of $sFilePath: $^E\n";
$hTemp= CreateFile( "$ENV{Temp}/temp.$$", GENERIC_WRITE(), 0,
CREATE_NEW(), FILE_FLAG_DELETE_ON_CLOSE()|attrLetsToBits("hst"), [] )
or die "Can't create temporary file, temp.$$: $^E\n";
```
DefineDosDevice
`DefineDosDevice( $uFlags, $sDosDeviceName, $sTargetPath )`
Defines a new DOS device, overrides the current definition of a DOS device, or deletes a definition of a DOS device. Like most routines, returns a true value if successful and a false value [and sets `$^E` and `regLastError()`] on failure.
`$sDosDeviceName` is the name of a DOS device for which we'd like to add or delete a definition.
`$uFlags` is an unsigned value with zero or more of the following bits set:
`DDD_RAW_TARGET_PATH` Indicates that `$sTargetPath` will be a raw Windows NT object name. This usually means that `$sTargetPath` starts with `"\\Device\\"`. Note that you cannot use `"/"` in place of `"\\"` in raw target path names.
`DDD_REMOVE_DEFINITION` Requests that a definition be deleted. If `$sTargetPath` is `[]` [for `NULL`], then the most recently added definition for `$sDosDeviceName` is removed. Otherwise the most recently added definition matching `$sTargetPath` is removed.
If the last definition is removed, then the DOS device name is also deleted.
`DDD_EXACT_MATCH_ON_REMOVE` When deleting a definition, this bit causes each `$sTargetPath` to be compared to the full-length definition when searching for the most recently added match. If this bit is not set, then `$sTargetPath` only needs to match a prefix of the definition.
`$sTargetPath` is the DOS device's specific definition that you wish to add or delete. For `DDD_RAW_TARGET_PATH`, these usually start with `"\\Device\\"`. If the `DDD_RAW_TARGET_PATH` bit is not set, then `$sTargetPath` is just an ordinary path to some file or directory, providing the functionality of the **subst** command.
DeleteFile
`DeleteFile( $sFileName )`
Deletes the named file. Compared to Perl's `unlink`, `DeleteFile` has the advantage of not deleting read-only files. For **some** versions of Perl, `unlink` silently calls `chmod` whether it needs to or not before deleting the file so that files that you have protected by marking them as read-only are not always protected from Perl's `unlink`.
Like most routines, returns a true value if successful and a false value [and sets `$^E` and `regLastError()`] on failure.
DeviceIoControl
`DeviceIoControl( $hDevice, $uIoControlCode, $pInBuf, $lInBuf, $opOutBuf, $lOutBuf, $olRetBytes, $pOverlapped )`
Requests a special operation on an I/O [input/output] device, such as ejecting a tape or formatting a disk. Like most routines, returns a true value if successful and a false value [and sets `$^E` and `regLastError()`] on failure.
`$hDevice` is a Win32 native file handle to a device [return value from `CreateFile`].
`$uIoControlCode` is an unsigned value [a `IOCTL_*` or `FSCTL_*` constant] indicating the type query or other operation to be performed.
`$pInBuf` is `[]` [for `NULL`] or a data structure packed into a string. The type of data structure depends on the `$uIoControlCode` value. `$lInBuf` is `0` or the length of the structure in `$pInBuf`. If `$pInBuf` is not `[]` and `$lInBuf` is `0`, then `$lInBuf` will automatically be set to `length($pInBuf)` for you.
`$opOutBuf` is `[]` [for `NULL`] or will be set to contain a returned data structure packed into a string. `$lOutBuf` indicates how much space to allocate in `$opOutBuf` for `DeviceIoControl` to store the data structure. If `$lOutBuf` is a number and `$opOutBuf` already has a buffer allocated for it that is larger than `$lOutBuf` bytes, then this larger buffer size will be passed to `DeviceIoControl`. However, you can force a specific buffer size to be passed to `DeviceIoControl` by prepending a `"="` to the front of `$lOutBuf`.
`$olRetBytes` is `[]` or is a scalar to receive the number of bytes written to `$opOutBuf`. Even when `$olRetBytes` is `[]`, a valid pointer to a `DWORD` [and not `NULL`] is passed to `DeviceIoControl`. In this case, `[]` just means that you don't care about the value that might be written to `$olRetBytes`, which is usually the case since you can usually use `length($opOutBuf)` instead.
`$pOverlapped` is `[]` or is a `OVERLAPPED` structure packed into a string. This is only useful if `$hDevice` was opened with the `FILE_FLAG_OVERLAPPED` flag set.
FdGetOsFHandle
`$hNativeHandle= FdGetOsFHandle( $ivFd )`
`FdGetOsFHandle` simply calls `_get_osfhandle()`. It was renamed to better fit in with the rest the function names of this module, in particular to distinguish it from `GetOsFHandle`. It takes an integer file descriptor [as from Perl's `fileno`] and returns the Win32 native file handle associated with that file descriptor or `INVALID_HANDLE_VALUE` if `$ivFd` is not an open file descriptor.
When you call Perl's `open` to set a Perl file handle [like `STDOUT`], Perl calls C's `fopen` to set a stdio `FILE *`. C's `fopen` calls something like Unix's `open`, that is, Win32's `_sopen`, to get an integer file descriptor [where 0 is for `STDIN`, 1 for `STDOUT`, etc.]. Win32's `_sopen` calls `CreateFile` to set a `HANDLE`, a Win32 native file handle. So every Perl file handle [like `STDOUT`] has an integer file descriptor associated with it that you can get via `fileno`. And, under Win32, every file descriptor has a Win32 native file handle associated with it. `FdGetOsFHandle` lets you get access to that.
`$hNativeHandle` is set to `INVALID_HANDLE_VALUE` [and `lastFileError()` and `$^E` are set] if `FdGetOsFHandle` fails. See also `GetOsFHandle` which provides a friendlier interface.
fileConstant
`$value= fileConstant( $sConstantName )`
Fetch the value of a constant. Returns `undef` if `$sConstantName` is not the name of a constant supported by this module. Never sets `$!` nor `$^E`.
This function is rarely used since you will usually get the value of a constant by having that constant imported into your package by listing the constant name in the `use Win32API::File` statement and then simply using the constant name in your code [perhaps followed by `()`]. This function is useful for verifying constant names not in Perl code, for example, after prompting a user to type in a constant name.
fileLastError
`$svError= fileLastError();`
`fileLastError( $uError );`
Returns the last error encountered by a routine from this module. It is just like `$^E` except it isn't changed by anything except routines from this module. Ideally you could just use `$^E`, but current versions of Perl often overwrite `$^E` before you get a chance to check it and really old versions of Perl don't really support `$^E` under Win32.
Just like `$^E`, in a numeric context `fileLastError()` returns the numeric error value while in a string context it returns a text description of the error [actually it returns a Perl scalar that contains both values so `$x= fileLastError()` causes `$x` to give different values in string vs. numeric contexts].
The last form sets the error returned by future calls to `fileLastError()` and should not be used often. `$uError` must be a numeric error code. Also returns the dual-valued version of `$uError`.
GetDriveType
`$uDriveType= GetDriveType( $sRootPath )`
Takes a string giving the path to the root directory of a file system [called a "drive" because every file system is assigned a "drive letter"] and returns an unsigned value indicating the type of drive the file system is on. The return value should be one of:
`DRIVE_UNKNOWN` None of the following.
`DRIVE_NO_ROOT_DIR` A "drive" that does not have a file system. This can be a drive letter that hasn't been defined or a drive letter assigned to a partition that hasn't been formatted yet.
`DRIVE_REMOVABLE` A floppy diskette drive or other removable media drive, but not a CD-ROM drive.
`DRIVE_FIXED` An ordinary hard disk partition.
`DRIVE_REMOTE` A network share.
`DRIVE_CDROM` A CD-ROM drive.
`DRIVE_RAMDISK` A "ram disk" or memory-resident virtual file system used for high-speed access to small amounts of temporary file space.
GetFileAttributes
`$uAttrs = GetFileAttributes( $sPath )`
Takes a path string and returns an unsigned value with attribute flags. If it fails, it returns INVALID\_FILE\_ATTRIBUTES, otherwise it can be one or more of the following values:
`FILE_ATTRIBUTE_ARCHIVE` The file or directory is an archive file or directory. Applications use this attribute to mark files for backup or removal.
`FILE_ATTRIBUTE_COMPRESSED` The file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.
`FILE_ATTRIBUTE_DEVICE` Reserved; do not use.
`FILE_ATTRIBUTE_DIRECTORY` The handle identifies a directory.
`FILE_ATTRIBUTE_ENCRYPTED` The file or directory is encrypted. For a file, this means that all data streams in the file are encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories.
`FILE_ATTRIBUTE_HIDDEN` The file or directory is hidden. It is not included in an ordinary directory listing.
`FILE_ATTRIBUTE_NORMAL` The file or directory has no other attributes set. This attribute is valid only if used alone.
`FILE_ATTRIBUTE_NOT_CONTENT_INDEXED` The file will not be indexed by the content indexing service.
`FILE_ATTRIBUTE_OFFLINE` The data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.
`FILE_ATTRIBUTE_READONLY` The file or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.
`FILE_ATTRIBUTE_REPARSE_POINT` The file or directory has an associated reparse point.
`FILE_ATTRIBUTE_SPARSE_FILE` The file is a sparse file.
`FILE_ATTRIBUTE_SYSTEM` The file or directory is part of, or is used exclusively by, the operating system.
`FILE_ATTRIBUTE_TEMPORARY` The file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.
GetFileType
`$uFileType= GetFileType( $hFile )`
Takes a Win32 native file handle and returns a `FILE_TYPE_*` constant indicating the type of the file opened on that handle:
`FILE_TYPE_UNKNOWN` None of the below. Often a special device.
`FILE_TYPE_DISK` An ordinary disk file.
`FILE_TYPE_CHAR` What Unix would call a "character special file", that is, a device that works on character streams such as a printer port or a console.
`FILE_TYPE_PIPE` Either a named or anonymous pipe.
getFileSize
`$size= getFileSize( $hFile )`
This is a Perl-friendly wrapper for the `GetFileSize` (below) API call.
It takes a Win32 native file handle and returns the size in bytes. Since the size can be a 64 bit value, on non 64 bit integer Perls the value returned will be an object of type `Math::BigInt`.
GetFileSize
`$iSizeLow= GetFileSize($win32Handle, $iSizeHigh)`
Returns the size of a file pointed to by `$win32Handle`, optionally storing the high order 32 bits into `$iSizeHigh` if it is not `[]`. If $iSizeHigh is `[]`, a non-zero value indicates success. Otherwise, on failure the return value will be `0xffffffff` and `fileLastError()` will not be `NO_ERROR`.
GetOverlappedResult
`$bRetval= GetOverlappedResult( $win32Handle, $pOverlapped, $numBytesTransferred, $bWait )`
Used for asynchronous IO in Win32 to get the result of a pending IO operation, such as when a file operation returns `ERROR_IO_PENDING`. Returns a false value on failure. The `$overlapped` structure and `$numBytesTransferred` will be modified with the results of the operation.
As far as creating the `$pOverlapped` structure, you are currently on your own.
See <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/getoverlappedresult.asp> for more information.
GetLogicalDrives
`$uDriveBits= GetLogicalDrives()`
Returns an unsigned value with one bit set for each drive letter currently defined. If "A:" is currently a valid drive letter, then the `1` bit will be set in `$uDriveBits`. If "B:" is valid, then the `2` bit will be set. If "Z:" is valid, then the `2**26` [`0x4000000`] bit will be set.
GetLogicalDriveStrings
`$olOutLength= GetLogicalDriveStrings( $lBufSize, $osBuffer )`
For each currently defined drive letter, a `'\0'`-terminated string of the path to the root of its file system is constructed. All of these strings are concatenated into a single larger string and an extra terminating `'\0'` is added. This larger string is returned in `$osBuffer`. Note that this includes drive letters that have been defined but that have no file system, such as drive letters assigned to unformatted partitions.
`$lBufSize` is the size of the buffer to allocate to store this list of strings. `26*4+1` is always sufficient and should usually be used.
`$osBuffer` is a scalar to be set to contain the constructed string.
`$olOutLength` is the number of bytes actually written to `$osBuffer` but `length($osBuffer)` can also be used to determine this.
For example, on a poorly equipped computer,
```
GetLogicalDriveStrings( 4*26+1, $osBuffer );
```
might set `$osBuffer` to the 9-character string, `"A:\\\0C:\\\0\0"`.
GetHandleInformation
`GetHandleInformation( $hObject, $ouFlags )`
Retrieves the flags associated with a Win32 native file handle or object handle.
`$hObject` is an open Win32 native file handle or an open Win32 native handle to some other type of object.
`$ouFlags` will be set to an unsigned value having zero or more of the bits `HANDLE_FLAG_INHERIT` and `HANDLE_FLAG_PROTECT_FROM_CLOSE` set. See the `":HANDLE_FLAG_"` export class for the meanings of these bits.
GetOsFHandle
`$hNativeHandle= GetOsFHandle( FILE )`
Takes a Perl file handle [like `STDIN`] and returns the Win32 native file handle associated with it. See `FdGetOsFHandle` for more information about Win32 native file handles.
`$hNativeHandle` is set to a false value [and `lastFileError()` and `$^E` are set] if `GetOsFHandle` fails. `GetOsFHandle` returns `"0 but true"` in the impossible(?) case of the handle having a value of `0`.
GetVolumeInformation
`GetVolumeInformation( $sRootPath, $osVolName, $lVolName, $ouSerialNum, $ouMaxNameLen, $ouFsFlags, $osFsType, $lFsType )`
Gets information about a file system volume, returning a true value if successful. On failure, returns a false value and sets `fileLastError()` and `$^E`.
`$sRootPath` is a string specifying the path to the root of the file system, for example, `"C:/"`.
`$osVolName` is a scalar to be set to the string representing the volume name, also called the file system label. `$lVolName` is the number of bytes to allocate for the `$osVolName` buffer [see ["Buffer Sizes"](#Buffer-Sizes) for more information].
`$ouSerialNum` is `[]` [for `NULL`] or will be set to the numeric value of the volume's serial number.
`$ouMaxNameLen` is `[]` [for `NULL`] or will be set to the maximum length allowed for a file name or directory name within the file system.
`$osFsType` is a scalar to be set to the string representing the file system type, such as `"FAT"` or `"NTFS"`. `$lFsType` is the number of bytes to allocate for the `$osFsType` buffer [see ["Buffer Sizes"](#Buffer-Sizes) for more information].
`$ouFsFlags` is `[]` [for `NULL`] or will be set to an unsigned integer with bits set indicating properties of the file system:
`FS_CASE_IS_PRESERVED` The file system preserves the case of file names [usually true]. That is, it doesn't change the case of file names such as forcing them to upper- or lower-case.
`FS_CASE_SENSITIVE` The file system supports the ability to not ignore the case of file names [but might ignore case the way you are using it]. That is, the file system has the ability to force you to get the letter case of a file's name exactly right to be able to open it. This is true for "NTFS" file systems, even though case in file names is usually still ignored.
`FS_UNICODE_STORED_ON_DISK` The file system preserves Unicode in file names [true for "NTFS"].
`FS_PERSISTENT_ACLS` The file system supports setting Access Control Lists on files [true for "NTFS"].
`FS_FILE_COMPRESSION` The file system supports compression on a per-file basis [true for "NTFS"].
`FS_VOL_IS_COMPRESSED` The entire file system is compressed such as via "DoubleSpace".
IsRecognizedPartition
`IsRecognizedPartition( $ivPartitionType )`
Takes a partition type and returns whether that partition type is supported under Win32. `$ivPartitonType` is an integer value as from the operating system byte of a hard disk's DOS-compatible partition table [that is, a partition table for x86-based Win32, not, for example, one used with Windows NT for Alpha processors]. For example, the `PartitionType` member of the `PARTITION_INFORMATION` structure.
Common values for `$ivPartitionType` include `PARTITION_FAT_12==1`, `PARTITION_FAT_16==4`, `PARTITION_EXTENDED==5`, `PARTITION_FAT32==0xB`.
IsContainerPartition
`IsContainerPartition( $ivPartitionType )`
Takes a partition type and returns whether that partition is a "container" partition that is supported under Win32, that is, whether it is an "extended" partition that can contain "logical" partitions. `$ivPartitonType` is as for `IsRecognizedPartition`.
MoveFile
`MoveFile( $sOldName, $sNewName )`
Renames a file or directory. `$sOldName` is the name of the existing file or directory that is to be renamed. `$sNewName` is the new name to give the file or directory. Returns a true value if the move succeeds. For failure, returns a false value and sets `fileLastErorr()` and `$^E` to the reason for the failure.
Files can be "renamed" between file systems and the file contents and some attributes will be moved. Directories can only be renamed within one file system. If there is already a file or directory named `$sNewName`, then `MoveFile` will fail.
MoveFileEx
`MoveFileEx( $sOldName, $sNewName, $uFlags )`
Renames a file or directory. `$sOldName` is the name of the existing file or directory that is to be renamed. `$sNewName` is the new name to give the file or directory. Returns a true value if the move succeeds. For failure, returns a false value and sets `fileLastErorr()` and `$^E` to the reason for the failure.
`$uFlags` is an unsigned value with zero or more of the following bits set:
`MOVEFILE_REPLACE_EXISTING` If this bit is set and a file [but not a directory] named `$sNewName` already exists, then it will be replaced by `$sOldName`. If this bit is not set then `MoveFileEx` will fail rather than replace an existing `$sNewName`.
`MOVEFILE_COPY_ALLOWED` Allows files [but not directories] to be moved between file systems by copying the `$sOldName` file data and some attributes to `$sNewName` and then deleting `$sOldName`. If this bit is not set [or if `$sOldName` denotes a directory] and `$sNewName` refers to a different file system than `$sOldName`, then `MoveFileEx` will fail.
`MOVEFILE_DELAY_UNTIL_REBOOT` Preliminary verifications are made and then an entry is added to the Registry to cause the rename [or delete] operation to be done the next time this copy of the operating system is booted [right after any automatic file system checks have completed]. This is not supported under Windows 95.
When this bit is set, `$sNewName` can be `[]` [for `NULL`] to indicate that `$sOldName` should be deleted during the next boot rather than renamed.
Setting both the `MOVEFILE_COPY_ALLOWED` and `MOVEFILE_DELAY_UNTIL_REBOOT` bits will cause `MoveFileEx` to fail.
`MOVEFILE_WRITE_THROUGH` Ensures that `MoveFileEx` won't return until the operation has finished and been flushed to disk. This is not supported under Windows 95. Only affects file renames to another file system, forcing a buffer flush at the end of the copy operation.
OsFHandleOpen
`OsFHandleOpen( FILE, $hNativeHandle, $sMode )`
Opens a Perl file handle based on an already open Win32 native file handle [much like C's `fdopen()` does with a file descriptor]. Returns a true value if the open operation succeeded. For failure, returns a false value and sets `$!` [and possibly `fileLastError()` and `$^E`] to the reason for the failure.
`FILE` is a Perl file handle [in any of the supported forms, a bareword, a string, a typeglob, or a reference to a typeglob] that will be opened. If `FILE` is already open, it will automatically be closed before it is reopened.
`$hNativeHandle` is an open Win32 native file handle, probably the return value from `CreateFile` or `createFile`.
`$sMode` is string of zero or more letters from `"rwatb"`. These are translated into a combination `O_RDONLY` [`"r"`], `O_WRONLY` [`"w"`], `O_RDWR` [`"rw"`], `O_APPEND` [`"a"`], `O_TEXT` [`"t"`], and `O_BINARY` [`"b"`] flags [see the [Fcntl](fcntl) module] that is passed to `OsFHandleOpenFd`. Currently only `O_APPEND` and `O_TEXT` have any significance.
Also, a `"r"` and/or `"w"` in `$sMode` is used to decide how the file descriptor is converted into a Perl file handle, even though this doesn't appear to make a difference. One of the following is used:
```
open( FILE, "<&=".$ivFd ) # "r" w/o "w"
open( FILE, ">&=".$ivFd ) # "w" w/o "r"
open( FILE, "+<&=".$ivFd ) # both "r" and "w"
```
`OsFHandleOpen` eventually calls the Win32-specific C routine `_open_osfhandle()` or Perl's "improved" version called `win32_open_osfhandle()`. Prior to Perl5.005, C's `_open_osfhandle()` is called which will fail if `GetFileType($hNativeHandle)` would return `FILE_TYPE_UNKNOWN`. For Perl5.005 and later, `OsFHandleOpen` calls `win32_open_osfhandle()` from the Perl DLL which doesn't have this restriction.
OsFHandleOpenFd
`$ivFD= OsFHandleOpenFd( $hNativeHandle, $uMode )`
Opens a file descriptor [`$ivFD`] based on an already open Win32 native file handle, `$hNativeHandle`. This just calls the Win32-specific C routine `_open_osfhandle()` or Perl's "improved" version called `win32_open_osfhandle()`. Prior to Perl5.005 and in Cygwin Perl, C's `_open_osfhandle()` is called which will fail if `GetFileType($hNativeHandle)` would return `FILE_TYPE_UNKNOWN`. For Perl5.005 and later, `OsFHandleOpenFd` calls `win32_open_osfhandle()` from the Perl DLL which doesn't have this restriction.
`$uMode` the logical combination of zero or more `O_*` constants exported by the `Fcntl` module. Currently only `O_APPEND` and `O_TEXT` have any significance.
`$ivFD` will be non-negative if the open operation was successful. For failure, `-1` is returned and `$!` [and possibly `fileLastError()` and `$^E`] is set to the reason for the failure.
QueryDosDevice
`$olTargetLen= QueryDosDevice( $sDosDeviceName, $osTargetPath, $lTargetBuf )`
Looks up the definition of a given "DOS" device name, yielding the active Windows NT native device name along with any currently dormant definitions.
`$sDosDeviceName` is the name of the "DOS" device whose definitions we want. For example, `"C:"`, `"COM1"`, or `"PhysicalDrive0"`. If `$sDosDeviceName` is `[]` [for `NULL`], the list of all DOS device names is returned instead.
`$osTargetPath` will be assigned a string containing the list of definitions. The definitions are each `'\0'`-terminate and are concatenated into the string, most recent first, with an extra `'\0'` at the end of the whole string [see `GetLogicalDriveStrings` for a sample of this format].
`$lTargetBuf` is the size [in bytes] of the buffer to allocate for `$osTargetPath`. See ["Buffer Sizes"](#Buffer-Sizes) for more information.
`$olTargetLen` is set to the number of bytes written to `$osTargetPath` but you can also use `length($osTargetPath)` to determine this.
For failure, `0` is returned and `fileLastError()` and `$^E` are set to the reason for the failure.
ReadFile
`ReadFile( $hFile, $opBuffer, $lBytes, $olBytesRead, $pOverlapped )`
Reads bytes from a file or file-like device. Returns a true value if the read operation was successful. For failure, returns a false value and sets `fileLastError()` and `$^E` for the reason for the failure.
`$hFile` is a Win32 native file handle that is already open to the file or device to read from.
`$opBuffer` will be set to a string containing the bytes read.
`$lBytes` is the number of bytes you would like to read. `$opBuffer` is automatically initialized to have a buffer large enough to hold that many bytes. Unlike other buffer sizes, `$lBytes` does not need to have a `"="` prepended to it to prevent a larger value to be passed to the underlying Win32 `ReadFile` API. However, a leading `"="` will be silently ignored, even if Perl warnings are enabled.
If `$olBytesRead` is not `[]`, it will be set to the actual number of bytes read, though `length($opBuffer)` can also be used to determine this.
`$pOverlapped` is `[]` or is a `OVERLAPPED` structure packed into a string. This is only useful if `$hFile` was opened with the `FILE_FLAG_OVERLAPPED` flag set.
SetErrorMode
`$uOldMode= SetErrorMode( $uNewMode )`
Sets the mode controlling system error handling **and** returns the previous mode value. Both `$uOldMode` and `$uNewMode` will have zero or more of the following bits set:
`SEM_FAILCRITICALERRORS` If set, indicates that when a critical error is encountered, the call that triggered the error fails immediately. Normally this bit is not set, which means that a critical error causes a dialogue box to appear notifying the desktop user that some application has triggered a critical error. The dialogue box allows the desktop user to decide whether the critical error is returned to the process, is ignored, or the offending operation is retried.
This affects the `CreateFile` and `GetVolumeInformation` calls.
Setting this bit is useful for allowing you to check whether a floppy diskette is in the floppy drive.
`SEM_NOALIGNMENTFAULTEXCEPT` If set, this causes memory access misalignment faults to be automatically fixed in a manner invisible to the process. This flag is ignored on x86-based versions of Windows NT. This flag is not supported on Windows 95.
`SEM_NOGPFAULTERRORBOX` If set, general protection faults do not generate a dialogue box but can instead be handled by the process via an exception handler. This bit should not be set by programs that don't know how to handle such faults.
`SEM_NOOPENFILEERRORBOX` If set, then when an attempt to continue reading from or writing to an already open file [usually on a removable medium like a floppy diskette] finds the file no longer available, the call will immediately fail. Normally this bit is not set, which means that instead a dialogue box will appear notifying the desktop user that some application has run into this problem. The dialogue box allows the desktop user to decide whether the failure is returned to the process, is ignored, or the offending operation is retried.
This affects the `ReadFile` and `WriteFile` calls.
setFilePointer
`$uNewPos = setFilePointer( $hFile, $ivOffset, $uFromWhere )`
This is a perl-friendly wrapper for the SetFilePointer API (below). `$ivOffset` can be a 64 bit integer or `Math::BigInt` object if your Perl doesn't have 64 bit integers. The return value is the new offset and will likewise be a 64 bit integer or a `Math::BigInt` object.
SetFilePointer
`$uNewPos = SetFilePointer( $hFile, $ivOffset, $ioivOffsetHigh, $uFromWhere )`
The native Win32 version of `seek()`. `SetFilePointer` sets the position within a file where the next read or write operation will start from.
`$hFile` is a Win32 native file handle.
`$uFromWhere` is either `FILE_BEGIN`, `FILE_CURRENT`, or `FILE_END`, indicating that the new file position is being specified relative to the beginning of the file, the current file pointer, or the end of the file, respectively.
`$ivOffset` is [if `$ioivOffsetHigh` is `[]`] the offset [in bytes] to the new file position from the position specified via `$uFromWhere`. If `$ioivOffsetHigh` is not `[]`, then `$ivOffset` is converted to an unsigned value to be used as the low-order 4 bytes of the offset.
`$ioivOffsetHigh` can be `[]` [for `NULL`] to indicate that you are only specifying a 4-byte offset and the resulting file position will be 0xFFFFFFFE or less [just under 4GB]. Otherwise `$ioivOfffsetHigh` starts out with the high-order 4 bytes [signed] of the offset and gets set to the [unsigned] high-order 4 bytes of the resulting file position.
The underlying `SetFilePointer` returns `0xFFFFFFFF` to indicate failure, but if `$ioivOffsetHigh` is not `[]`, you would also have to check `$^E` to determine whether `0xFFFFFFFF` indicates an error or not. `Win32API::File::SetFilePointer` does this checking for you and returns a false value if and only if the underlying `SetFilePointer` failed. For this reason, `$uNewPos` is set to `"0 but true"` if you set the file pointer to the beginning of the file [or any position with 0 for the low-order 4 bytes].
So the return value will be true if the seek operation was successful. For failure, a false value is returned and `fileLastError()` and `$^E` are set to the reason for the failure.
SetHandleInformation
`SetHandleInformation( $hObject, $uMask, $uFlags )`
Sets the flags associated with a Win32 native file handle or object handle. Returns a true value if the operation was successful. For failure, returns a false value and sets `fileLastError()` and `$^E` for the reason for the failure.
`$hObject` is an open Win32 native file handle or an open Win32 native handle to some other type of object.
`$uMask` is an unsigned value having one or more of the bits `HANDLE_FLAG_INHERIT` and `HANDLE_FLAG_PROTECT_FROM_CLOSE` set. Only bits set in `$uMask` will be modified by `SetHandleInformation`.
`$uFlags` is an unsigned value having zero or more of the bits `HANDLE_FLAG_INHERIT` and `HANDLE_FLAG_PROTECT_FROM_CLOSE` set. For each bit set in `$uMask`, the corresponding bit in the handle's flags is set to the value of the corresponding bit in `$uFlags`.
If `$uOldFlags` were the value of the handle's flags before the call to `SetHandleInformation`, then the value of the handle's flags afterward would be:
```
( $uOldFlags & ~$uMask ) | ( $uFlags & $uMask )
```
[at least as far as the `HANDLE_FLAG_INHERIT` and `HANDLE_FLAG_PROTECT_FROM_CLOSE` bits are concerned.]
See the `":HANDLE_FLAG_"` export class for the meanings of these bits.
WriteFile
`WriteFile( $hFile, $pBuffer, $lBytes, $ouBytesWritten, $pOverlapped )`
Write bytes to a file or file-like device. Returns a true value if the operation was successful. For failure, returns a false value and sets `fileLastError()` and `$^E` for the reason for the failure.
`$hFile` is a Win32 native file handle that is already open to the file or device to be written to.
`$pBuffer` is a string containing the bytes to be written.
`$lBytes` is the number of bytes you would like to write. If `$pBuffer` is not at least `$lBytes` long, `WriteFile` croaks. You can specify `0` for `$lBytes` to write `length($pBuffer)` bytes. A leading `"="` on `$lBytes` will be silently ignored, even if Perl warnings are enabled.
`$ouBytesWritten` will be set to the actual number of bytes written unless you specify it as `[]`.
`$pOverlapped` is `[]` or is an `OVERLAPPED` structure packed into a string. This is only useful if `$hFile` was opened with the `FILE_FLAG_OVERLAPPED` flag set.
`":FuncA"`
The ASCII-specific functions. Each of these is just the same as the version without the trailing "A".
```
CopyFileA
CreateFileA
DefineDosDeviceA
DeleteFileA
GetDriveTypeA
GetFileAttributesA
GetLogicalDriveStringsA
GetVolumeInformationA
MoveFileA
MoveFileExA
QueryDosDeviceA
```
`":FuncW"`
The wide-character-specific (Unicode) functions. Each of these is just the same as the version without the trailing "W" except that strings are expected in Unicode and some lengths are measured as number of `WCHAR`s instead of number of bytes, as indicated below.
CopyFileW
`CopyFileW( $swOldFileName, $swNewFileName, $bFailIfExists )`
`$swOldFileName` and `$swNewFileName` are Unicode strings.
CreateFileW
`$hObject= CreateFileW( $swPath, $uAccess, $uShare, $pSecAttr, $uCreate, $uFlags, $hModel )`
`$swPath` is Unicode.
DefineDosDeviceW
`DefineDosDeviceW( $uFlags, $swDosDeviceName, $swTargetPath )`
`$swDosDeviceName` and `$swTargetPath` are Unicode.
DeleteFileW
`DeleteFileW( $swFileName )`
`$swFileName` is Unicode.
GetDriveTypeW
`$uDriveType= GetDriveTypeW( $swRootPath )`
`$swRootPath` is Unicode.
GetFileAttributesW
`$uAttrs= GetFileAttributesW( $swPath )`
`$swPath` is Unicode.
GetLogicalDriveStringsW
`$olwOutLength= GetLogicalDriveStringsW( $lwBufSize, $oswBuffer )`
Unicode is stored in `$oswBuffer`. `$lwBufSize` and `$olwOutLength` are measured as number of `WCHAR`s.
GetVolumeInformationW
`GetVolumeInformationW( $swRootPath, $oswVolName, $lwVolName, $ouSerialNum, $ouMaxNameLen, $ouFsFlags, $oswFsType, $lwFsType )`
`$swRootPath` is Unicode and Unicode is written to `$oswVolName` and `$oswFsType`. `$lwVolName` and `$lwFsType` are measures as number of `WCHAR`s.
MoveFileW
`MoveFileW( $swOldName, $swNewName )`
`$swOldName` and `$swNewName` are Unicode.
MoveFileExW
`MoveFileExW( $swOldName, $swNewName, $uFlags )`
`$swOldName` and `$swNewName` are Unicode.
QueryDosDeviceW
`$olwTargetLen= QueryDosDeviceW( $swDeviceName, $oswTargetPath, $lwTargetBuf )`
`$swDeviceName` is Unicode and Unicode is written to `$oswTargetPath`. `$lwTargetBuf` and `$olwTargetLen` are measured as number of `WCHAR`s.
`":Misc"`
Miscellaneous constants. Used for the `$uCreate` argument of `CreateFile` or the `$uFromWhere` argument of `SetFilePointer`. Plus `INVALID_HANDLE_VALUE`, which you usually won't need to check for since most routines translate it into a false value.
```
CREATE_ALWAYS CREATE_NEW OPEN_ALWAYS
OPEN_EXISTING TRUNCATE_EXISTING INVALID_HANDLE_VALUE
FILE_BEGIN FILE_CURRENT FILE_END
```
`":DDD_"`
Constants for the `$uFlags` argument of `DefineDosDevice`.
```
DDD_EXACT_MATCH_ON_REMOVE
DDD_RAW_TARGET_PATH
DDD_REMOVE_DEFINITION
```
`":DRIVE_"`
Constants returned by `GetDriveType`.
```
DRIVE_UNKNOWN DRIVE_NO_ROOT_DIR DRIVE_REMOVABLE
DRIVE_FIXED DRIVE_REMOTE DRIVE_CDROM
DRIVE_RAMDISK
```
`":FILE_"`
Specific types of access to files that can be requested via the `$uAccess` argument to `CreateFile`.
```
FILE_READ_DATA FILE_LIST_DIRECTORY
FILE_WRITE_DATA FILE_ADD_FILE
FILE_APPEND_DATA FILE_ADD_SUBDIRECTORY
FILE_CREATE_PIPE_INSTANCE FILE_READ_EA
FILE_WRITE_EA FILE_EXECUTE
FILE_TRAVERSE FILE_DELETE_CHILD
FILE_READ_ATTRIBUTES FILE_WRITE_ATTRIBUTES
FILE_ALL_ACCESS FILE_GENERIC_READ
FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE )],
```
`":FILE_ATTRIBUTE_"`
File attribute constants. Returned by `attrLetsToBits` and used in the `$uFlags` argument to `CreateFile`.
```
FILE_ATTRIBUTE_ARCHIVE FILE_ATTRIBUTE_COMPRESSED
FILE_ATTRIBUTE_HIDDEN FILE_ATTRIBUTE_NORMAL
FILE_ATTRIBUTE_OFFLINE FILE_ATTRIBUTE_READONLY
FILE_ATTRIBUTE_SYSTEM FILE_ATTRIBUTE_TEMPORARY
```
In addition, `GetFileAttributes` can return these constants (or INVALID\_FILE\_ATTRIBUTES in case of an error).
```
FILE_ATTRIBUTE_DEVICE FILE_ATTRIBUTE_DIRECTORY
FILE_ATTRIBUTE_ENCRYPTED FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
FILE_ATTRIBUTE_REPARSE_POINT FILE_ATTRIBUTE_SPARSE_FILE
```
`":FILE_FLAG_"`
File option flag constants. Used in the `$uFlags` argument to `CreateFile`.
```
FILE_FLAG_BACKUP_SEMANTICS FILE_FLAG_DELETE_ON_CLOSE
FILE_FLAG_NO_BUFFERING FILE_FLAG_OVERLAPPED
FILE_FLAG_POSIX_SEMANTICS FILE_FLAG_RANDOM_ACCESS
FILE_FLAG_SEQUENTIAL_SCAN FILE_FLAG_WRITE_THROUGH
FILE_FLAG_OPEN_REPARSE_POINT
```
`":FILE_SHARE_"`
File sharing constants. Used in the `$uShare` argument to `CreateFile`.
```
FILE_SHARE_DELETE FILE_SHARE_READ FILE_SHARE_WRITE
```
`":FILE_TYPE_"`
File type constants. Returned by `GetFileType`.
```
FILE_TYPE_CHAR FILE_TYPE_DISK
FILE_TYPE_PIPE FILE_TYPE_UNKNOWN
```
`":FS_"`
File system characteristics constants. Placed in the `$ouFsFlags` argument to `GetVolumeInformation`.
```
FS_CASE_IS_PRESERVED FS_CASE_SENSITIVE
FS_UNICODE_STORED_ON_DISK FS_PERSISTENT_ACLS
FS_FILE_COMPRESSION FS_VOL_IS_COMPRESSED
```
`":HANDLE_FLAG_"`
Flag bits modifying the behavior of an object handle and accessed via `GetHandleInformation` and `SetHandleInformation`.
HANDLE\_FLAG\_INHERIT If this bit is set, then children of this process who inherit handles [that is, processes created by calls to the Win32 `CreateProcess` API with the `bInheritHandles` parameter specified as `TRUE`], will inherit this particular object handle.
HANDLE\_FLAG\_PROTECT\_FROM\_CLOSE If this bit is set, then calls to `CloseHandle` against this handle will be ignored, leaving the handle open and usable.
`":IOCTL_STORAGE_"`
I/O control operations for generic storage devices. Used in the `$uIoControlCode` argument to `DeviceIoControl`. Includes `IOCTL_STORAGE_CHECK_VERIFY`, `IOCTL_STORAGE_MEDIA_REMOVAL`, `IOCTL_STORAGE_EJECT_MEDIA`, `IOCTL_STORAGE_LOAD_MEDIA`, `IOCTL_STORAGE_RESERVE`, `IOCTL_STORAGE_RELEASE`, `IOCTL_STORAGE_FIND_NEW_DEVICES`, and `IOCTL_STORAGE_GET_MEDIA_TYPES`.
`IOCTL_STORAGE_CHECK_VERIFY` Verify that a device's media is accessible. `$pInBuf` and `$opOutBuf` should both be `[]`. If `DeviceIoControl` returns a true value, then the media is currently accessible.
`IOCTL_STORAGE_MEDIA_REMOVAL` Allows the device's media to be locked or unlocked. `$opOutBuf` should be `[]`. `$pInBuf` should be a `PREVENT_MEDIA_REMOVAL` data structure, which is simply an integer containing a boolean value:
```
$pInBuf= pack( "i", $bPreventMediaRemoval );
```
`IOCTL_STORAGE_EJECT_MEDIA` Requests that the device eject the media. `$pInBuf` and `$opOutBuf` should both be `[]`.
`IOCTL_STORAGE_LOAD_MEDIA` Requests that the device load the media. `$pInBuf` and `$opOutBuf` should both be `[]`.
`IOCTL_STORAGE_RESERVE` Requests that the device be reserved. `$pInBuf` and `$opOutBuf` should both be `[]`.
`IOCTL_STORAGE_RELEASE` Releases a previous device reservation. `$pInBuf` and `$opOutBuf` should both be `[]`.
`IOCTL_STORAGE_FIND_NEW_DEVICES` No documentation on this IOCTL operation was found.
`IOCTL_STORAGE_GET_MEDIA_TYPES` Requests information about the type of media supported by the device. `$pInBuf` should be `[]`. `$opOutBuf` will be set to contain a vector of `DISK_GEOMETRY` data structures, which can be decoded via:
```
# Calculate the number of DISK_GEOMETRY structures returned:
my $cStructs= length($opOutBuf)/(4+4+4+4+4+4);
my @fields= unpack( "L l I L L L" x $cStructs, $opOutBuf )
my( @ucCylsLow, @ivcCylsHigh, @uMediaType, @uTracksPerCyl,
@uSectsPerTrack, @uBytesPerSect )= ();
while( @fields ) {
push( @ucCylsLow, unshift @fields );
push( @ivcCylsHigh, unshift @fields );
push( @uMediaType, unshift @fields );
push( @uTracksPerCyl, unshift @fields );
push( @uSectsPerTrack, unshift @fields );
push( @uBytesPerSect, unshift @fields );
}
```
For the `$i`th type of supported media, the following variables will contain the following data.
`$ucCylsLow[$i]`
The low-order 4 bytes of the total number of cylinders.
`$ivcCylsHigh[$i]`
The high-order 4 bytes of the total number of cylinders.
`$uMediaType[$i]`
A code for the type of media. See the `":MEDIA_TYPE"` export class.
`$uTracksPerCyl[$i]`
The number of tracks in each cylinder.
`$uSectsPerTrack[$i]`
The number of sectors in each track.
`$uBytesPerSect[$i]`
The number of bytes in each sector.
`":IOCTL_DISK_"`
I/O control operations for disk devices. Used in the `$uIoControlCode` argument to `DeviceIoControl`. Most of these are to be used on physical drive devices like `"//./PhysicalDrive0"`. However, `IOCTL_DISK_GET_PARTITION_INFO` and `IOCTL_DISK_SET_PARTITION_INFO` should only be used on a single-partition device like `"//./C:"`. Also, `IOCTL_DISK_GET_MEDIA_TYPES` is documented as having been superseded but is still useful when used on a floppy device like `"//./A:"`.
Includes `IOCTL_DISK_FORMAT_TRACKS`, `IOCTL_DISK_FORMAT_TRACKS_EX`, `IOCTL_DISK_GET_DRIVE_GEOMETRY`, `IOCTL_DISK_GET_DRIVE_LAYOUT`, `IOCTL_DISK_GET_MEDIA_TYPES`, `IOCTL_DISK_GET_PARTITION_INFO`, `IOCTL_DISK_HISTOGRAM_DATA`, `IOCTL_DISK_HISTOGRAM_RESET`, `IOCTL_DISK_HISTOGRAM_STRUCTURE`, `IOCTL_DISK_IS_WRITABLE`, `IOCTL_DISK_LOGGING`, `IOCTL_DISK_PERFORMANCE`, `IOCTL_DISK_REASSIGN_BLOCKS`, `IOCTL_DISK_REQUEST_DATA`, `IOCTL_DISK_REQUEST_STRUCTURE`, `IOCTL_DISK_SET_DRIVE_LAYOUT`, `IOCTL_DISK_SET_PARTITION_INFO`, and `IOCTL_DISK_VERIFY`.
`IOCTL_DISK_GET_DRIVE_GEOMETRY` Request information about the size and geometry of the disk. `$pInBuf` should be `[]`. `$opOutBuf` will be set to a `DISK_GEOMETRY` data structure which can be decode via:
```
( $ucCylsLow, $ivcCylsHigh, $uMediaType, $uTracksPerCyl,
$uSectsPerTrack, $uBytesPerSect )= unpack( "L l I L L L", $opOutBuf );
```
`$ucCylsLow`
The low-order 4 bytes of the total number of cylinders.
`$ivcCylsHigh`
The high-order 4 bytes of the total number of cylinders.
`$uMediaType`
A code for the type of media. See the `":MEDIA_TYPE"` export class.
`$uTracksPerCyl`
The number of tracks in each cylinder.
`$uSectsPerTrack`
The number of sectors in each track.
`$uBytesPerSect`
The number of bytes in each sector.
`IOCTL_DISK_GET_PARTITION_INFO` Request information about the size and geometry of the partition. `$pInBuf` should be `[]`. `$opOutBuf` will be set to a `PARTITION_INFORMATION` data structure which can be decode via:
```
( $uStartLow, $ivStartHigh, $ucHiddenSects, $uPartitionSeqNumber,
$uPartitionType, $bActive, $bRecognized, $bToRewrite )=
unpack( "L l L L C c c c", $opOutBuf );
```
`$uStartLow` and `$ivStartHigh`
The low-order and high-order [respectively] 4 bytes of the starting offset of the partition, measured in bytes.
`$ucHiddenSects`
The number of "hidden" sectors for this partition. Actually this is the number of sectors found prior to this partition, that is, the starting offset [as found in `$uStartLow` and `$ivStartHigh`] divided by the number of bytes per sector.
`$uPartitionSeqNumber`
The sequence number of this partition. Partitions are numbered starting as `1` [with "partition 0" meaning the entire disk]. Sometimes this field may be `0` and you'll have to infer the partition sequence number from how many partitions precede it on the disk.
`$uPartitionType`
The type of partition. See the `":PARTITION_"` export class for a list of known types. See also `IsRecognizedPartition` and `IsContainerPartition`.
`$bActive`
`1` for the active [boot] partition, `0` otherwise.
`$bRecognized`
Whether this type of partition is support under Win32.
`$bToRewrite`
Whether to update this partition information. This field is not used by `IOCTL_DISK_GET_PARTITION_INFO`. For `IOCTL_DISK_SET_DRIVE_LAYOUT`, you must set this field to a true value for any partitions you wish to have changed, added, or deleted.
`IOCTL_DISK_SET_PARTITION_INFO` Change the type of the partition. `$opOutBuf` should be `[]`. `$pInBuf` should be a `SET_PARTITION_INFORMATION` data structure which is just a single byte containing the new partition type [see the `":PARTITION_"` export class for a list of known types]:
```
$pInBuf= pack( "C", $uPartitionType );
```
`IOCTL_DISK_GET_DRIVE_LAYOUT` Request information about the disk layout. `$pInBuf` should be `[]`. `$opOutBuf` will be set to contain `DRIVE_LAYOUT_INFORMATION` structure including several `PARTITION_INFORMATION` structures:
```
my( $cPartitions, $uDiskSignature )= unpack( "L L", $opOutBuf );
my @fields= unpack( "x8" . ( "L l L L C c c c" x $cPartitions ),
$opOutBuf );
my( @uStartLow, @ivStartHigh, @ucHiddenSects,
@uPartitionSeqNumber, @uPartitionType, @bActive,
@bRecognized, @bToRewrite )= ();
for( 1..$cPartition ) {
push( @uStartLow, unshift @fields );
push( @ivStartHigh, unshift @fields );
push( @ucHiddenSects, unshift @fields );
push( @uPartitionSeqNumber, unshift @fields );
push( @uPartitionType, unshift @fields );
push( @bActive, unshift @fields );
push( @bRecognized, unshift @fields );
push( @bToRewrite, unshift @fields );
}
```
`$cPartitions`
If the number of partitions on the disk.
`$uDiskSignature`
Is the disk signature, a unique number assigned by Disk Administrator [*WinDisk.exe*] and used to identify the disk. This allows drive letters for partitions on that disk to remain constant even if the SCSI Target ID of the disk gets changed.
See `IOCTL_DISK_GET_PARTITION_INFORMATION` for information on the remaining these fields.
`IOCTL_DISK_GET_MEDIA_TYPES` Is supposed to be superseded by `IOCTL_STORAGE_GET_MEDIA_TYPES` but is still useful for determining the types of floppy diskette formats that can be produced by a given floppy drive. See *ex/FormatFloppy.plx* for an example.
`IOCTL_DISK_SET_DRIVE_LAYOUT` Change the partition layout of the disk. `$pOutBuf` should be `[]`. `$pInBuf` should be a `DISK_LAYOUT_INFORMATION` data structure including several `PARTITION_INFORMATION` data structures.
```
# Already set: $cPartitions, $uDiskSignature, @uStartLow, @ivStartHigh,
# @ucHiddenSects, @uPartitionSeqNumber, @uPartitionType, @bActive,
# @bRecognized, and @bToRewrite.
my( @fields, $prtn )= ();
for $prtn ( 1..$cPartition ) {
push( @fields, $uStartLow[$prtn-1], $ivStartHigh[$prtn-1],
$ucHiddenSects[$prtn-1], $uPartitionSeqNumber[$prtn-1],
$uPartitionType[$prtn-1], $bActive[$prtn-1],
$bRecognized[$prtn-1], $bToRewrite[$prtn-1] );
}
$pInBuf= pack( "L L" . ( "L l L L C c c c" x $cPartitions ),
$cPartitions, $uDiskSignature, @fields );
```
To delete a partition, zero out all fields except for `$bToRewrite` which should be set to `1`. To add a partition, increment `$cPartitions` and add the information for the new partition into the arrays, making sure that you insert `1` into @bToRewrite.
See `IOCTL_DISK_GET_DRIVE_LAYOUT` and `IOCTL_DISK_GET_PARITITON_INFORMATION` for descriptions of the fields.
`IOCTL_DISK_VERIFY` Performs a logical format of [part of] the disk. `$opOutBuf` should be `[]`. `$pInBuf` should contain a `VERIFY_INFORMATION` data structure:
```
$pInBuf= pack( "L l L",
$uStartOffsetLow, $ivStartOffsetHigh, $uLength );
```
`$uStartOffsetLow` and `$ivStartOffsetHigh`
The low-order and high-order [respectively] 4 bytes of the offset [in bytes] where the formatting should begin.
`$uLength`
The length [in bytes] of the section to be formatted.
`IOCTL_DISK_FORMAT_TRACKS` Format a range of tracks on the disk. `$opOutBuf` should be `[]`. `$pInBuf` should contain a `FORMAT_PARAMETERS` data structure:
```
$pInBuf= pack( "L L L L L", $uMediaType,
$uStartCyl, $uEndCyl, $uStartHead, $uEndHead );
```
`$uMediaType` if the type of media to be formatted. Mostly used to specify the density to use when formatting a floppy diskette. See the `":MEDIA_TYPE"` export class for more information.
The remaining fields specify the starting and ending cylinder and head of the range of tracks to be formatted.
`IOCTL_DISK_REASSIGN_BLOCKS` Reassign a list of disk blocks to the disk's spare-block pool. `$opOutBuf` should be `[]`. `$pInBuf` should be a `REASSIGN_BLOCKS` data structure:
```
$pInBuf= pack( "S S L*", 0, $cBlocks, @uBlockNumbers );
```
`IOCTL_DISK_PERFORMANCE` Request information about disk performance. `$pInBuf` should be `[]`. `$opOutBuf` will be set to contain a `DISK_PERFORMANCE` data structure:
```
my( $ucBytesReadLow, $ivcBytesReadHigh,
$ucBytesWrittenLow, $ivcBytesWrittenHigh,
$uReadTimeLow, $ivReadTimeHigh,
$uWriteTimeLow, $ivWriteTimeHigh,
$ucReads, $ucWrites, $uQueueDepth )=
unpack( "L l L l L l L l L L L", $opOutBuf );
```
`IOCTL_DISK_IS_WRITABLE` No documentation on this IOCTL operation was found.
`IOCTL_DISK_LOGGING` Control disk logging. Little documentation for this IOCTL operation was found. It makes use of a `DISK_LOGGING` data structure:
DISK\_LOGGING\_START Start logging each disk request in a buffer internal to the disk device driver of size `$uLogBufferSize`:
```
$pInBuf= pack( "C L L", 0, 0, $uLogBufferSize );
```
DISK\_LOGGING\_STOP Stop logging each disk request:
```
$pInBuf= pack( "C L L", 1, 0, 0 );
```
DISK\_LOGGING\_DUMP Copy the internal log into the supplied buffer:
```
$pLogBuffer= ' ' x $uLogBufferSize
$pInBuf= pack( "C P L", 2, $pLogBuffer, $uLogBufferSize );
( $uByteOffsetLow[$i], $ivByteOffsetHigh[$i],
$uStartTimeLow[$i], $ivStartTimeHigh[$i],
$uEndTimeLog[$i], $ivEndTimeHigh[$i],
$hVirtualAddress[$i], $ucBytes[$i],
$uDeviceNumber[$i], $bWasReading[$i] )=
unpack( "x".(8+8+8+4+4+1+1+2)." L l L l L l L L C c x2", $pLogBuffer );
```
DISK\_LOGGING\_BINNING Keep statics grouped into bins based on request sizes.
```
$pInBuf= pack( "C P L", 3, $pUnknown, $uUnknownSize );
```
`IOCTL_DISK_FORMAT_TRACKS_EX` No documentation on this IOCTL is included.
`IOCTL_DISK_HISTOGRAM_STRUCTURE` No documentation on this IOCTL is included.
`IOCTL_DISK_HISTOGRAM_DATA` No documentation on this IOCTL is included.
`IOCTL_DISK_HISTOGRAM_RESET` No documentation on this IOCTL is included.
`IOCTL_DISK_REQUEST_STRUCTURE` No documentation on this IOCTL operation was found.
`IOCTL_DISK_REQUEST_DATA` No documentation on this IOCTL operation was found.
`":FSCTL_"`
File system control operations. Used in the `$uIoControlCode` argument to `DeviceIoControl`.
Includes `FSCTL_SET_REPARSE_POINT`, `FSCTL_GET_REPARSE_POINT`, `FSCTL_DELETE_REPARSE_POINT`.
`FSCTL_SET_REPARSE_POINT` Sets reparse point data to be associated with $hDevice.
`FSCTL_GET_REPARSE_POINT` Retrieves the reparse point data associated with $hDevice.
`FSCTL_DELETE_REPARSE_POINT` Deletes the reparse point data associated with $hDevice.
`":GENERIC_"`
Constants specifying generic access permissions that are not specific to one type of object.
```
GENERIC_ALL GENERIC_EXECUTE
GENERIC_READ GENERIC_WRITE
```
`":MEDIA_TYPE"`
Different classes of media that a device can support. Used in the `$uMediaType` field of a `DISK_GEOMETRY` structure.
`Unknown` Format is unknown.
`F5_1Pt2_512` 5.25" floppy, 1.2MB [really 1,200KB] total space, 512 bytes/sector.
`F3_1Pt44_512` 3.5" floppy, 1.44MB [really 1,440KB] total space, 512 bytes/sector.
`F3_2Pt88_512` 3.5" floppy, 2.88MB [really 2,880KB] total space, 512 bytes/sector.
`F3_20Pt8_512` 3.5" floppy, 20.8MB total space, 512 bytes/sector.
`F3_720_512` 3.5" floppy, 720KB total space, 512 bytes/sector.
`F5_360_512` 5.25" floppy, 360KB total space, 512 bytes/sector.
`F5_320_512` 5.25" floppy, 320KB total space, 512 bytes/sector.
`F5_320_1024` 5.25" floppy, 320KB total space, 1024 bytes/sector.
`F5_180_512` 5.25" floppy, 180KB total space, 512 bytes/sector.
`F5_160_512` 5.25" floppy, 160KB total space, 512 bytes/sector.
`RemovableMedia` Some type of removable media other than a floppy diskette.
`FixedMedia` A fixed hard disk.
`F3_120M_512` 3.5" floppy, 120MB total space.
`":MOVEFILE_"`
Constants for use in `$uFlags` arguments to `MoveFileEx`.
```
MOVEFILE_COPY_ALLOWED MOVEFILE_DELAY_UNTIL_REBOOT
MOVEFILE_REPLACE_EXISTING MOVEFILE_WRITE_THROUGH
```
`":SECURITY_"`
Security quality of service values that can be used in the `$uFlags` argument to `CreateFile` if opening the client side of a named pipe.
```
SECURITY_ANONYMOUS SECURITY_CONTEXT_TRACKING
SECURITY_DELEGATION SECURITY_EFFECTIVE_ONLY
SECURITY_IDENTIFICATION SECURITY_IMPERSONATION
SECURITY_SQOS_PRESENT
```
`":SEM_"`
Constants to be used with `SetErrorMode`.
```
SEM_FAILCRITICALERRORS SEM_NOGPFAULTERRORBOX
SEM_NOALIGNMENTFAULTEXCEPT SEM_NOOPENFILEERRORBOX
```
`":PARTITION_"`
Constants describing partition types.
```
PARTITION_ENTRY_UNUSED PARTITION_FAT_12
PARTITION_XENIX_1 PARTITION_XENIX_2
PARTITION_FAT_16 PARTITION_EXTENDED
PARTITION_HUGE PARTITION_IFS
PARTITION_FAT32 PARTITION_FAT32_XINT13
PARTITION_XINT13 PARTITION_XINT13_EXTENDED
PARTITION_PREP PARTITION_UNIX
VALID_NTFT PARTITION_NTFT
```
`":STD_HANDLE_"`
Constants for GetStdHandle and SetStdHandle
```
STD_ERROR_HANDLE
STD_INPUT_HANDLE
STD_OUTPUT_HANDLE
```
`":ALL"`
All of the above.
BUGS
----
None known at this time.
AUTHOR
------
Tye McQueen, [email protected], http://perlmonks.org/?node=tye.
SEE ALSO
---------
The pyramids.
| programming_docs |
perl perltru64 perltru64
=========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Compiling Perl 5 on Tru64](#Compiling-Perl-5-on-Tru64)
+ [Using Large Files with Perl on Tru64](#Using-Large-Files-with-Perl-on-Tru64)
+ [Threaded Perl on Tru64](#Threaded-Perl-on-Tru64)
+ [Long Doubles on Tru64](#Long-Doubles-on-Tru64)
+ [DB\_File tests failing on Tru64](#DB_File-tests-failing-on-Tru64)
+ [64-bit Perl on Tru64](#64-bit-Perl-on-Tru64)
+ [Warnings about floating-point overflow when compiling Perl on Tru64](#Warnings-about-floating-point-overflow-when-compiling-Perl-on-Tru64)
* [Testing Perl on Tru64](#Testing-Perl-on-Tru64)
* [ext/ODBM\_File/odbm Test Failing With Static Builds](#ext/ODBM_File/odbm-Test-Failing-With-Static-Builds)
* [Perl Fails Because Of Unresolved Symbol sockatmark](#Perl-Fails-Because-Of-Unresolved-Symbol-sockatmark)
* [read\_cur\_obj\_info: bad file magic number](#read_cur_obj_info:-bad-file-magic-number)
* [AUTHOR](#AUTHOR)
NAME
----
perltru64 - Perl version 5 on Tru64 (formerly known as Digital UNIX formerly known as DEC OSF/1) systems
DESCRIPTION
-----------
This document describes various features of HP's (formerly Compaq's, formerly Digital's) Unix operating system (Tru64) that will affect how Perl version 5 (hereafter just Perl) is configured, compiled and/or runs.
###
Compiling Perl 5 on Tru64
The recommended compiler to use in Tru64 is the native C compiler. The native compiler produces much faster code (the speed difference is noticeable: several dozen percentages) and also more correct code: if you are considering using the GNU C compiler you should use at the very least the release of 2.95.3 since all older gcc releases are known to produce broken code when compiling Perl. One manifestation of this brokenness is the lib/sdbm test dumping core; another is many of the op/regexp and op/pat, or ext/Storable tests dumping core (the exact pattern of failures depending on the GCC release and optimization flags).
Both the native cc and gcc seem to consume lots of memory when building Perl. toke.c is a known trouble spot when optimizing: 256 megabytes of data section seems to be enough. Another known trouble spot is the mktables script which builds the Unicode support tables. The default setting of the process data section in Tru64 should be one gigabyte, but some sites/setups might have lowered that. The configuration process of Perl checks for too low process limits, and lowers the optimization for the toke.c if necessary, and also gives advice on how to raise the process limits (for example: `ulimit -d 262144`)
Also, Configure might abort with
```
Build a threading Perl? [n]
Configure[2437]: Syntax error at line 1 : 'config.sh' is not expected.
```
This indicates that Configure is being run with a broken Korn shell (even though you think you are using a Bourne shell by using "sh Configure" or "./Configure"). The Korn shell bug has been reported to Compaq as of February 1999 but in the meanwhile, the reason ksh is being used is that you have the environment variable BIN\_SH set to 'xpg4'. This causes /bin/sh to delegate its duties to /bin/posix/sh (a ksh). Unset the environment variable and rerun Configure.
###
Using Large Files with Perl on Tru64
In Tru64 Perl is automatically able to use large files, that is, files larger than 2 gigabytes, there is no need to use the Configure -Duselargefiles option as described in INSTALL (though using the option is harmless).
###
Threaded Perl on Tru64
If you want to use threads, you should primarily use the Perl 5.8.0 threads model by running Configure with -Duseithreads.
Perl threading is going to work only in Tru64 4.0 and newer releases, older operating releases like 3.2 aren't probably going to work properly with threads.
In Tru64 V5 (at least V5.1A, V5.1B) you cannot build threaded Perl with gcc because the system header <pthread.h> explicitly checks for supported C compilers, gcc (at least 3.2.2) not being one of them. But the system C compiler should work just fine.
###
Long Doubles on Tru64
You cannot Configure Perl to use long doubles unless you have at least Tru64 V5.0, the long double support simply wasn't functional enough before that. Perl's Configure will override attempts to use the long doubles (you can notice this by Configure finding out that the modfl() function does not work as it should).
At the time of this writing (June 2002), there is a known bug in the Tru64 libc printing of long doubles when not using "e" notation. The values are correct and usable, but you only get a limited number of digits displayed unless you force the issue by using `printf "%.33e",$num` or the like. For Tru64 versions V5.0A through V5.1A, a patch is expected sometime after perl 5.8.0 is released. If your libc has not yet been patched, you'll get a warning from Configure when selecting long doubles.
###
DB\_File tests failing on Tru64
The DB\_File tests (db-btree.t, db-hash.t, db-recno.t) may fail you have installed a newer version of Berkeley DB into the system and the -I and -L compiler and linker flags introduce version conflicts with the DB 1.85 headers and libraries that came with the Tru64. For example, mixing a DB v2 library with the DB v1 headers is a bad idea. Watch out for Configure options -Dlocincpth and -Dloclibpth, and check your /usr/local/include and /usr/local/lib since they are included by default.
The second option is to explicitly instruct Configure to detect the newer Berkeley DB installation, by supplying the right directories with `-Dlocincpth=/some/include` and `-Dloclibpth=/some/lib` **and** before running "make test" setting your LD\_LIBRARY\_PATH to */some/lib*.
The third option is to work around the problem by disabling the DB\_File completely when build Perl by specifying -Ui\_db to Configure, and then using the BerkeleyDB module from CPAN instead of DB\_File. The BerkeleyDB works with Berkeley DB versions 2.\* or greater.
The Berkeley DB 4.1.25 has been tested with Tru64 V5.1A and found to work. The latest Berkeley DB can be found from <http://www.sleepycat.com>.
###
64-bit Perl on Tru64
In Tru64 Perl's integers are automatically 64-bit wide, there is no need to use the Configure -Duse64bitint option as described in INSTALL. Similarly, there is no need for -Duse64bitall since pointers are automatically 64-bit wide.
###
Warnings about floating-point overflow when compiling Perl on Tru64
When compiling Perl in Tru64 you may (depending on the compiler release) see two warnings like this
```
cc: Warning: numeric.c, line 104: In this statement, floating-point
overflow occurs in evaluating the expression "1.8e308". (floatoverfl)
return HUGE_VAL;
-----------^
```
and when compiling the POSIX extension
```
cc: Warning: const-c.inc, line 2007: In this statement, floating-point
overflow occurs in evaluating the expression "1.8e308". (floatoverfl)
return HUGE_VAL;
-------------------^
```
The exact line numbers may vary between Perl releases. The warnings are benign and can be ignored: in later C compiler releases the warnings should be gone.
When the file *pp\_sys.c* is being compiled you may (depending on the operating system release) see an additional compiler flag being used: `-DNO_EFF_ONLY_OK`. This is normal and refers to a feature that is relevant only if you use the `filetest` pragma. In older releases of the operating system the feature was broken and the NO\_EFF\_ONLY\_OK instructs Perl not to use the feature.
Testing Perl on Tru64
----------------------
During "make test" the `comp`/`cpp` will be skipped because on Tru64 it cannot be tested before Perl has been installed. The test refers to the use of the `-P` option of Perl.
ext/ODBM\_File/odbm Test Failing With Static Builds
----------------------------------------------------
The ext/ODBM\_File/odbm is known to fail with static builds (Configure -Uusedl) due to a known bug in Tru64's static libdbm library. The good news is that you very probably don't need to ever use the ODBM\_File extension since more advanced NDBM\_File works fine, not to mention the even more advanced DB\_File.
Perl Fails Because Of Unresolved Symbol sockatmark
---------------------------------------------------
If you get an error like
```
Can't load '.../OSF1/lib/perl5/5.8.0/alpha-dec_osf/auto/IO/IO.so' for module IO: Unresolved symbol in .../lib/perl5/5.8.0/alpha-dec_osf/auto/IO/IO.so: sockatmark at .../lib/perl5/5.8.0/alpha-dec_osf/XSLoader.pm line 75.
```
you need to either recompile your Perl in Tru64 4.0D or upgrade your Tru64 4.0D to at least 4.0F: the sockatmark() system call was added in Tru64 4.0F, and the IO extension refers that symbol.
read\_cur\_obj\_info: bad file magic number
--------------------------------------------
You may be mixing the Tru64 cc/ar/ld with the GNU gcc/ar/ld. That may work, but sometimes it doesn't (your gcc or GNU utils may have been compiled for an incompatible OS release).
Try 'which ld' and 'which ld' (or try 'ar --version' and 'ld --version', which work only for the GNU tools, and will announce themselves to be such), and adjust your PATH so that you are consistently using either the native tools or the GNU tools. After fixing your PATH, you should do 'make distclean' and start all the way from running the Configure since you may have quite a confused situation.
AUTHOR
------
Jarkko Hietaniemi <[email protected]>
perl ExtUtils::Mksymlists ExtUtils::Mksymlists
====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
* [REVISION](#REVISION)
NAME
----
ExtUtils::Mksymlists - write linker options files for dynamic extension
SYNOPSIS
--------
```
use ExtUtils::Mksymlists;
Mksymlists( NAME => $name ,
DL_VARS => [ $var1, $var2, $var3 ],
DL_FUNCS => { $pkg1 => [ $func1, $func2 ],
$pkg2 => [ $func3 ] );
```
DESCRIPTION
-----------
`ExtUtils::Mksymlists` produces files used by the linker under some OSs during the creation of shared libraries for dynamic extensions. It is normally called from a MakeMaker-generated Makefile when the extension is built. The linker option file is generated by calling the function `Mksymlists`, which is exported by default from `ExtUtils::Mksymlists`. It takes one argument, a list of key-value pairs, in which the following keys are recognized:
DLBASE This item specifies the name by which the linker knows the extension, which may be different from the name of the extension itself (for instance, some linkers add an '\_' to the name of the extension). If it is not specified, it is derived from the NAME attribute. It is presently used only by OS2 and Win32.
DL\_FUNCS This is identical to the DL\_FUNCS attribute available via MakeMaker, from which it is usually taken. Its value is a reference to an associative array, in which each key is the name of a package, and each value is an a reference to an array of function names which should be exported by the extension. For instance, one might say `DL_FUNCS => { Homer::Iliad => [ qw(trojans greeks) ], Homer::Odyssey => [ qw(travellers family suitors) ] }`. The function names should be identical to those in the XSUB code; `Mksymlists` will alter the names written to the linker option file to match the changes made by *xsubpp*. In addition, if none of the functions in a list begin with the string **boot\_**, `Mksymlists` will add a bootstrap function for that package, just as xsubpp does. (If a **boot\_<pkg>** function is present in the list, it is passed through unchanged.) If DL\_FUNCS is not specified, it defaults to the bootstrap function for the extension specified in NAME.
DL\_VARS This is identical to the DL\_VARS attribute available via MakeMaker, and, like DL\_FUNCS, it is usually specified via MakeMaker. Its value is a reference to an array of variable names which should be exported by the extension.
FILE This key can be used to specify the name of the linker option file (minus the OS-specific extension), if for some reason you do not want to use the default value, which is the last word of the NAME attribute (*e.g.* for `Tk::Canvas`, FILE defaults to `Canvas`).
FUNCLIST This provides an alternate means to specify function names to be exported from the extension. Its value is a reference to an array of function names to be exported by the extension. These names are passed through unaltered to the linker options file. Specifying a value for the FUNCLIST attribute suppresses automatic generation of the bootstrap function for the package. To still create the bootstrap name you have to specify the package name in the DL\_FUNCS hash:
```
Mksymlists( NAME => $name ,
FUNCLIST => [ $func1, $func2 ],
DL_FUNCS => { $pkg => [] } );
```
IMPORTS This attribute is used to specify names to be imported into the extension. It is currently only used by OS/2 and Win32.
NAME This gives the name of the extension (*e.g.* `Tk::Canvas`) for which the linker option file will be produced.
When calling `Mksymlists`, one should always specify the NAME attribute. In most cases, this is all that's necessary. In the case of unusual extensions, however, the other attributes can be used to provide additional information to the linker.
AUTHOR
------
Charles Bailey *<[email protected]>*
REVISION
--------
Last revised 14-Feb-1996, for Perl 5.002.
perl Test::Simple Test::Simple
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [EXAMPLE](#EXAMPLE)
* [CAVEATS](#CAVEATS)
* [NOTES](#NOTES)
* [HISTORY](#HISTORY)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [MAINTAINERS](#MAINTAINERS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test::Simple - Basic utilities for writing tests.
SYNOPSIS
--------
```
use Test::Simple tests => 1;
ok( $foo eq $bar, 'foo is bar' );
```
DESCRIPTION
-----------
\*\* If you are unfamiliar with testing **read <Test::Tutorial> first!** \*\*
This is an extremely simple, extremely basic module for writing tests suitable for CPAN modules and other pursuits. If you wish to do more complicated testing, use the Test::More module (a drop-in replacement for this one).
The basic unit of Perl testing is the ok. For each thing you want to test your program will print out an "ok" or "not ok" to indicate pass or fail. You do this with the `ok()` function (see below).
The only other constraint is you must pre-declare how many tests you plan to run. This is in case something goes horribly wrong during the test and your test program aborts, or skips a test or whatever. You do this like so:
```
use Test::Simple tests => 23;
```
You must have a plan.
**ok**
```
ok( $foo eq $bar, $name );
ok( $foo eq $bar );
```
`ok()` is given an expression (in this case `$foo eq $bar`). If it's true, the test passed. If it's false, it didn't. That's about it.
`ok()` prints out either "ok" or "not ok" along with a test number (it keeps track of that for you).
```
# This produces "ok 1 - Hell not yet frozen over" (or not ok)
ok( get_temperature($hell) > 0, 'Hell not yet frozen over' );
```
If you provide a $name, that will be printed along with the "ok/not ok" to make it easier to find your test when if fails (just search for the name). It also makes it easier for the next guy to understand what your test is for. It's highly recommended you use test names.
All tests are run in scalar context. So this:
```
ok( @stuff, 'I have some stuff' );
```
will do what you mean (fail if stuff is empty)
Test::Simple will start by printing number of tests run in the form "1..M" (so "1..5" means you're going to run 5 tests). This strange format lets <Test::Harness> know how many tests you plan on running in case something goes horribly wrong.
If all your tests passed, Test::Simple will exit with zero (which is normal). If anything failed it will exit with how many failed. If you run less (or more) tests than you planned, the missing (or extras) will be considered failures. If no tests were ever run Test::Simple will throw a warning and exit with 255. If the test died, even after having successfully completed all its tests, it will still be considered a failure and will exit with 255.
So the exit codes are...
```
0 all tests successful
255 test died or all passed but wrong # of tests run
any other number how many failed (including missing or extras)
```
If you fail more than 254 tests, it will be reported as 254.
This module is by no means trying to be a complete testing system. It's just to get you started. Once you're off the ground its recommended you look at <Test::More>.
EXAMPLE
-------
Here's an example of a simple .t file for the fictional Film module.
```
use Test::Simple tests => 5;
use Film; # What you're testing.
my $btaste = Film->new({ Title => 'Bad Taste',
Director => 'Peter Jackson',
Rating => 'R',
NumExplodingSheep => 1
});
ok( defined($btaste) && ref $btaste eq 'Film', 'new() works' );
ok( $btaste->Title eq 'Bad Taste', 'Title() get' );
ok( $btaste->Director eq 'Peter Jackson', 'Director() get' );
ok( $btaste->Rating eq 'R', 'Rating() get' );
ok( $btaste->NumExplodingSheep == 1, 'NumExplodingSheep() get' );
```
It will produce output like this:
```
1..5
ok 1 - new() works
ok 2 - Title() get
ok 3 - Director() get
not ok 4 - Rating() get
# Failed test 'Rating() get'
# in t/film.t at line 14.
ok 5 - NumExplodingSheep() get
# Looks like you failed 1 tests of 5
```
Indicating the Film::Rating() method is broken.
CAVEATS
-------
Test::Simple will only report a maximum of 254 failures in its exit code. If this is a problem, you probably have a huge test script. Split it into multiple files. (Otherwise blame the Unix folks for using an unsigned short integer as the exit status).
Because VMS's exit codes are much, much different than the rest of the universe, and perl does horrible mangling to them that gets in my way, it works like this on VMS.
```
0 SS$_NORMAL all tests successful
4 SS$_ABORT something went wrong
```
Unfortunately, I can't differentiate any further.
NOTES
-----
Test::Simple is **explicitly** tested all the way back to perl 5.6.0.
Test::Simple is thread-safe in perl 5.8.1 and up.
HISTORY
-------
This module was conceived while talking with Tony Bowden in his kitchen one night about the problems I was having writing some really complicated feature into the new Testing module. He observed that the main problem is not dealing with these edge cases but that people hate to write tests **at all**. What was needed was a dead simple module that took all the hard work out of testing and was really, really easy to learn. Paul Johnson simultaneously had this idea (unfortunately, he wasn't in Tony's kitchen). This is it.
SEE ALSO
---------
<Test::More>
More testing functions! Once you outgrow Test::Simple, look at <Test::More>. Test::Simple is 100% forward compatible with <Test::More> (i.e. you can just use <Test::More> instead of Test::Simple in your programs and things will still work).
Look in <Test::More>'s SEE ALSO for more testing modules.
AUTHORS
-------
Idea by Tony Bowden and Paul Johnson, code by Michael G Schwern <[email protected]>, wardrobe by Calvin Klein.
MAINTAINERS
-----------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2001-2008 by Michael G Schwern <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://www.perl.com/perl/misc/Artistic.html*
perl Sys::Syslog::Win32 Sys::Syslog::Win32
==================
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHORS](#AUTHORS)
* [LICENSE](#LICENSE)
NAME
----
Sys::Syslog::Win32 - Win32 support for Sys::Syslog
DESCRIPTION
-----------
This module is a back-end plugin for `Sys::Syslog`, for supporting the Win32 event log. It is not expected to be directly used by any module other than `Sys::Syslog` therefore it's API may change at any time and no warranty is made with regards to backward compatibility. You Have Been Warned.
SEE ALSO
---------
<Sys::Syslog>
AUTHORS
-------
Sébastien Aperghis-Tramoni and Yves Orton
LICENSE
-------
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| programming_docs |
perl Term::Cap Term::Cap
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [METHODS](#METHODS)
* [EXAMPLES](#EXAMPLES)
* [COPYRIGHT AND LICENSE](#COPYRIGHT-AND-LICENSE)
* [AUTHOR](#AUTHOR)
* [SEE ALSO](#SEE-ALSO)
NAME
----
Term::Cap - Perl termcap interface
SYNOPSIS
--------
```
require Term::Cap;
$terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
$terminal->Trequire(qw/ce ku kd/);
$terminal->Tgoto('cm', $col, $row, $FH);
$terminal->Tputs('dl', $count, $FH);
$terminal->Tpad($string, $count, $FH);
```
DESCRIPTION
-----------
These are low-level functions to extract and use capabilities from a terminal capability (termcap) database.
More information on the terminal capabilities will be found in the termcap manpage on most Unix-like systems.
### METHODS
The output strings for **Tputs** are cached for counts of 1 for performance. **Tgoto** and **Tpad** do not cache. `$self->{_xx}` is the raw termcap data and `$self->{xx}` is the cached version.
```
print $terminal->Tpad($self->{_xx}, 1);
```
**Tgoto**, **Tputs**, and **Tpad** return the string and will also output the string to $FH if specified.
**Tgetent** Returns a blessed object reference which the user can then use to send the control strings to the terminal using **Tputs** and **Tgoto**.
The function extracts the entry of the specified terminal type *TERM* (defaults to the environment variable *TERM*) from the database.
It will look in the environment for a *TERMCAP* variable. If found, and the value does not begin with a slash, and the terminal type name is the same as the environment string *TERM*, the *TERMCAP* string is used instead of reading a termcap file. If it does begin with a slash, the string is used as a path name of the termcap file to search. If *TERMCAP* does not begin with a slash and name is different from *TERM*, **Tgetent** searches the files *$HOME/.termcap*, */etc/termcap*, and */usr/share/misc/termcap*, in that order, unless the environment variable *TERMPATH* exists, in which case it specifies a list of file pathnames (separated by spaces or colons) to be searched **instead**. Whenever multiple files are searched and a tc field occurs in the requested entry, the entry it names must be found in the same file or one of the succeeding files. If there is a `:tc=...:` in the *TERMCAP* environment variable string it will continue the search in the files as above.
The extracted termcap entry is available in the object as `$self->{TERMCAP}`.
It takes a hash reference as an argument with two optional keys:
OSPEED The terminal output bit rate (often mistakenly called the baud rate) for this terminal - if not set a warning will be generated and it will be defaulted to 9600. *OSPEED* can be specified as either a POSIX termios/SYSV termio speeds (where 9600 equals 9600) or an old DSD-style speed ( where 13 equals 9600).
TERM The terminal type whose termcap entry will be used - if not supplied it will default to $ENV{TERM}: if that is not set then **Tgetent** will croak.
It calls `croak` on failure.
**Tpad** Outputs a literal string with appropriate padding for the current terminal.
It takes three arguments:
**$string**
The literal string to be output. If it starts with a number and an optional '\*' then the padding will be increased by an amount relative to this number, if the '\*' is present then this amount will be multiplied by $cnt. This part of $string is removed before output/
**$cnt**
Will be used to modify the padding applied to string as described above.
**$FH**
An optional filehandle (or IO::Handle ) that output will be printed to.
The padded $string is returned.
**Tputs** Output the string for the given capability padded as appropriate without any parameter substitution.
It takes three arguments:
**$cap**
The capability whose string is to be output.
**$cnt**
A count passed to Tpad to modify the padding applied to the output string. If $cnt is zero or one then the resulting string will be cached.
**$FH**
An optional filehandle (or IO::Handle ) that output will be printed to.
The appropriate string for the capability will be returned.
**Tgoto** **Tgoto** decodes a cursor addressing string with the given parameters.
There are four arguments:
**$cap**
The name of the capability to be output.
**$col**
The first value to be substituted in the output string ( usually the column in a cursor addressing capability )
**$row**
The second value to be substituted in the output string (usually the row in cursor addressing capabilities)
**$FH**
An optional filehandle (or IO::Handle ) to which the output string will be printed.
Substitutions are made with $col and $row in the output string with the following sprintf() line formats:
```
%% output `%'
%d output value as in printf %d
%2 output value as in printf %2d
%3 output value as in printf %3d
%. output value as in printf %c
%+x add x to value, then do %.
%>xy if value > x then add y, no output
%r reverse order of two parameters, no output
%i increment by one, no output
%B BCD (16*(value/10)) + (value%10), no output
%n exclusive-or all parameters with 0140 (Datamedia 2500)
%D Reverse coding (value - 2*(value%16)), no output (Delta Data)
```
The output string will be returned.
**Trequire** Takes a list of capabilities as an argument and will croak if one is not found.
EXAMPLES
--------
```
use Term::Cap;
# Get terminal output speed
require POSIX;
my $termios = new POSIX::Termios;
$termios->getattr;
my $ospeed = $termios->getospeed;
# Old-style ioctl code to get ospeed:
# require 'ioctl.pl';
# ioctl(TTY,$TIOCGETP,$sgtty);
# ($ispeed,$ospeed) = unpack('cc',$sgtty);
# allocate and initialize a terminal structure
$terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
# require certain capabilities to be available
$terminal->Trequire(qw/ce ku kd/);
# Output Routines, if $FH is undefined these just return the string
# Tgoto does the % expansion stuff with the given args
$terminal->Tgoto('cm', $col, $row, $FH);
# Tputs doesn't do any % expansion.
$terminal->Tputs('dl', $count = 1, $FH);
```
COPYRIGHT AND LICENSE
----------------------
Copyright 1995-2015 (c) perl5 porters.
This software is free software and can be modified and distributed under the same terms as Perl itself.
Please see the file README in the Perl source distribution for details of the Perl license.
AUTHOR
------
This module is part of the core Perl distribution and is also maintained for CPAN by Jonathan Stowe <[email protected]>.
The code is hosted on Github: https://github.com/jonathanstowe/Term-Cap please feel free to fork, submit patches etc, etc there.
SEE ALSO
---------
termcap(5)
perl DBM_Filter::compress DBM\_Filter::compress
=====================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [AUTHOR](#AUTHOR)
NAME
----
DBM\_Filter::compress - filter for DBM\_Filter
SYNOPSIS
--------
```
use SDBM_File; # or DB_File, GDBM_File, NDBM_File, ODBM_File
use DBM_Filter ;
$db = tie %hash, ...
$db->Filter_Push('compress');
```
DESCRIPTION
-----------
This DBM filter will compress all data before it is written to the database and uncompressed it on reading.
A fatal error will be thrown if the Compress::Zlib module is not available.
SEE ALSO
---------
[DBM\_Filter](dbm_filter), <perldbmfilter>, <Compress::Zlib>
AUTHOR
------
Paul Marquess [email protected]
perl overloading overloading
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
overloading - perl pragma to lexically control overloading
SYNOPSIS
--------
```
{
no overloading;
my $str = "$object"; # doesn't call stringification overload
}
# it's lexical, so this stringifies:
warn "$object";
# it can be enabled per op
no overloading qw("");
warn "$object";
# and also reenabled
use overloading;
```
DESCRIPTION
-----------
This pragma allows you to lexically disable or enable overloading.
`no overloading`
Disables overloading entirely in the current lexical scope.
`no overloading @ops`
Disables only specific overloads in the current lexical scope.
`use overloading`
Reenables overloading in the current lexical scope.
`use overloading @ops`
Reenables overloading only for specific ops in the current lexical scope.
perl utf8 utf8
====
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Utility functions](#Utility-functions)
* [BUGS](#BUGS)
* [SEE ALSO](#SEE-ALSO)
NAME
----
utf8 - Perl pragma to enable/disable UTF-8 (or UTF-EBCDIC) in source code
SYNOPSIS
--------
```
use utf8;
no utf8;
# Convert the internal representation of a Perl scalar to/from UTF-8.
$num_octets = utf8::upgrade($string);
$success = utf8::downgrade($string[, $fail_ok]);
# Change each character of a Perl scalar to/from a series of
# characters that represent the UTF-8 bytes of each original character.
utf8::encode($string); # "\x{100}" becomes "\xc4\x80"
utf8::decode($string); # "\xc4\x80" becomes "\x{100}"
# Convert a code point from the platform native character set to
# Unicode, and vice-versa.
$unicode = utf8::native_to_unicode(ord('A')); # returns 65 on both
# ASCII and EBCDIC
# platforms
$native = utf8::unicode_to_native(65); # returns 65 on ASCII
# platforms; 193 on
# EBCDIC
$flag = utf8::is_utf8($string); # since Perl 5.8.1
$flag = utf8::valid($string);
```
DESCRIPTION
-----------
The `use utf8` pragma tells the Perl parser to allow UTF-8 in the program text in the current lexical scope. The `no utf8` pragma tells Perl to switch back to treating the source text as literal bytes in the current lexical scope. (On EBCDIC platforms, technically it is allowing UTF-EBCDIC, and not UTF-8, but this distinction is academic, so in this document the term UTF-8 is used to mean both).
**Do not use this pragma for anything else than telling Perl that your script is written in UTF-8.** The utility functions described below are directly usable without `use utf8;`.
Because it is not possible to reliably tell UTF-8 from native 8 bit encodings, you need either a Byte Order Mark at the beginning of your source code, or `use utf8;`, to instruct perl.
When UTF-8 becomes the standard source format, this pragma will effectively become a no-op.
See also the effects of the `-C` switch and its cousin, the `PERL_UNICODE` environment variable, in <perlrun>.
Enabling the `utf8` pragma has the following effect:
* Bytes in the source text that are not in the ASCII character set will be treated as being part of a literal UTF-8 sequence. This includes most literals such as identifier names, string constants, and constant regular expression patterns.
Note that if you have non-ASCII, non-UTF-8 bytes in your script (for example embedded Latin-1 in your string literals), `use utf8` will be unhappy. If you want to have such bytes under `use utf8`, you can disable this pragma until the end the block (or file, if at top level) by `no utf8;`.
###
Utility functions
The following functions are defined in the `utf8::` package by the Perl core. You do not need to say `use utf8` to use these and in fact you should not say that unless you really want to have UTF-8 source code.
* `$num_octets = utf8::upgrade($string)`
(Since Perl v5.8.0) Converts in-place the internal representation of the string from an octet sequence in the native encoding (Latin-1 or EBCDIC) to UTF-8. The logical character sequence itself is unchanged. If *$string* is already upgraded, then this is a no-op. Returns the number of octets necessary to represent the string as UTF-8.
If your code needs to be compatible with versions of perl without `use feature 'unicode_strings';`, you can force Unicode semantics on a given string:
```
# force unicode semantics for $string without the
# "unicode_strings" feature
utf8::upgrade($string);
```
For example:
```
# without explicit or implicit use feature 'unicode_strings'
my $x = "\xDF"; # LATIN SMALL LETTER SHARP S
$x =~ /ss/i; # won't match
my $y = uc($x); # won't convert
utf8::upgrade($x);
$x =~ /ss/i; # matches
my $z = uc($x); # converts to "SS"
```
**Note that this function does not handle arbitrary encodings**; use [Encode](encode) instead.
* `$success = utf8::downgrade($string[, $fail_ok])`
(Since Perl v5.8.0) Converts in-place the internal representation of the string from UTF-8 to the equivalent octet sequence in the native encoding (Latin-1 or EBCDIC). The logical character sequence itself is unchanged. If *$string* is already stored as native 8 bit, then this is a no-op. Can be used to make sure that the UTF-8 flag is off, e.g. when you want to make sure that the substr() or length() function works with the usually faster byte algorithm.
Fails if the original UTF-8 sequence cannot be represented in the native 8 bit encoding. On failure dies or, if the value of *$fail\_ok* is true, returns false.
Returns true on success.
If your code expects an octet sequence this can be used to validate that you've received one:
```
# throw an exception if not representable as octets
utf8::downgrade($string)
# or do your own error handling
utf8::downgrade($string, 1) or die "string must be octets";
```
**Note that this function does not handle arbitrary encodings**; use [Encode](encode) instead.
* `utf8::encode($string)`
(Since Perl v5.8.0) Converts in-place the character sequence to the corresponding octet sequence in Perl's extended UTF-8. That is, every (possibly wide) character gets replaced with a sequence of one or more characters that represent the individual UTF-8 bytes of the character. The UTF8 flag is turned off. Returns nothing.
```
my $x = "\x{100}"; # $x contains one character, with ord 0x100
utf8::encode($x); # $x contains two characters, with ords (on
# ASCII platforms) 0xc4 and 0x80. On EBCDIC
# 1047, this would instead be 0x8C and 0x41.
```
Similar to:
```
use Encode;
$x = Encode::encode("utf8", $x);
```
**Note that this function does not handle arbitrary encodings**; use [Encode](encode) instead.
* `$success = utf8::decode($string)`
(Since Perl v5.8.0) Attempts to convert in-place the octet sequence encoded in Perl's extended UTF-8 to the corresponding character sequence. That is, it replaces each sequence of characters in the string whose ords represent a valid (extended) UTF-8 byte sequence, with the corresponding single character. The UTF-8 flag is turned on only if the source string contains multiple-byte UTF-8 characters. If *$string* is invalid as extended UTF-8, returns false; otherwise returns true.
```
my $x = "\xc4\x80"; # $x contains two characters, with ords
# 0xc4 and 0x80
utf8::decode($x); # On ASCII platforms, $x contains one char,
# with ord 0x100. Since these bytes aren't
# legal UTF-EBCDIC, on EBCDIC platforms, $x is
# unchanged and the function returns FALSE.
my $y = "\xc3\x83\xc2\xab"; This has been encoded twice; this
# example is only for ASCII platforms
utf8::decode($y); # Converts $y to \xc3\xab, returns TRUE;
utf8::decode($y); # Further converts to \xeb, returns TRUE;
utf8::decode($y); # Returns FALSE, leaves $y unchanged
```
**Note that this function does not handle arbitrary encodings**; use [Encode](encode) instead.
* `$unicode = utf8::native_to_unicode($code_point)`
(Since Perl v5.8.0) This takes an unsigned integer (which represents the ordinal number of a character (or a code point) on the platform the program is being run on) and returns its Unicode equivalent value. Since ASCII platforms natively use the Unicode code points, this function returns its input on them. On EBCDIC platforms it converts from EBCDIC to Unicode.
A meaningless value will currently be returned if the input is not an unsigned integer.
Since Perl v5.22.0, calls to this function are optimized out on ASCII platforms, so there is no performance hit in using it there.
* `$native = utf8::unicode_to_native($code_point)`
(Since Perl v5.8.0) This is the inverse of `utf8::native_to_unicode()`, converting the other direction. Again, on ASCII platforms, this returns its input, but on EBCDIC platforms it will find the native platform code point, given any Unicode one.
A meaningless value will currently be returned if the input is not an unsigned integer.
Since Perl v5.22.0, calls to this function are optimized out on ASCII platforms, so there is no performance hit in using it there.
* `$flag = utf8::is_utf8($string)`
(Since Perl 5.8.1) Test whether *$string* is marked internally as encoded in UTF-8. Functionally the same as `Encode::is_utf8($string)`.
Typically only necessary for debugging and testing, if you need to dump the internals of an SV, [Devel::Peek's](Devel::Peek) Dump() provides more detail in a compact form.
If you still think you need this outside of debugging, testing or dealing with filenames, you should probably read <perlunitut> and ["What is "the UTF8 flag"?" in perlunifaq](perlunifaq#What-is-%22the-UTF8-flag%22%3F).
Don't use this flag as a marker to distinguish character and binary data: that should be decided for each variable when you write your code.
To force unicode semantics in code portable to perl 5.8 and 5.10, call `utf8::upgrade($string)` unconditionally.
* `$flag = utf8::valid($string)`
[INTERNAL] Test whether *$string* is in a consistent state regarding UTF-8. Will return true if it is well-formed Perl extended UTF-8 and has the UTF-8 flag on **or** if *$string* is held as bytes (both these states are 'consistent'). The main reason for this routine is to allow Perl's test suite to check that operations have left strings in a consistent state.
`utf8::encode` is like `utf8::upgrade`, but the UTF8 flag is cleared. See <perlunicode>, and the C API functions `[sv\_utf8\_upgrade](perlapi#sv_utf8_upgrade)`, `["sv\_utf8\_downgrade" in perlapi](perlapi#sv_utf8_downgrade)`, `["sv\_utf8\_encode" in perlapi](perlapi#sv_utf8_encode)`, and `["sv\_utf8\_decode" in perlapi](perlapi#sv_utf8_decode)`, which are wrapped by the Perl functions `utf8::upgrade`, `utf8::downgrade`, `utf8::encode` and `utf8::decode`. Also, the functions `utf8::is_utf8`, `utf8::valid`, `utf8::encode`, `utf8::decode`, `utf8::upgrade`, and `utf8::downgrade` are actually internal, and thus always available, without a `require utf8` statement.
BUGS
----
Some filesystems may not support UTF-8 file names, or they may be supported incompatibly with Perl. Therefore UTF-8 names that are visible to the filesystem, such as module names may not work.
SEE ALSO
---------
<perlunitut>, <perluniintro>, <perlrun>, <bytes>, <perlunicode>
perl Module::Loaded Module::Loaded
==============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [$bool = mark\_as\_loaded( PACKAGE );](#%24bool-=-mark_as_loaded(-PACKAGE-);)
+ [$bool = mark\_as\_unloaded( PACKAGE );](#%24bool-=-mark_as_unloaded(-PACKAGE-);)
+ [$loc = is\_loaded( PACKAGE );](#%24loc-=-is_loaded(-PACKAGE-);)
* [BUG REPORTS](#BUG-REPORTS)
* [AUTHOR](#AUTHOR)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Module::Loaded - mark modules as loaded or unloaded
SYNOPSIS
--------
```
use Module::Loaded;
$bool = mark_as_loaded('Foo'); # Foo.pm is now marked as loaded
$loc = is_loaded('Foo'); # location of Foo.pm set to the
# loaders location
eval "require 'Foo'"; # is now a no-op
$bool = mark_as_unloaded('Foo'); # Foo.pm no longer marked as loaded
eval "require 'Foo'"; # Will try to find Foo.pm in @INC
```
DESCRIPTION
-----------
When testing applications, often you find yourself needing to provide functionality in your test environment that would usually be provided by external modules. Rather than munging the `%INC` by hand to mark these external modules as loaded, so they are not attempted to be loaded by perl, this module offers you a very simple way to mark modules as loaded and/or unloaded.
FUNCTIONS
---------
###
$bool = mark\_as\_loaded( PACKAGE );
Marks the package as loaded to perl. `PACKAGE` can be a bareword or string.
If the module is already loaded, `mark_as_loaded` will carp about this and tell you from where the `PACKAGE` has been loaded already.
###
$bool = mark\_as\_unloaded( PACKAGE );
Marks the package as unloaded to perl, which is the exact opposite of `mark_as_loaded`. `PACKAGE` can be a bareword or string.
If the module is already unloaded, `mark_as_unloaded` will carp about this and tell you the `PACKAGE` has been unloaded already.
###
$loc = is\_loaded( PACKAGE );
`is_loaded` tells you if `PACKAGE` has been marked as loaded yet. `PACKAGE` can be a bareword or string.
It returns falls if `PACKAGE` has not been loaded yet and the location from where it is said to be loaded on success.
BUG REPORTS
------------
Please report bugs or other issues to <[email protected]<gt>.
AUTHOR
------
This module by Jos Boumans <[email protected]>.
COPYRIGHT
---------
This library is free software; you may redistribute and/or modify it under the same terms as Perl itself.
| programming_docs |
perl UNIVERSAL UNIVERSAL
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [WARNINGS](#WARNINGS)
* [EXPORTS](#EXPORTS)
NAME
----
UNIVERSAL - base class for ALL classes (blessed references)
SYNOPSIS
--------
```
$is_io = $fd->isa("IO::Handle");
$is_io = Class->isa("IO::Handle");
$does_log = $obj->DOES("Logger");
$does_log = Class->DOES("Logger");
$sub = $obj->can("print");
$sub = Class->can("print");
$sub = eval { $ref->can("fandango") };
$ver = $obj->VERSION;
# but never do this!
$is_io = UNIVERSAL::isa($fd, "IO::Handle");
$sub = UNIVERSAL::can($obj, "print");
```
DESCRIPTION
-----------
`UNIVERSAL` is the base class from which all blessed references inherit. See <perlobj>.
`UNIVERSAL` provides the following methods:
`$obj->isa( TYPE )`
`CLASS->isa( TYPE )`
`eval { VAL->isa( TYPE ) }`
Where
`TYPE` is a package name
`$obj`
is a blessed reference or a package name
`CLASS` is a package name
`VAL` is any of the above or an unblessed reference
When used as an instance or class method (`$obj->isa( TYPE )`), `isa` returns *true* if $obj is blessed into package `TYPE` or inherits from package `TYPE`.
When used as a class method (`CLASS->isa( TYPE )`, sometimes referred to as a static method), `isa` returns *true* if `CLASS` inherits from (or is itself) the name of the package `TYPE` or inherits from package `TYPE`.
If you're not sure what you have (the `VAL` case), wrap the method call in an `eval` block to catch the exception if `VAL` is undefined or an unblessed reference. The [`isa` operator](perlop#Class-Instance-Operator) is an alternative that simply returns false in this case, so the `eval` is not needed.
If you want to be sure that you're calling `isa` as a method, not a class, check the invocand with `blessed` from <Scalar::Util> first:
```
use Scalar::Util 'blessed';
if ( blessed( $obj ) && $obj->isa("Some::Class") ) {
...
}
```
`$obj->DOES( ROLE )`
`CLASS->DOES( ROLE )`
`DOES` checks if the object or class performs the role `ROLE`. A role is a named group of specific behavior (often methods of particular names and signatures), similar to a class, but not necessarily a complete class by itself. For example, logging or serialization may be roles.
`DOES` and `isa` are similar, in that if either is true, you know that the object or class on which you call the method can perform specific behavior. However, `DOES` is different from `isa` in that it does not care *how* the invocand performs the operations, merely that it does. (`isa` of course mandates an inheritance relationship. Other relationships include aggregation, delegation, and mocking.)
By default, classes in Perl only perform the `UNIVERSAL` role, as well as the role of all classes in their inheritance. In other words, by default `DOES` responds identically to `isa`.
There is a relationship between roles and classes, as each class implies the existence of a role of the same name. There is also a relationship between inheritance and roles, in that a subclass that inherits from an ancestor class implicitly performs any roles its parent performs. Thus you can use `DOES` in place of `isa` safely, as it will return true in all places where `isa` will return true (provided that any overridden `DOES` *and* `isa` methods behave appropriately).
`$obj->can( METHOD )`
`CLASS->can( METHOD )`
`eval { VAL->can( METHOD ) }`
`can` checks if the object or class has a method called `METHOD`. If it does, then it returns a reference to the sub. If it does not, then it returns *undef*. This includes methods inherited or imported by `$obj`, `CLASS`, or `VAL`.
`can` cannot know whether an object will be able to provide a method through AUTOLOAD (unless the object's class has overridden `can` appropriately), so a return value of *undef* does not necessarily mean the object will not be able to handle the method call. To get around this some module authors use a forward declaration (see <perlsub>) for methods they will handle via AUTOLOAD. For such 'dummy' subs, `can` will still return a code reference, which, when called, will fall through to the AUTOLOAD. If no suitable AUTOLOAD is provided, calling the coderef will cause an error.
You may call `can` as a class (static) method or an object method.
Again, the same rule about having a valid invocand applies -- use an `eval` block or `blessed` if you need to be extra paranoid.
`VERSION ( [ REQUIRE ] )`
`VERSION` will return the value of the variable `$VERSION` in the package the object is blessed into. If `REQUIRE` is given then it will do a comparison and die if the package version is not greater than or equal to `REQUIRE`, or if either `$VERSION` or `REQUIRE` is not a "lax" version number (as defined by the <version> module).
The return from `VERSION` will actually be the stringified version object using the package `$VERSION` scalar, which is guaranteed to be equivalent but may not be precisely the contents of the `$VERSION` scalar. If you want the actual contents of `$VERSION`, use `$CLASS::VERSION` instead.
`VERSION` can be called as either a class (static) method or an object method.
WARNINGS
--------
**NOTE:** `can` directly uses Perl's internal code for method lookup, and `isa` uses a very similar method and cache-ing strategy. This may cause strange effects if the Perl code dynamically changes @ISA in any package.
You may add other methods to the UNIVERSAL class via Perl or XS code. You do not need to `use UNIVERSAL` to make these methods available to your program (and you should not do so).
EXPORTS
-------
None.
Previous versions of this documentation suggested using `isa` as a function to determine the type of a reference:
```
$yes = UNIVERSAL::isa($h, "HASH");
$yes = UNIVERSAL::isa("Foo", "Bar");
```
The problem is that this code would *never* call an overridden `isa` method in any class. Instead, use `reftype` from <Scalar::Util> for the first case:
```
use Scalar::Util 'reftype';
$yes = reftype( $h ) eq "HASH";
```
and the method form of `isa` for the second:
```
$yes = Foo->isa("Bar");
```
perl Config::Extensions Config::Extensions
==================
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [AUTHOR](#AUTHOR)
NAME
----
Config::Extensions - hash lookup of which core extensions were built.
SYNOPSIS
--------
```
use Config::Extensions '%Extensions';
if ($Extensions{PerlIO::via}) {
# This perl has PerlIO::via built
}
```
DESCRIPTION
-----------
The Config::Extensions module provides a hash `%Extensions` containing all the core extensions that were enabled for this perl. The hash is keyed by extension name, with each entry having one of 3 possible values:
dynamic The extension is dynamically linked
nonxs The extension is pure perl, so doesn't need linking to the perl executable
static The extension is statically linked to the perl binary
As all values evaluate to true, a simple `if` test is good enough to determine whether an extension is present.
All the data uses to generate the `%Extensions` hash is already present in the `Config` module, but not in such a convenient format to quickly reference.
AUTHOR
------
Nicholas Clark <[email protected]>
perl TAP::Formatter::File TAP::Formatter::File
====================
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
* [SYNOPSIS](#SYNOPSIS)
+ [open\_test](#open_test)
NAME
----
TAP::Formatter::File - Harness output delegate for file output
VERSION
-------
Version 3.44
DESCRIPTION
-----------
This provides file orientated output formatting for TAP::Harness.
SYNOPSIS
--------
```
use TAP::Formatter::File;
my $harness = TAP::Formatter::File->new( \%args );
```
### `open_test`
See <TAP::Formatter::Base>
perl Pod::Perldoc Pod::Perldoc
============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [SEE ALSO](#SEE-ALSO)
* [COPYRIGHT AND DISCLAIMERS](#COPYRIGHT-AND-DISCLAIMERS)
* [AUTHOR](#AUTHOR)
NAME
----
Pod::Perldoc - Look up Perl documentation in Pod format.
SYNOPSIS
--------
```
use Pod::Perldoc ();
Pod::Perldoc->run();
```
DESCRIPTION
-----------
The guts of <perldoc> utility.
SEE ALSO
---------
<perldoc>
COPYRIGHT AND DISCLAIMERS
--------------------------
Copyright (c) 2002-2007 Sean M. Burke.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
AUTHOR
------
Current maintainer: Mark Allen `<[email protected]>`
Past contributions from: brian d foy `<[email protected]>` Adriano R. Ferreira `<[email protected]>`, Sean M. Burke `<[email protected]>`
perl I18N::Collate I18N::Collate
=============
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
NAME
----
I18N::Collate - compare 8-bit scalar data according to the current locale
SYNOPSIS
--------
```
use I18N::Collate;
setlocale(LC_COLLATE, 'locale-of-your-choice');
$s1 = I18N::Collate->new("scalar_data_1");
$s2 = I18N::Collate->new("scalar_data_2");
```
DESCRIPTION
-----------
```
***
WARNING: starting from the Perl version 5.003_06
the I18N::Collate interface for comparing 8-bit scalar data
according to the current locale
HAS BEEN DEPRECATED
That is, please do not use it anymore for any new applications
and please migrate the old applications away from it because its
functionality was integrated into the Perl core language in the
release 5.003_06.
See the perllocale manual page for further information.
***
```
This module provides you with objects that will collate according to your national character set, provided that the POSIX setlocale() function is supported on your system.
You can compare $s1 and $s2 above with
```
$s1 le $s2
```
to extract the data itself, you'll need a dereference: $$s1
This module uses POSIX::setlocale(). The basic collation conversion is done by strxfrm() which terminates at NUL characters being a decent C routine. collate\_xfrm() handles embedded NUL characters gracefully.
The available locales depend on your operating system; try whether `locale -a` shows them or man pages for "locale" or "nlsinfo" or the direct approach `ls /usr/lib/nls/loc` or `ls /usr/lib/nls` or `ls /usr/lib/locale`. Not all the locales that your vendor supports are necessarily installed: please consult your operating system's documentation and possibly your local system administration. The locale names are probably something like `xx_XX.(ISO)?8859-N` or `xx_XX.(ISO)?8859N`, for example `fr_CH.ISO8859-1` is the Swiss (CH) variant of French (fr), ISO Latin (8859) 1 (-1) which is the Western European character set.
perl perlfaq1 perlfaq1
========
CONTENTS
--------
* [NAME](#NAME)
* [VERSION](#VERSION)
* [DESCRIPTION](#DESCRIPTION)
+ [What is Perl?](#What-is-Perl?)
+ [Who supports Perl? Who develops it? Why is it free?](#Who-supports-Perl?-Who-develops-it?-Why-is-it-free?)
+ [Which version of Perl should I use?](#Which-version-of-Perl-should-I-use?)
+ [What are Perl 4, Perl 5, or Raku (Perl 6)?](#What-are-Perl-4,-Perl-5,-or-Raku-(Perl-6)?)
+ [What is Raku (Perl 6)?](#What-is-Raku-(Perl-6)?)
+ [How stable is Perl?](#How-stable-is-Perl?)
+ [How often are new versions of Perl released?](#How-often-are-new-versions-of-Perl-released?)
+ [Is Perl difficult to learn?](#Is-Perl-difficult-to-learn?)
+ [How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?](#How-does-Perl-compare-with-other-languages-like-Java,-Python,-REXX,-Scheme,-or-Tcl?)
+ [Can I do [task] in Perl?](#Can-I-do-%5Btask%5D-in-Perl?)
+ [When shouldn't I program in Perl?](#When-shouldn't-I-program-in-Perl?)
+ [What's the difference between "perl" and "Perl"?](#What's-the-difference-between-%22perl%22-and-%22Perl%22?)
+ [What is a JAPH?](#What-is-a-JAPH?)
+ [How can I convince others to use Perl?](#How-can-I-convince-others-to-use-Perl?)
* [AUTHOR AND COPYRIGHT](#AUTHOR-AND-COPYRIGHT)
NAME
----
perlfaq1 - General Questions About Perl
VERSION
-------
version 5.20210520
DESCRIPTION
-----------
This section of the FAQ answers very general, high-level questions about Perl.
###
What is Perl?
Perl is a high-level programming language with an eclectic heritage written by Larry Wall and a cast of thousands.
Perl's process, file, and text manipulation facilities make it particularly well-suited for tasks involving quick prototyping, system utilities, software tools, system management tasks, database access, graphical programming, networking, and web programming.
Perl derives from the ubiquitous C programming language and to a lesser extent from sed, awk, the Unix shell, and many other tools and languages.
These strengths make it especially popular with web developers and system administrators. Mathematicians, geneticists, journalists, managers and many other people also use Perl.
###
Who supports Perl? Who develops it? Why is it free?
The original culture of the pre-populist Internet and the deeply-held beliefs of Perl's author, Larry Wall, gave rise to the free and open distribution policy of Perl. Perl is supported by its users. The core, the standard Perl library, the optional modules, and the documentation you're reading now were all written by volunteers.
The core development team (known as the Perl Porters) are a group of highly altruistic individuals committed to producing better software for free than you could hope to purchase for money. You may snoop on pending developments via the [archives](http://www.nntp.perl.org/group/perl.perl5.porters/) or you can subscribe to the mailing list by sending [email protected] a subscription request (an empty message with no subject is fine).
While the GNU project includes Perl in its distributions, there's no such thing as "GNU Perl". Perl is not produced nor maintained by the Free Software Foundation. Perl's licensing terms are also more open than GNU software's tend to be.
You can get commercial support of Perl if you wish, although for most users the informal support will more than suffice. See the answer to "Where can I buy a commercial version of Perl?" for more information.
###
Which version of Perl should I use?
(contributed by brian d foy with updates from others)
There is often a matter of opinion and taste, and there isn't any one answer that fits everyone. In general, you want to use either the current stable release, or the stable release immediately prior to that one.
Beyond that, you have to consider several things and decide which is best for you.
* If things aren't broken, upgrading perl may break them (or at least issue new warnings).
* The latest versions of perl have more bug fixes.
* The latest versions of perl may contain performance improvements and features not present in older versions. There have been many changes in perl since perl5 was first introduced.
* The Perl community is geared toward supporting the most recent releases, so you'll have an easier time finding help for those.
* Older versions of perl may have security vulnerabilities, some of which are serious (see <perlsec> and search [CVEs](https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=Perl) for more information).
* The latest versions are probably the least deployed and widely tested, so you may want to wait a few months after their release and see what problems others have if you are risk averse.
* The immediate, in addition to the current stable release, the previous stable release is maintained. See ["MAINTENANCE AND SUPPORT" in perlpolicy](perlpolicy#MAINTENANCE-AND-SUPPORT) for more information.
* There are really two tracks of perl development: a maintenance version and an experimental version. The maintenance versions are stable, and have an even number as the minor release (i.e. perl5.24.x, where 24 is the minor release). The experimental versions may include features that don't make it into the stable versions, and have an odd number as the minor release (i.e. perl5.25.x, where 25 is the minor release).
* You can consult [releases](http://dev.perl.org/perl5) to determine the current stable release of Perl.
###
What are Perl 4, Perl 5, or Raku (Perl 6)?
In short, Perl 4 is the parent to both Perl 5 and Raku (formerly known as Perl 6). Perl 5 is the older sibling, and though they are different languages, someone who knows one will spot many similarities in the other.
The number after Perl (i.e. the 5 after Perl 5) is the major release of the perl interpreter as well as the version of the language. Each major version has significant differences that earlier versions cannot support.
The current major release of Perl is Perl 5, first released in 1994. It can run scripts from the previous major release, Perl 4 (March 1991), but has significant differences.
Raku is a reinvention of Perl, a language in the same lineage but not compatible. The two are complementary, not mutually exclusive. Raku is not meant to replace Perl, and vice versa. See ["What is Raku (Perl 6)?"](#What-is-Raku-%28Perl-6%29%3F) below to find out more.
See [perlhist](https://perldoc.perl.org/5.36.0/perlhist) for a history of Perl revisions.
###
What is Raku (Perl 6)?
Raku (formerly known as Perl 6) was *originally* described as the community's rewrite of Perl, however as the language evolved, it became clear that it is a separate language, but in the same language family as Perl.
Raku is not intended primarily as a replacement for Perl, but as its own thing - and libraries exist to allow you to call Perl code from Raku programs and vice versa.
Contrary to popular belief, Raku and Perl peacefully coexist with one another. Raku has proven to be a fascinating source of ideas for those using Perl (the [Moose](moose) object system is a well-known example). There is overlap in the communities, and this overlap fosters the tradition of sharing and borrowing that have been instrumental to Perl's success.
For more about Raku see <https://www.raku.org/>.
"We're really serious about reinventing everything that needs reinventing." --Larry Wall
###
How stable is Perl?
Production releases, which incorporate bug fixes and new functionality, are widely tested before release. Since the 5.000 release, we have averaged about one production release per year.
The Perl development team occasionally make changes to the internal core of the language, but all possible efforts are made toward backward compatibility.
###
How often are new versions of Perl released?
Recently, the plan has been to release a new version of Perl roughly every April, but getting the release right is more important than sticking rigidly to a calendar date, so the release date is somewhat flexible. The historical release dates can be viewed at <http://www.cpan.org/src/README.html>.
Even numbered minor versions (5.14, 5.16, 5.18) are production versions, and odd numbered minor versions (5.15, 5.17, 5.19) are development versions. Unless you want to try out an experimental feature, you probably never want to install a development version of Perl.
The Perl development team are called Perl 5 Porters, and their organization is described at <http://perldoc.perl.org/perlpolicy.html>. The organizational rules really just boil down to one: Larry is always right, even when he was wrong.
###
Is Perl difficult to learn?
No, Perl is easy to start [learning](http://learn.perl.org/) --and easy to keep learning. It looks like most programming languages you're likely to have experience with, so if you've ever written a C program, an awk script, a shell script, or even a BASIC program, you're already partway there.
Most tasks only require a small subset of the Perl language. One of the guiding mottos for Perl development is "there's more than one way to do it" (TMTOWTDI, sometimes pronounced "tim toady"). Perl's learning curve is therefore shallow (easy to learn) and long (there's a whole lot you can do if you really want).
Finally, because Perl is frequently (but not always, and certainly not by definition) an interpreted language, you can write your programs and test them without an intermediate compilation step, allowing you to experiment and test/debug quickly and easily. This ease of experimentation flattens the learning curve even more.
Things that make Perl easier to learn: Unix experience, almost any kind of programming experience, an understanding of regular expressions, and the ability to understand other people's code. If there's something you need to do, then it's probably already been done, and a working example is usually available for free. Don't forget Perl modules, either. They're discussed in Part 3 of this FAQ, along with [CPAN](http://www.cpan.org/), which is discussed in Part 2.
###
How does Perl compare with other languages like Java, Python, REXX, Scheme, or Tcl?
Perl can be used for almost any coding problem, even ones which require integrating specialist C code for extra speed. As with any tool it can be used well or badly. Perl has many strengths, and a few weaknesses, precisely which areas are good and bad is often a personal choice.
When choosing a language you should also be influenced by the [resources](http://www.cpan.org/), [testing culture](http://www.cpantesters.org/) and [community](http://www.perl.org/community.html) which surrounds it.
For comparisons to a specific language it is often best to create a small project in both languages and compare the results, make sure to use all the [resources](http://www.cpan.org/) of each language, as a language is far more than just it's syntax.
###
Can I do [task] in Perl?
Perl is flexible and extensible enough for you to use on virtually any task, from one-line file-processing tasks to large, elaborate systems.
For many people, Perl serves as a great replacement for shell scripting. For others, it serves as a convenient, high-level replacement for most of what they'd program in low-level languages like C or C++. It's ultimately up to you (and possibly your management) which tasks you'll use Perl for and which you won't.
If you have a library that provides an API, you can make any component of it available as just another Perl function or variable using a Perl extension written in C or C++ and dynamically linked into your main perl interpreter. You can also go the other direction, and write your main program in C or C++, and then link in some Perl code on the fly, to create a powerful application. See <perlembed>.
That said, there will always be small, focused, special-purpose languages dedicated to a specific problem domain that are simply more convenient for certain kinds of problems. Perl tries to be all things to all people, but nothing special to anyone. Examples of specialized languages that come to mind include prolog and matlab.
###
When shouldn't I program in Perl?
One good reason is when you already have an existing application written in another language that's all done (and done well), or you have an application language specifically designed for a certain task (e.g. prolog, make).
If you find that you need to speed up a specific part of a Perl application (not something you often need) you may want to use C, but you can access this from your Perl code with <perlxs>.
###
What's the difference between "perl" and "Perl"?
"Perl" is the name of the language. Only the "P" is capitalized. The name of the interpreter (the program which runs the Perl script) is "perl" with a lowercase "p".
You may or may not choose to follow this usage. But never write "PERL", because perl is not an acronym.
###
What is a JAPH?
(contributed by brian d foy)
JAPH stands for "Just another Perl hacker,", which Randal Schwartz used to sign email and usenet messages starting in the late 1980s. He previously used the phrase with many subjects ("Just another x hacker,"), so to distinguish his JAPH, he started to write them as Perl programs:
```
print "Just another Perl hacker,";
```
Other people picked up on this and started to write clever or obfuscated programs to produce the same output, spinning things quickly out of control while still providing hours of amusement for their creators and readers.
CPAN has several JAPH programs at <http://www.cpan.org/misc/japh>.
###
How can I convince others to use Perl?
(contributed by brian d foy)
Appeal to their self interest! If Perl is new (and thus scary) to them, find something that Perl can do to solve one of their problems. That might mean that Perl either saves them something (time, headaches, money) or gives them something (flexibility, power, testability).
In general, the benefit of a language is closely related to the skill of the people using that language. If you or your team can be faster, better, and stronger through Perl, you'll deliver more value. Remember, people often respond better to what they get out of it. If you run into resistance, figure out what those people get out of the other choice and how Perl might satisfy that requirement.
You don't have to worry about finding or paying for Perl; it's freely available and several popular operating systems come with Perl. Community support in places such as Perlmonks ( <http://www.perlmonks.com> ) and the various Perl mailing lists ( <http://lists.perl.org> ) means that you can usually get quick answers to your problems.
Finally, keep in mind that Perl might not be the right tool for every job. You're a much better advocate if your claims are reasonable and grounded in reality. Dogmatically advocating anything tends to make people discount your message. Be honest about possible disadvantages to your choice of Perl since any choice has trade-offs.
You might find these links useful:
* <http://www.perl.org/about.html>
* <http://perltraining.com.au/whyperl.html>
AUTHOR AND COPYRIGHT
---------------------
Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.
This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.
Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required.
| programming_docs |
perl Test2::IPC Test2::IPC
==========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
+ [DISABLING IT](#DISABLING-IT)
* [EXPORTS](#EXPORTS)
* [SOURCE](#SOURCE)
* [MAINTAINERS](#MAINTAINERS)
* [AUTHORS](#AUTHORS)
* [COPYRIGHT](#COPYRIGHT)
NAME
----
Test2::IPC - Turn on IPC for threading or forking support.
SYNOPSIS
--------
You should `use Test2::IPC;` as early as possible in your test file. If you import this module after API initialization it will attempt to retrofit IPC onto the existing hubs.
###
DISABLING IT
You can use `no Test2::IPC;` to disable IPC for good. You can also use the T2\_NO\_IPC env var.
EXPORTS
-------
All exports are optional.
cull() Cull allows you to collect results from other processes or threads on demand.
SOURCE
------
The source code repository for Test2 can be found at *http://github.com/Test-More/test-more/*.
MAINTAINERS
-----------
Chad Granum <[email protected]> AUTHORS
-------
Chad Granum <[email protected]> COPYRIGHT
---------
Copyright 2020 Chad Granum <[email protected]>.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See *http://dev.perl.org/licenses/*
perl VMS::DCLsym VMS::DCLsym
===========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
+ [Tied hash interface](#Tied-hash-interface)
+ [Object interface](#Object-interface)
* [AUTHOR](#AUTHOR)
* [VERSION](#VERSION)
* [BUGS](#BUGS)
NAME
----
VMS::DCLsym - Perl extension to manipulate DCL symbols
SYNOPSIS
--------
```
tie %allsyms, VMS::DCLsym;
tie %cgisyms, VMS::DCLsym, 'GLOBAL';
$handle = new VMS::DCLsym;
$value = $handle->getsym($name);
$handle->setsym($name, $value, 'GLOBAL')
or die "Can't create symbol: $!\n";
$handle->delsym($name, 'LOCAL') or die "Can't delete symbol: $!\n";
$handle->clearcache();
```
DESCRIPTION
-----------
The VMS::DCLsym extension provides access to DCL symbols using a tied hash interface. This allows Perl scripts to manipulate symbols in a manner similar to the way in which logical names are manipulated via the built-in `%ENV` hash. Alternatively, one can call methods in this package directly to read, create, and delete symbols.
###
Tied hash interface
This interface lets you treat the DCL symbol table as a Perl associative array, in which the key of each element is the symbol name, and the value of the element is that symbol's value. Case is not significant in the key string, as DCL converts symbol names to uppercase, but it is significant in the value string. All of the usual operations on associative arrays are supported. Reading an element retrieves the current value of the symbol, assigning to it defines a new symbol (or overwrites the old value of an existing symbol), and deleting an element deletes the corresponding symbol. Setting an element to `undef`, or `undef`ing it directly, sets the corresponding symbol to the null string. You may also read the special keys ':GLOBAL' and ':LOCAL' to find out whether a default symbol table has been specified for this hash (see the next paragraph), or set either or these keys to specify a default symbol table.
When you call the `tie` function to bind an associative array to this package, you may specify as an optional argument the symbol table in which you wish to create and delete symbols. If the argument is the string 'GLOBAL', then the global symbol table is used; any other string causes the local symbol table to be used. Note that this argument does not affect attempts to read symbols; if a symbol with the specified name exists in the local symbol table, it is always returned in preference to a symbol by the same name in the global symbol table.
###
Object interface
Although it's less convenient in some ways than the tied hash interface, you can also call methods directly to manipulate individual symbols. In some cases, this allows you finer control than using a tied hash aggregate. The following methods are supported:
new This creates a `VMS::DCLsym` object which can be used as a handle for later method calls. The single optional argument specifies the symbol table used by default in future method calls, in the same way as the optional argument to `tie` described above.
getsym If called in a scalar context, `getsym` returns the value of the symbol whose name is given as the argument to the call, or `undef` if no such symbol exists. Symbols in the local symbol table are always used in preference to symbols in the global symbol table. If called in a list context, `getsym` returns a two-element list, whose first element is the value of the symbol, and whose second element is the string 'GLOBAL' or 'LOCAL', indicating the table from which the symbol's value was read.
setsym The first two arguments taken by this method are the name of the symbol and the value which should be assigned to it. The optional third argument is a string specifying the symbol table to be used; 'GLOBAL' specifies the global symbol table, and any other string specifies the local symbol table. If this argument is omitted, the default symbol table for the object is used. `setsym` returns TRUE if successful, and FALSE otherwise.
delsym This method deletes the symbol whose name is given as the first argument. The optional second argument specifies the symbol table, as described above under `setsym`. It returns TRUE if the symbol was successfully deleted, and FALSE if it was not.
clearcache Because of the overhead associated with obtaining the list of defined symbols for the tied hash iterator, it is only done once, and the list is reused for subsequent iterations. Changes to symbols made through this package are recorded, but in the rare event that someone changes the process' symbol table from outside (as is possible using some software from the net), the iterator will be out of sync with the symbol table. If you expect this to happen, you can reset the cache by calling this method. In addition, if you pass a FALSE value as the first argument, caching will be disabled. It can be re-enabled later by calling `clearcache` again with a TRUE value as the first argument. It returns TRUE or FALSE to indicate whether caching was previously enabled or disabled, respectively.
This method is a stopgap until we can incorporate code into this extension to traverse the process' symbol table directly, so it may disappear in a future version of this package.
AUTHOR
------
Charles Bailey [email protected]
VERSION
-------
1.09
BUGS
----
The list of symbols for the iterator is assembled by spawning off a subprocess, which can be slow. Ideally, we should just traverse the process' symbol table directly from C.
perl Sub::Util Sub::Util
=========
CONTENTS
--------
* [NAME](#NAME)
* [SYNOPSIS](#SYNOPSIS)
* [DESCRIPTION](#DESCRIPTION)
* [FUNCTIONS](#FUNCTIONS)
+ [prototype](#prototype)
+ [set\_prototype](#set_prototype)
+ [subname](#subname)
+ [set\_subname](#set_subname)
* [AUTHOR](#AUTHOR)
NAME
----
Sub::Util - A selection of utility subroutines for subs and CODE references
SYNOPSIS
--------
```
use Sub::Util qw( prototype set_prototype subname set_subname );
```
DESCRIPTION
-----------
`Sub::Util` contains a selection of utility subroutines that are useful for operating on subs and CODE references.
The rationale for inclusion in this module is that the function performs some work for which an XS implementation is essential because it cannot be implemented in Pure Perl, and which is sufficiently-widely used across CPAN that its popularity warrants inclusion in a core module, which this is.
FUNCTIONS
---------
### prototype
```
my $proto = prototype( $code )
```
*Since version 1.40.*
Returns the prototype of the given `$code` reference, if it has one, as a string. This is the same as the `CORE::prototype` operator; it is included here simply for symmetry and completeness with the other functions.
### set\_prototype
```
my $code = set_prototype $prototype, $code;
```
*Since version 1.40.*
Sets the prototype of the function given by the `$code` reference, or deletes it if `$prototype` is `undef`. Returns the `$code` reference itself.
*Caution*: This function takes arguments in a different order to the previous copy of the code from `Scalar::Util`. This is to match the order of `set_subname`, and other potential additions in this file. This order has been chosen as it allows a neat and simple chaining of other `Sub::Util::set_*` functions as might become available, such as:
```
my $code =
set_subname name_here =>
set_prototype '&@' =>
set_attribute ':lvalue' =>
sub { ...... };
```
### subname
```
my $name = subname( $code )
```
*Since version 1.40.*
Returns the name of the given `$code` reference, if it has one. Normal named subs will give a fully-qualified name consisting of the package and the localname separated by `::`. Anonymous code references will give `__ANON__` as the localname. If the package the code was compiled in has been deleted (e.g. using `delete_package` from [Symbol](symbol)), `__ANON__` will be returned as the package name. If a name has been set using ["set\_subname"](#set_subname), this name will be returned instead.
This function was inspired by `sub_fullname` from <Sub::Identify>. The remaining functions that `Sub::Identify` implements can easily be emulated using regexp operations, such as
```
sub get_code_info { return (subname $_[0]) =~ m/^(.+)::(.*?)$/ }
sub sub_name { return (get_code_info $_[0])[0] }
sub stash_name { return (get_code_info $_[0])[1] }
```
*Users of Sub::Name beware*: This function is **not** the same as `Sub::Name::subname`; it returns the existing name of the sub rather than changing it. To set or change a name, see instead ["set\_subname"](#set_subname).
### set\_subname
```
my $code = set_subname $name, $code;
```
*Since version 1.40.*
Sets the name of the function given by the `$code` reference. Returns the `$code` reference itself. If the `$name` is unqualified, the package of the caller is used to qualify it.
This is useful for applying names to anonymous CODE references so that stack traces and similar situations, to give a useful name rather than having the default of `__ANON__`. Note that this name is only used for this situation; the `set_subname` will not install it into the symbol table; you will have to do that yourself if required.
However, since the name is not used by perl except as the return value of `caller`, for stack traces or similar, there is no actual requirement that the name be syntactically valid as a perl function name. This could be used to attach extra information that could be useful in debugging stack traces.
This function was copied from `Sub::Name::subname` and renamed to the naming convention of this module.
AUTHOR
------
The general structure of this module was written by Paul Evans <[email protected]>.
The XS implementation of ["set\_subname"](#set_subname) was copied from <Sub::Name> by Matthijs van Duin <[email protected]>
perl perlunicode perlunicode
===========
CONTENTS
--------
* [NAME](#NAME)
* [DESCRIPTION](#DESCRIPTION)
+ [Important Caveats](#Important-Caveats)
+ [Byte and Character Semantics](#Byte-and-Character-Semantics)
+ [ASCII Rules versus Unicode Rules](#ASCII-Rules-versus-Unicode-Rules)
+ [Extended Grapheme Clusters (Logical characters)](#Extended-Grapheme-Clusters-(Logical-characters))
+ [Unicode Character Properties](#Unicode-Character-Properties)
- [General\_Category](#General_Category)
- [Bidirectional Character Types](#Bidirectional-Character-Types)
- [Scripts](#Scripts)
- [Use of the "Is" Prefix](#Use-of-the-%22Is%22-Prefix)
- [Blocks](#Blocks)
- [Other Properties](#Other-Properties)
+ [Comparison of \N{...} and \p{name=...}](#Comparison-of-%5CN%7B...%7D-and-%5Cp%7Bname=...%7D)
+ [Wildcards in Property Values](#Wildcards-in-Property-Values)
+ [User-Defined Character Properties](#User-Defined-Character-Properties)
+ [User-Defined Case Mappings (for serious hackers only)](#User-Defined-Case-Mappings-(for-serious-hackers-only))
+ [Character Encodings for Input and Output](#Character-Encodings-for-Input-and-Output)
+ [Unicode Regular Expression Support Level](#Unicode-Regular-Expression-Support-Level)
- [Level 1 - Basic Unicode Support](#Level-1-Basic-Unicode-Support)
- [Level 2 - Extended Unicode Support](#Level-2-Extended-Unicode-Support)
- [Level 3 - Tailored Support](#Level-3-Tailored-Support)
+ [Unicode Encodings](#Unicode-Encodings)
+ [Noncharacter code points](#Noncharacter-code-points)
+ [Beyond Unicode code points](#Beyond-Unicode-code-points)
+ [Security Implications of Unicode](#Security-Implications-of-Unicode)
+ [Unicode in Perl on EBCDIC](#Unicode-in-Perl-on-EBCDIC)
+ [Locales](#Locales)
+ [When Unicode Does Not Happen](#When-Unicode-Does-Not-Happen)
+ [The "Unicode Bug"](#The-%22Unicode-Bug%22)
+ [Forcing Unicode in Perl (Or Unforcing Unicode in Perl)](#Forcing-Unicode-in-Perl-(Or-Unforcing-Unicode-in-Perl))
+ [Using Unicode in XS](#Using-Unicode-in-XS)
+ [Hacking Perl to work on earlier Unicode versions (for very serious hackers only)](#Hacking-Perl-to-work-on-earlier-Unicode-versions-(for-very-serious-hackers-only))
+ [Porting code from perl-5.6.X](#Porting-code-from-perl-5.6.X)
* [BUGS](#BUGS)
+ [Interaction with Extensions](#Interaction-with-Extensions)
+ [Speed](#Speed)
* [SEE ALSO](#SEE-ALSO)
NAME
----
perlunicode - Unicode support in Perl
DESCRIPTION
-----------
If you haven't already, before reading this document, you should become familiar with both <perlunitut> and <perluniintro>.
Unicode aims to **UNI**-fy the en-**CODE**-ings of all the world's character sets into a single Standard. For quite a few of the various coding standards that existed when Unicode was first created, converting from each to Unicode essentially meant adding a constant to each code point in the original standard, and converting back meant just subtracting that same constant. For ASCII and ISO-8859-1, the constant is 0. For ISO-8859-5, (Cyrillic) the constant is 864; for Hebrew (ISO-8859-8), it's 1488; Thai (ISO-8859-11), 3424; and so forth. This made it easy to do the conversions, and facilitated the adoption of Unicode.
And it worked; nowadays, those legacy standards are rarely used. Most everyone uses Unicode.
Unicode is a comprehensive standard. It specifies many things outside the scope of Perl, such as how to display sequences of characters. For a full discussion of all aspects of Unicode, see <https://www.unicode.org>.
###
Important Caveats
Even though some of this section may not be understandable to you on first reading, we think it's important enough to highlight some of the gotchas before delving further, so here goes:
Unicode support is an extensive requirement. While Perl does not implement the Unicode standard or the accompanying technical reports from cover to cover, Perl does support many Unicode features.
Also, the use of Unicode may present security issues that aren't obvious, see ["Security Implications of Unicode"](#Security-Implications-of-Unicode) below.
Safest if you `use feature 'unicode_strings'`
In order to preserve backward compatibility, Perl does not turn on full internal Unicode support unless the pragma [`use feature 'unicode_strings'`](feature#The-%27unicode_strings%27-feature) is specified. (This is automatically selected if you `use v5.12` or higher.) Failure to do this can trigger unexpected surprises. See ["The "Unicode Bug""](#The-%22Unicode-Bug%22) below.
This pragma doesn't affect I/O. Nor does it change the internal representation of strings, only their interpretation. There are still several places where Unicode isn't fully supported, such as in filenames.
Input and Output Layers Use the `:encoding(...)` layer to read from and write to filehandles using the specified encoding. (See <open>.)
You must convert your non-ASCII, non-UTF-8 Perl scripts to be UTF-8. The <encoding> module has been deprecated since perl 5.18 and the perl internals it requires have been removed with perl 5.26.
`use utf8` still needed to enable [UTF-8](#Unicode-Encodings) in scripts If your Perl script is itself encoded in [UTF-8](#Unicode-Encodings), the `use utf8` pragma must be explicitly included to enable recognition of that (in string or regular expression literals, or in identifier names). **This is the only time when an explicit `use utf8` is needed.** (See <utf8>).
If a Perl script begins with the bytes that form the UTF-8 encoding of the Unicode BYTE ORDER MARK (`BOM`, see ["Unicode Encodings"](#Unicode-Encodings)), those bytes are completely ignored.
[UTF-16](#Unicode-Encodings) scripts autodetected If a Perl script begins with the Unicode `BOM` (UTF-16LE, UTF16-BE), or if the script looks like non-`BOM`-marked UTF-16 of either endianness, Perl will correctly read in the script as the appropriate Unicode encoding.
###
Byte and Character Semantics
Before Unicode, most encodings used 8 bits (a single byte) to encode each character. Thus a character was a byte, and a byte was a character, and there could be only 256 or fewer possible characters. "Byte Semantics" in the title of this section refers to this behavior. There was no need to distinguish between "Byte" and "Character".
Then along comes Unicode which has room for over a million characters (and Perl allows for even more). This means that a character may require more than a single byte to represent it, and so the two terms are no longer equivalent. What matter are the characters as whole entities, and not usually the bytes that comprise them. That's what the term "Character Semantics" in the title of this section refers to.
Perl had to change internally to decouple "bytes" from "characters". It is important that you too change your ideas, if you haven't already, so that "byte" and "character" no longer mean the same thing in your mind.
The basic building block of Perl strings has always been a "character". The changes basically come down to that the implementation no longer thinks that a character is always just a single byte.
There are various things to note:
* String handling functions, for the most part, continue to operate in terms of characters. `length()`, for example, returns the number of characters in a string, just as before. But that number no longer is necessarily the same as the number of bytes in the string (there may be more bytes than characters). The other such functions include `chop()`, `chomp()`, `substr()`, `pos()`, `index()`, `rindex()`, `sort()`, `sprintf()`, and `write()`.
The exceptions are:
+ the bit-oriented `vec`
+ the byte-oriented `pack`/`unpack` `"C"` format
However, the `W` specifier does operate on whole characters, as does the `U` specifier.
+ some operators that interact with the platform's operating system
Operators dealing with filenames are examples.
+ when the functions are called from within the scope of the `[use bytes](bytes)` pragma
Likely, you should use this only for debugging anyway.
* Strings--including hash keys--and regular expression patterns may contain characters that have ordinal values larger than 255.
If you use a Unicode editor to edit your program, Unicode characters may occur directly within the literal strings in UTF-8 encoding, or UTF-16. (The former requires a `use utf8`, the latter may require a `BOM`.)
["Creating Unicode" in perluniintro](perluniintro#Creating-Unicode) gives other ways to place non-ASCII characters in your strings.
* The `chr()` and `ord()` functions work on whole characters.
* Regular expressions match whole characters. For example, `"."` matches a whole character instead of only a single byte.
* The `tr///` operator translates whole characters. (Note that the `tr///CU` functionality has been removed. For similar functionality to that, see `pack('U0', ...)` and `pack('C0', ...)`).
* `scalar reverse()` reverses by character rather than by byte.
* The bit string operators, `& | ^ ~` and (starting in v5.22) `&. |. ^. ~.` can operate on bit strings encoded in UTF-8, but this can give unexpected results if any of the strings contain code points above 0xFF. Starting in v5.28, it is a fatal error to have such an operand. Otherwise, the operation is performed on a non-UTF-8 copy of the operand. If you're not sure about the encoding of a string, downgrade it before using any of these operators; you can use [`utf8::utf8_downgrade()`](utf8#Utility-functions).
The bottom line is that Perl has always practiced "Character Semantics", but with the advent of Unicode, that is now different than "Byte Semantics".
###
ASCII Rules versus Unicode Rules
Before Unicode, when a character was a byte was a character, Perl knew only about the 128 characters defined by ASCII, code points 0 through 127 (except for under [`use locale`](perllocale)). That left the code points 128 to 255 as unassigned, and available for whatever use a program might want. The only semantics they have is their ordinal numbers, and that they are members of none of the non-negative character classes. None are considered to match `\w` for example, but all match `\W`.
Unicode, of course, assigns each of those code points a particular meaning (along with ones above 255). To preserve backward compatibility, Perl only uses the Unicode meanings when there is some indication that Unicode is what is intended; otherwise the non-ASCII code points remain treated as if they are unassigned.
Here are the ways that Perl knows that a string should be treated as Unicode:
* Within the scope of `use utf8`
If the whole program is Unicode (signified by using 8-bit **U**nicode **T**ransformation **F**ormat), then all literal strings within it must be Unicode.
* Within the scope of [`use feature 'unicode_strings'`](feature#The-%27unicode_strings%27-feature)
This pragma was created so you can explicitly tell Perl that operations executed within its scope are to use Unicode rules. More operations are affected with newer perls. See ["The "Unicode Bug""](#The-%22Unicode-Bug%22).
* Within the scope of `use v5.12` or higher
This implicitly turns on `use feature 'unicode_strings'`.
* Within the scope of [`use locale 'not_characters'`](perllocale#Unicode-and-UTF-8), or [`use locale`](perllocale) and the current locale is a UTF-8 locale.
The former is defined to imply Unicode handling; and the latter indicates a Unicode locale, hence a Unicode interpretation of all strings within it.
* When the string contains a Unicode-only code point
Perl has never accepted code points above 255 without them being Unicode, so their use implies Unicode for the whole string.
* When the string contains a Unicode named code point `\N{...}`
The `\N{...}` construct explicitly refers to a Unicode code point, even if it is one that is also in ASCII. Therefore the string containing it must be Unicode.
* When the string has come from an external source marked as Unicode
The [`-C`](perlrun#-C-%5Bnumber%2Flist%5D) command line option can specify that certain inputs to the program are Unicode, and the values of this can be read by your Perl code, see ["${^UNICODE}" in perlvar](perlvar#%24%7B%5EUNICODE%7D).
* When the string has been upgraded to UTF-8
The function [`utf8::utf8_upgrade()`](utf8#Utility-functions) can be explicitly used to permanently (unless a subsequent `utf8::utf8_downgrade()` is called) cause a string to be treated as Unicode.
* There are additional methods for regular expression patterns
A pattern that is compiled with the `/u` or `/a` modifiers is treated as Unicode (though there are some restrictions with `/a`). Under the `/d` and `/l` modifiers, there are several other indications for Unicode; see ["Character set modifiers" in perlre](perlre#Character-set-modifiers).
Note that all of the above are overridden within the scope of `[use bytes](bytes)`; but you should be using this pragma only for debugging.
Note also that some interactions with the platform's operating system never use Unicode rules.
When Unicode rules are in effect:
* Case translation operators use the Unicode case translation tables.
Note that `uc()`, or `\U` in interpolated strings, translates to uppercase, while `ucfirst`, or `\u` in interpolated strings, translates to titlecase in languages that make the distinction (which is equivalent to uppercase in languages without the distinction).
There is a CPAN module, `<Unicode::Casing>`, which allows you to define your own mappings to be used in `lc()`, `lcfirst()`, `uc()`, `ucfirst()`, and `fc` (or their double-quoted string inlined versions such as `\U`). (Prior to Perl 5.16, this functionality was partially provided in the Perl core, but suffered from a number of insurmountable drawbacks, so the CPAN module was written instead.)
* Character classes in regular expressions match based on the character properties specified in the Unicode properties database.
`\w` can be used to match a Japanese ideograph, for instance; and `[[:digit:]]` a Bengali number.
* Named Unicode properties, scripts, and block ranges may be used (like bracketed character classes) by using the `\p{}` "matches property" construct and the `\P{}` negation, "doesn't match property".
See ["Unicode Character Properties"](#Unicode-Character-Properties) for more details.
You can define your own character properties and use them in the regular expression with the `\p{}` or `\P{}` construct. See ["User-Defined Character Properties"](#User-Defined-Character-Properties) for more details.
###
Extended Grapheme Clusters (Logical characters)
Consider a character, say `H`. It could appear with various marks around it, such as an acute accent, or a circumflex, or various hooks, circles, arrows, *etc.*, above, below, to one side or the other, *etc*. There are many possibilities among the world's languages. The number of combinations is astronomical, and if there were a character for each combination, it would soon exhaust Unicode's more than a million possible characters. So Unicode took a different approach: there is a character for the base `H`, and a character for each of the possible marks, and these can be variously combined to get a final logical character. So a logical character--what appears to be a single character--can be a sequence of more than one individual characters. The Unicode standard calls these "extended grapheme clusters" (which is an improved version of the no-longer much used "grapheme cluster"); Perl furnishes the `\X` regular expression construct to match such sequences in their entirety.
But Unicode's intent is to unify the existing character set standards and practices, and several pre-existing standards have single characters that mean the same thing as some of these combinations, like ISO-8859-1, which has quite a few of them. For example, `"LATIN CAPITAL LETTER E WITH ACUTE"` was already in this standard when Unicode came along. Unicode therefore added it to its repertoire as that single character. But this character is considered by Unicode to be equivalent to the sequence consisting of the character `"LATIN CAPITAL LETTER E"` followed by the character `"COMBINING ACUTE ACCENT"`.
`"LATIN CAPITAL LETTER E WITH ACUTE"` is called a "pre-composed" character, and its equivalence with the "E" and the "COMBINING ACCENT" sequence is called canonical equivalence. All pre-composed characters are said to have a decomposition (into the equivalent sequence), and the decomposition type is also called canonical. A string may be comprised as much as possible of precomposed characters, or it may be comprised of entirely decomposed characters. Unicode calls these respectively, "Normalization Form Composed" (NFC) and "Normalization Form Decomposed". The `<Unicode::Normalize>` module contains functions that convert between the two. A string may also have both composed characters and decomposed characters; this module can be used to make it all one or the other.
You may be presented with strings in any of these equivalent forms. There is currently nothing in Perl 5 that ignores the differences. So you'll have to specially handle it. The usual advice is to convert your inputs to `NFD` before processing further.
For more detailed information, see <http://unicode.org/reports/tr15/>.
###
Unicode Character Properties
(The only time that Perl considers a sequence of individual code points as a single logical character is in the `\X` construct, already mentioned above. Therefore "character" in this discussion means a single Unicode code point.)
Very nearly all Unicode character properties are accessible through regular expressions by using the `\p{}` "matches property" construct and the `\P{}` "doesn't match property" for its negation.
For instance, `\p{Uppercase}` matches any single character with the Unicode `"Uppercase"` property, while `\p{L}` matches any character with a `General_Category` of `"L"` (letter) property (see ["General\_Category"](#General_Category) below). Brackets are not required for single letter property names, so `\p{L}` is equivalent to `\pL`.
More formally, `\p{Uppercase}` matches any single character whose Unicode `Uppercase` property value is `True`, and `\P{Uppercase}` matches any character whose `Uppercase` property value is `False`, and they could have been written as `\p{Uppercase=True}` and `\p{Uppercase=False}`, respectively.
This formality is needed when properties are not binary; that is, if they can take on more values than just `True` and `False`. For example, the `Bidi_Class` property (see ["Bidirectional Character Types"](#Bidirectional-Character-Types) below), can take on several different values, such as `Left`, `Right`, `Whitespace`, and others. To match these, one needs to specify both the property name (`Bidi_Class`), AND the value being matched against (`Left`, `Right`, *etc.*). This is done, as in the examples above, by having the two components separated by an equal sign (or interchangeably, a colon), like `\p{Bidi_Class: Left}`.
All Unicode-defined character properties may be written in these compound forms of `\p{*property*=*value*}` or `\p{*property*:*value*}`, but Perl provides some additional properties that are written only in the single form, as well as single-form short-cuts for all binary properties and certain others described below, in which you may omit the property name and the equals or colon separator.
Most Unicode character properties have at least two synonyms (or aliases if you prefer): a short one that is easier to type and a longer one that is more descriptive and hence easier to understand. Thus the `"L"` and `"Letter"` properties above are equivalent and can be used interchangeably. Likewise, `"Upper"` is a synonym for `"Uppercase"`, and we could have written `\p{Uppercase}` equivalently as `\p{Upper}`. Also, there are typically various synonyms for the values the property can be. For binary properties, `"True"` has 3 synonyms: `"T"`, `"Yes"`, and `"Y"`; and `"False"` has correspondingly `"F"`, `"No"`, and `"N"`. But be careful. A short form of a value for one property may not mean the same thing as the short form spelled the same for another. Thus, for the `["General\_Category"](#General_Category)` property, `"L"` means `"Letter"`, but for the [`Bidi_Class`](#Bidirectional-Character-Types) property, `"L"` means `"Left"`. A complete list of properties and synonyms is in <perluniprops>.
Upper/lower case differences in property names and values are irrelevant; thus `\p{Upper}` means the same thing as `\p{upper}` or even `\p{UpPeR}`. Similarly, you can add or subtract underscores anywhere in the middle of a word, so that these are also equivalent to `\p{U_p_p_e_r}`. And white space is generally irrelevant adjacent to non-word characters, such as the braces and the equals or colon separators, so `\p{ Upper }` and `\p{ Upper_case : Y }` are equivalent to these as well. In fact, white space and even hyphens can usually be added or deleted anywhere. So even `\p{ Up-per case = Yes}` is equivalent. All this is called "loose-matching" by Unicode. The "name" property has some restrictions on this due to a few outlier names. Full details are given in <https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>.
The few places where stricter matching is used is in the middle of numbers, the "name" property, and in the Perl extension properties that begin or end with an underscore. Stricter matching cares about white space (except adjacent to non-word characters), hyphens, and non-interior underscores.
You can also use negation in both `\p{}` and `\P{}` by introducing a caret (`^`) between the first brace and the property name: `\p{^Tamil}` is equal to `\P{Tamil}`.
Almost all properties are immune to case-insensitive matching. That is, adding a `/i` regular expression modifier does not change what they match. There are two sets that are affected. The first set is `Uppercase_Letter`, `Lowercase_Letter`, and `Titlecase_Letter`, all of which match `Cased_Letter` under `/i` matching. And the second set is `Uppercase`, `Lowercase`, and `Titlecase`, all of which match `Cased` under `/i` matching. This set also includes its subsets `PosixUpper` and `PosixLower` both of which under `/i` match `PosixAlpha`. (The difference between these sets is that some things, such as Roman numerals, come in both upper and lower case so they are `Cased`, but aren't considered letters, so they aren't `Cased_Letter`'s.)
See ["Beyond Unicode code points"](#Beyond-Unicode-code-points) for special considerations when matching Unicode properties against non-Unicode code points.
#### **General\_Category**
Every Unicode character is assigned a general category, which is the "most usual categorization of a character" (from <https://www.unicode.org/reports/tr44>).
The compound way of writing these is like `\p{General_Category=Number}` (short: `\p{gc:n}`). But Perl furnishes shortcuts in which everything up through the equal or colon separator is omitted. So you can instead just write `\pN`.
Here are the short and long forms of the values the `General Category` property can have:
```
Short Long
L Letter
LC, L& Cased_Letter (that is: [\p{Ll}\p{Lu}\p{Lt}])
Lu Uppercase_Letter
Ll Lowercase_Letter
Lt Titlecase_Letter
Lm Modifier_Letter
Lo Other_Letter
M Mark
Mn Nonspacing_Mark
Mc Spacing_Mark
Me Enclosing_Mark
N Number
Nd Decimal_Number (also Digit)
Nl Letter_Number
No Other_Number
P Punctuation (also Punct)
Pc Connector_Punctuation
Pd Dash_Punctuation
Ps Open_Punctuation
Pe Close_Punctuation
Pi Initial_Punctuation
(may behave like Ps or Pe depending on usage)
Pf Final_Punctuation
(may behave like Ps or Pe depending on usage)
Po Other_Punctuation
S Symbol
Sm Math_Symbol
Sc Currency_Symbol
Sk Modifier_Symbol
So Other_Symbol
Z Separator
Zs Space_Separator
Zl Line_Separator
Zp Paragraph_Separator
C Other
Cc Control (also Cntrl)
Cf Format
Cs Surrogate
Co Private_Use
Cn Unassigned
```
Single-letter properties match all characters in any of the two-letter sub-properties starting with the same letter. `LC` and `L&` are special: both are aliases for the set consisting of everything matched by `Ll`, `Lu`, and `Lt`.
####
**Bidirectional Character Types**
Because scripts differ in their directionality (Hebrew and Arabic are written right to left, for example) Unicode supplies a `Bidi_Class` property. Some of the values this property can have are:
```
Value Meaning
L Left-to-Right
LRE Left-to-Right Embedding
LRO Left-to-Right Override
R Right-to-Left
AL Arabic Letter
RLE Right-to-Left Embedding
RLO Right-to-Left Override
PDF Pop Directional Format
EN European Number
ES European Separator
ET European Terminator
AN Arabic Number
CS Common Separator
NSM Non-Spacing Mark
BN Boundary Neutral
B Paragraph Separator
S Segment Separator
WS Whitespace
ON Other Neutrals
```
This property is always written in the compound form. For example, `\p{Bidi_Class:R}` matches characters that are normally written right to left. Unlike the `["General\_Category"](#General_Category)` property, this property can have more values added in a future Unicode release. Those listed above comprised the complete set for many Unicode releases, but others were added in Unicode 6.3; you can always find what the current ones are in <perluniprops>. And <https://www.unicode.org/reports/tr9/> describes how to use them.
#### **Scripts**
The world's languages are written in many different scripts. This sentence (unless you're reading it in translation) is written in Latin, while Russian is written in Cyrillic, and Greek is written in, well, Greek; Japanese mainly in Hiragana or Katakana. There are many more.
The Unicode `Script` and `Script_Extensions` properties give what script a given character is in. The `Script_Extensions` property is an improved version of `Script`, as demonstrated below. Either property can be specified with the compound form like `\p{Script=Hebrew}` (short: `\p{sc=hebr}`), or `\p{Script_Extensions=Javanese}` (short: `\p{scx=java}`). In addition, Perl furnishes shortcuts for all `Script_Extensions` property names. You can omit everything up through the equals (or colon), and simply write `\p{Latin}` or `\P{Cyrillic}`. (This is not true for `Script`, which is required to be written in the compound form. Prior to Perl v5.26, the single form returned the plain old `Script` version, but was changed because `Script_Extensions` gives better results.)
The difference between these two properties involves characters that are used in multiple scripts. For example the digits '0' through '9' are used in many parts of the world. These are placed in a script named `Common`. Other characters are used in just a few scripts. For example, the `"KATAKANA-HIRAGANA DOUBLE HYPHEN"` is used in both Japanese scripts, Katakana and Hiragana, but nowhere else. The `Script` property places all characters that are used in multiple scripts in the `Common` script, while the `Script_Extensions` property places those that are used in only a few scripts into each of those scripts; while still using `Common` for those used in many scripts. Thus both these match:
```
"0" =~ /\p{sc=Common}/ # Matches
"0" =~ /\p{scx=Common}/ # Matches
```
and only the first of these match:
```
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Common} # Matches
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Common} # No match
```
And only the last two of these match:
```
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Hiragana} # No match
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{sc=Katakana} # No match
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Hiragana} # Matches
"\N{KATAKANA-HIRAGANA DOUBLE HYPHEN}" =~ /\p{scx=Katakana} # Matches
```
`Script_Extensions` is thus an improved `Script`, in which there are fewer characters in the `Common` script, and correspondingly more in other scripts. It is new in Unicode version 6.0, and its data are likely to change significantly in later releases, as things get sorted out. New code should probably be using `Script_Extensions` and not plain `Script`. If you compile perl with a Unicode release that doesn't have `Script_Extensions`, the single form Perl extensions will instead refer to the plain `Script` property. If you compile with a version of Unicode that doesn't have the `Script` property, these extensions will not be defined at all.
(Actually, besides `Common`, the `Inherited` script, contains characters that are used in multiple scripts. These are modifier characters which inherit the script value of the controlling character. Some of these are used in many scripts, and so go into `Inherited` in both `Script` and `Script_Extensions`. Others are used in just a few scripts, so are in `Inherited` in `Script`, but not in `Script_Extensions`.)
It is worth stressing that there are several different sets of digits in Unicode that are equivalent to 0-9 and are matchable by `\d` in a regular expression. If they are used in a single language only, they are in that language's `Script` and `Script_Extensions`. If they are used in more than one script, they will be in `sc=Common`, but only if they are used in many scripts should they be in `scx=Common`.
The explanation above has omitted some detail; refer to UAX#24 "Unicode Script Property": <https://www.unicode.org/reports/tr24>.
A complete list of scripts and their shortcuts is in <perluniprops>.
####
**Use of the `"Is"` Prefix**
For backward compatibility (with ancient Perl 5.6), all properties writable without using the compound form mentioned so far may have `Is` or `Is_` prepended to their name, so `\P{Is_Lu}`, for example, is equal to `\P{Lu}`, and `\p{IsScript:Arabic}` is equal to `\p{Arabic}`.
#### **Blocks**
In addition to **scripts**, Unicode also defines **blocks** of characters. The difference between scripts and blocks is that the concept of scripts is closer to natural languages, while the concept of blocks is more of an artificial grouping based on groups of Unicode characters with consecutive ordinal values. For example, the `"Basic Latin"` block is all the characters whose ordinals are between 0 and 127, inclusive; in other words, the ASCII characters. The `"Latin"` script contains some letters from this as well as several other blocks, like `"Latin-1 Supplement"`, `"Latin Extended-A"`, *etc.*, but it does not contain all the characters from those blocks. It does not, for example, contain the digits 0-9, because those digits are shared across many scripts, and hence are in the `Common` script.
For more about scripts versus blocks, see UAX#24 "Unicode Script Property": <https://www.unicode.org/reports/tr24>
The `Script_Extensions` or `Script` properties are likely to be the ones you want to use when processing natural language; the `Block` property may occasionally be useful in working with the nuts and bolts of Unicode.
Block names are matched in the compound form, like `\p{Block: Arrows}` or `\p{Blk=Hebrew}`. Unlike most other properties, only a few block names have a Unicode-defined short name.
Perl also defines single form synonyms for the block property in cases where these do not conflict with something else. But don't use any of these, because they are unstable. Since these are Perl extensions, they are subordinate to official Unicode property names; Unicode doesn't know nor care about Perl's extensions. It may happen that a name that currently means the Perl extension will later be changed without warning to mean a different Unicode property in a future version of the perl interpreter that uses a later Unicode release, and your code would no longer work. The extensions are mentioned here for completeness: Take the block name and prefix it with one of: `In` (for example `\p{Blk=Arrows}` can currently be written as `\p{In_Arrows}`); or sometimes `Is` (like `\p{Is_Arrows}`); or sometimes no prefix at all (`\p{Arrows}`). As of this writing (Unicode 9.0) there are no conflicts with using the `In_` prefix, but there are plenty with the other two forms. For example, `\p{Is_Hebrew}` and `\p{Hebrew}` mean `\p{Script_Extensions=Hebrew}` which is NOT the same thing as `\p{Blk=Hebrew}`. Our advice used to be to use the `In_` prefix as a single form way of specifying a block. But Unicode 8.0 added properties whose names begin with `In`, and it's now clear that it's only luck that's so far prevented a conflict. Using `In` is only marginally less typing than `Blk:`, and the latter's meaning is clearer anyway, and guaranteed to never conflict. So don't take chances. Use `\p{Blk=foo}` for new code. And be sure that block is what you really really want to do. In most cases scripts are what you want instead.
A complete list of blocks is in <perluniprops>.
####
**Other Properties**
There are many more properties than the very basic ones described here. A complete list is in <perluniprops>.
Unicode defines all its properties in the compound form, so all single-form properties are Perl extensions. Most of these are just synonyms for the Unicode ones, but some are genuine extensions, including several that are in the compound form. And quite a few of these are actually recommended by Unicode (in <https://www.unicode.org/reports/tr18>).
This section gives some details on all extensions that aren't just synonyms for compound-form Unicode properties (for those properties, you'll have to refer to the [Unicode Standard](https://www.unicode.org/reports/tr44).
**`\p{All}`**
This matches every possible code point. It is equivalent to `qr/./s`. Unlike all the other non-user-defined `\p{}` property matches, no warning is ever generated if this is property is matched against a non-Unicode code point (see ["Beyond Unicode code points"](#Beyond-Unicode-code-points) below).
**`\p{Alnum}`**
This matches any `\p{Alphabetic}` or `\p{Decimal_Number}` character.
**`\p{Any}`**
This matches any of the 1\_114\_112 Unicode code points. It is a synonym for `\p{Unicode}`.
**`\p{ASCII}`**
This matches any of the 128 characters in the US-ASCII character set, which is a subset of Unicode.
**`\p{Assigned}`**
This matches any assigned code point; that is, any code point whose [general category](#General_Category) is not `Unassigned` (or equivalently, not `Cn`).
**`\p{Blank}`**
This is the same as `\h` and `\p{HorizSpace}`: A character that changes the spacing horizontally.
**`\p{Decomposition_Type: Non_Canonical}`** (Short: `\p{Dt=NonCanon}`) Matches a character that has any of the non-canonical decomposition types. Canonical decompositions are introduced in the ["Extended Grapheme Clusters (Logical characters)"](#Extended-Grapheme-Clusters-%28Logical-characters%29) section above. However, many more characters have a different type of decomposition, generically called "compatible" decompositions, or "non-canonical". The sequences that form these decompositions are not considered canonically equivalent to the pre-composed character. An example is the `"SUPERSCRIPT ONE"`. It is somewhat like a regular digit 1, but not exactly; its decomposition into the digit 1 is called a "compatible" decomposition, specifically a "super" (for "superscript") decomposition. There are several such compatibility decompositions (see <https://www.unicode.org/reports/tr44>). `\p{Dt: Non_Canon}` is a Perl extension that uses just one name to refer to the union of all of them.
Most Unicode characters don't have a decomposition, so their decomposition type is `"None"`. Hence, `Non_Canonical` is equivalent to
```
qr/(?[ \P{DT=Canonical} - \p{DT=None} ])/
```
(Note that one of the non-canonical decompositions is named "compat", which could perhaps have been better named "miscellaneous". It includes just the things that Unicode couldn't figure out a better generic name for.)
**`\p{Graph}`**
Matches any character that is graphic. Theoretically, this means a character that on a printer would cause ink to be used.
**`\p{HorizSpace}`**
This is the same as `\h` and `\p{Blank}`: a character that changes the spacing horizontally.
**`\p{In=*}`**
This is a synonym for `\p{Present_In=*}`
**`\p{PerlSpace}`**
This is the same as `\s`, restricted to ASCII, namely `[ \f\n\r\t]` and starting in Perl v5.18, a vertical tab.
Mnemonic: Perl's (original) space
**`\p{PerlWord}`**
This is the same as `\w`, restricted to ASCII, namely `[A-Za-z0-9_]`
Mnemonic: Perl's (original) word.
**`\p{Posix...}`**
There are several of these, which are equivalents, using the `\p{}` notation, for Posix classes and are described in ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
**`\p{Present_In: *}`** (Short: `\p{In=*}`) This property is used when you need to know in what Unicode version(s) a character is.
The "\*" above stands for some Unicode version number, such as `1.1` or `12.0`; or the "\*" can also be `Unassigned`. This property will match the code points whose final disposition has been settled as of the Unicode release given by the version number; `\p{Present_In: Unassigned}` will match those code points whose meaning has yet to be assigned.
For example, `U+0041` `"LATIN CAPITAL LETTER A"` was present in the very first Unicode release available, which is `1.1`, so this property is true for all valid "\*" versions. On the other hand, `U+1EFF` was not assigned until version 5.1 when it became `"LATIN SMALL LETTER Y WITH LOOP"`, so the only "\*" that would match it are 5.1, 5.2, and later.
Unicode furnishes the `Age` property from which this is derived. The problem with Age is that a strict interpretation of it (which Perl takes) has it matching the precise release a code point's meaning is introduced in. Thus `U+0041` would match only 1.1; and `U+1EFF` only 5.1. This is not usually what you want.
Some non-Perl implementations of the Age property may change its meaning to be the same as the Perl `Present_In` property; just be aware of that.
Another confusion with both these properties is that the definition is not that the code point has been *assigned*, but that the meaning of the code point has been *determined*. This is because 66 code points will always be unassigned, and so the `Age` for them is the Unicode version in which the decision to make them so was made. For example, `U+FDD0` is to be permanently unassigned to a character, and the decision to do that was made in version 3.1, so `\p{Age=3.1}` matches this character, as also does `\p{Present_In: 3.1}` and up.
**`\p{Print}`**
This matches any character that is graphical or blank, except controls.
**`\p{SpacePerl}`**
This is the same as `\s`, including beyond ASCII.
Mnemonic: Space, as modified by Perl. (It doesn't include the vertical tab until v5.18, which both the Posix standard and Unicode consider white space.)
**`\p{Title}`** and **`\p{Titlecase}`**
Under case-sensitive matching, these both match the same code points as `\p{General Category=Titlecase_Letter}` (`\p{gc=lt}`). The difference is that under `/i` caseless matching, these match the same as `\p{Cased}`, whereas `\p{gc=lt}` matches `\p{Cased_Letter`).
**`\p{Unicode}`**
This matches any of the 1\_114\_112 Unicode code points. `\p{Any}`.
**`\p{VertSpace}`**
This is the same as `\v`: A character that changes the spacing vertically.
**`\p{Word}`**
This is the same as `\w`, including over 100\_000 characters beyond ASCII.
**`\p{XPosix...}`**
There are several of these, which are the standard Posix classes extended to the full Unicode range. They are described in ["POSIX Character Classes" in perlrecharclass](perlrecharclass#POSIX-Character-Classes).
###
Comparison of `\N{...}` and `\p{name=...}`
Starting in Perl 5.32, you can specify a character by its name in regular expression patterns using `\p{name=...}`. This is in addition to the longstanding method of using `\N{...}`. The following summarizes the differences between these two:
```
\N{...} \p{Name=...}
can interpolate only with eval yes [1]
custom names yes no [2]
name aliases yes yes [3]
named sequences yes yes [4]
name value parsing exact Unicode loose [5]
```
[1] The ability to interpolate means you can do something like
```
qr/\p{na=latin capital letter $which}/
```
and specify `$which` elsewhere.
[2] You can create your own names for characters, and override official ones when using `\N{...}`. See ["CUSTOM ALIASES" in charnames](charnames#CUSTOM-ALIASES).
[3] Some characters have multiple names (synonyms).
[4] Some particular sequences of characters are given a single name, in addition to their individual ones.
[5] Exact name value matching means you have to specify case, hyphens, underscores, and spaces precisely in the name you want. Loose matching follows the Unicode rules <https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>, where these are mostly irrelevant. Except for a few outlier character names, these are the same rules as are already used for any other `\p{...}` property.
###
Wildcards in Property Values
Starting in Perl 5.30, it is possible to do something like this:
```
qr!\p{numeric_value=/\A[0-5]\z/}!
```
or, by abbreviating and adding `/x`,
```
qr! \p{nv= /(?x) \A [0-5] \z / }!
```
This matches all code points whose numeric value is one of 0, 1, 2, 3, 4, or 5. This particular example could instead have been written as
```
qr! \A [ \p{nv=0}\p{nv=1}\p{nv=2}\p{nv=3}\p{nv=4}\p{nv=5} ] \z !xx
```
in earlier perls, so in this case this feature just makes things easier and shorter to write. If we hadn't included the `\A` and `\z`, these would have matched things like `1/2` because that contains a 1 (as well as a 2). As written, it matches things like subscripts that have these numeric values. If we only wanted the decimal digits with those numeric values, we could say,
```
qr! (?[ \d & \p{nv=/[0-5]/ ]) }!x
```
The `\d` gets rid of needing to anchor the pattern, since it forces the result to only match `[0-9]`, and the `[0-5]` further restricts it.
The text in the above examples enclosed between the `"/"` characters can be just about any regular expression. It is independent of the main pattern, so doesn't share any capturing groups, *etc*. The delimiters for it must be ASCII punctuation, but it may NOT be delimited by `"{"`, nor `"}"` nor contain a literal `"}"`, as that delimits the end of the enclosing `\p{}`. Like any pattern, certain other delimiters are terminated by their mirror images. These are `"("`, `"[`", and `"<"`. If the delimiter is any of `"-"`, `"_"`, `"+"`, or `"\"`, or is the same delimiter as is used for the enclosing pattern, it must be preceded by a backslash escape, both fore and aft.
Beware of using `"$"` to indicate to match the end of the string. It can too easily be interpreted as being a punctuation variable, like `$/`.
No modifiers may follow the final delimiter. Instead, use ["(?adlupimnsx-imnsx)" in perlre](perlre#%28%3Fadlupimnsx-imnsx%29) and/or ["(?adluimnsx-imnsx:pattern)" in perlre](perlre#%28%3Fadluimnsx-imnsx%3Apattern%29) to specify modifiers. However, certain modifiers are illegal in your wildcard subpattern. The only character set modifier specifiable is `/aa`; any other character set, and `-m`, and `p`, and `s` are all illegal. Specifying modifiers like `qr/.../gc` that aren't legal in the `(?...)` notation normally raise a warning, but with wildcard subpatterns, their use is an error. The `m` modifier is ineffective; everything that matches will be a single line.
By default, your pattern is matched case-insensitively, as if `/i` had been specified. You can change this by saying `(?-i)` in your pattern.
There are also certain operations that are illegal. You can't nest `\p{...}` and `\P{...}` calls within a wildcard subpattern, and `\G` doesn't make sense, so is also prohibited.
And the `*` quantifier (or its equivalent `(0,}`) is illegal.
This feature is not available when the left-hand side is prefixed by `Is_`, nor for any form that is marked as "Discouraged" in ["Discouraged" in perluniprops](perluniprops#Discouraged).
This experimental feature has been added to begin to implement <https://www.unicode.org/reports/tr18/#Wildcard_Properties>. Using it will raise a (default-on) warning in the `experimental::uniprop_wildcards` category. We reserve the right to change its operation as we gain experience.
Your subpattern can be just about anything, but for it to have some utility, it should match when called with either or both of a) the full name of the property value with underscores (and/or spaces in the Block property) and some things uppercase; or b) the property value in all lowercase with spaces and underscores squeezed out. For example,
```
qr!\p{Blk=/Old I.*/}!
qr!\p{Blk=/oldi.*/}!
```
would match the same things.
Another example that shows that within `\p{...}`, `/x` isn't needed to have spaces:
```
qr!\p{scx= /Hebrew|Greek/ }!
```
To be safe, we should have anchored the above example, to prevent matches for something like `Hebrew_Braille`, but there aren't any script names like that, so far. A warning is issued if none of the legal values for a property are matched by your pattern. It's likely that a future release will raise a warning if your pattern ends up causing every possible code point to match.
Starting in 5.32, the Name, Name Aliases, and Named Sequences properties are allowed to be matched. They are considered to be a single combination property, just as has long been the case for `\N{}`. Loose matching doesn't work in exactly the same way for these as it does for the values of other properties. The rules are given in <https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>. As a result, Perl doesn't try loose matching for you, like it does in other properties. All letters in names are uppercase, but you can add `(?i)` to your subpattern to ignore case. If you're uncertain where a blank is, you can use `?` in your subpattern. No character name contains an underscore, so don't bother trying to match one. The use of hyphens is particularly problematic; refer to the above link. But note that, as of Unicode 13.0, the only script in modern usage which has weirdnesses with these is Tibetan; also the two Korean characters U+116C HANGUL JUNGSEONG OE and U+1180 HANGUL JUNGSEONG O-E. Unicode makes no promises to not add hyphen-problematic names in the future.
Using wildcards on these is resource intensive, given the hundreds of thousands of legal names that must be checked against.
An example of using Name property wildcards is
```
qr!\p{name=/(SMILING|GRINNING) FACE/}!
```
Another is
```
qr/(?[ \p{name=\/CJK\/} - \p{ideographic} ])/
```
which is the 200-ish (as of Unicode 13.0) CJK characters that aren't ideographs.
There are certain properties that wildcard subpatterns don't currently work with. These are:
```
Bidi Mirroring Glyph
Bidi Paired Bracket
Case Folding
Decomposition Mapping
Equivalent Unified Ideograph
Lowercase Mapping
NFKC Case Fold
Titlecase Mapping
Uppercase Mapping
```
Nor is the `@*unicode\_property*@` form implemented.
Here's a complete example of matching IPV4 internet protocol addresses in any (single) script
```
no warnings 'experimental::uniprop_wildcards';
# Can match a substring, so this intermediate regex needs to have
# context or anchoring in its final use. Using nt=de yields decimal
# digits. When specifying a subset of these, we must include \d to
# prevent things like U+00B2 SUPERSCRIPT TWO from matching
my $zero_through_255 =
qr/ \b (*sr: # All from same sript
(?[ \p{nv=0} & \d ])* # Optional leading zeros
( # Then one of:
\d{1,2} # 0 - 99
| (?[ \p{nv=1} & \d ]) \d{2} # 100 - 199
| (?[ \p{nv=2} & \d ])
( (?[ \p{nv=:[0-4]:} & \d ]) \d # 200 - 249
| (?[ \p{nv=5} & \d ])
(?[ \p{nv=:[0-5]:} & \d ]) # 250 - 255
)
)
)
\b
/x;
my $ipv4 = qr/ \A (*sr: $zero_through_255
(?: [.] $zero_through_255 ) {3}
)
\z
/x;
```
###
User-Defined Character Properties
You can define your own binary character properties by defining subroutines whose names begin with `"In"` or `"Is"`. (The regex sets feature ["(?[ ])" in perlre](perlre#%28%3F%5B-%5D%29) provides an alternative which allows more complex definitions.) The subroutines can be defined in any package. They override any Unicode properties expressed as the same names. The user-defined properties can be used in the regular expression `\p{}` and `\P{}` constructs; if you are using a user-defined property from a package other than the one you are in, you must specify its package in the `\p{}` or `\P{}` construct.
```
# assuming property IsForeign defined in Lang::
package main; # property package name required
if ($txt =~ /\p{Lang::IsForeign}+/) { ... }
package Lang; # property package name not required
if ($txt =~ /\p{IsForeign}+/) { ... }
```
Note that the effect is compile-time and immutable once defined. However, the subroutines are passed a single parameter, which is 0 if case-sensitive matching is in effect and non-zero if caseless matching is in effect. The subroutine may return different values depending on the value of the flag, and one set of values will immutably be in effect for all case-sensitive matches, and the other set for all case-insensitive matches.
Note that if the regular expression is tainted, then Perl will die rather than calling the subroutine when the name of the subroutine is determined by the tainted data.
The subroutines must return a specially-formatted string, with one or more newline-separated lines. Each line must be one of the following:
* A single hexadecimal number denoting a code point to include.
* Two hexadecimal numbers separated by horizontal whitespace (space or tabular characters) denoting a range of code points to include. The second number must not be smaller than the first.
* Something to include, prefixed by `"+"`: a built-in character property (prefixed by `"utf8::"`) or a fully qualified (including package name) user-defined character property, to represent all the characters in that property; two hexadecimal code points for a range; or a single hexadecimal code point.
* Something to exclude, prefixed by `"-"`: an existing character property (prefixed by `"utf8::"`) or a fully qualified (including package name) user-defined character property, to represent all the characters in that property; two hexadecimal code points for a range; or a single hexadecimal code point.
* Something to negate, prefixed `"!"`: an existing character property (prefixed by `"utf8::"`) or a fully qualified (including package name) user-defined character property, to represent all the characters in that property; two hexadecimal code points for a range; or a single hexadecimal code point.
* Something to intersect with, prefixed by `"&"`: an existing character property (prefixed by `"utf8::"`) or a fully qualified (including package name) user-defined character property, for all the characters except the characters in the property; two hexadecimal code points for a range; or a single hexadecimal code point.
For example, to define a property that covers both the Japanese syllabaries (hiragana and katakana), you can define
```
sub InKana {
return <<END;
3040\t309F
30A0\t30FF
END
}
```
Imagine that the here-doc end marker is at the beginning of the line. Now you can use `\p{InKana}` and `\P{InKana}`.
You could also have used the existing block property names:
```
sub InKana {
return <<'END';
+utf8::InHiragana
+utf8::InKatakana
END
}
```
Suppose you wanted to match only the allocated characters, not the raw block ranges: in other words, you want to remove the unassigned characters:
```
sub InKana {
return <<'END';
+utf8::InHiragana
+utf8::InKatakana
-utf8::IsCn
END
}
```
The negation is useful for defining (surprise!) negated classes.
```
sub InNotKana {
return <<'END';
!utf8::InHiragana
-utf8::InKatakana
+utf8::IsCn
END
}
```
This will match all non-Unicode code points, since every one of them is not in Kana. You can use intersection to exclude these, if desired, as this modified example shows:
```
sub InNotKana {
return <<'END';
!utf8::InHiragana
-utf8::InKatakana
+utf8::IsCn
&utf8::Any
END
}
```
`&utf8::Any` must be the last line in the definition.
Intersection is used generally for getting the common characters matched by two (or more) classes. It's important to remember not to use `"&"` for the first set; that would be intersecting with nothing, resulting in an empty set. (Similarly using `"-"` for the first set does nothing).
Unlike non-user-defined `\p{}` property matches, no warning is ever generated if these properties are matched against a non-Unicode code point (see ["Beyond Unicode code points"](#Beyond-Unicode-code-points) below).
###
User-Defined Case Mappings (for serious hackers only)
**This feature has been removed as of Perl 5.16.** The CPAN module `<Unicode::Casing>` provides better functionality without the drawbacks that this feature had. If you are using a Perl earlier than 5.16, this feature was most fully documented in the 5.14 version of this pod: <http://perldoc.perl.org/5.14.0/perlunicode.html#User-Defined-Case-Mappings-%28for-serious-hackers-only%29>
###
Character Encodings for Input and Output
See [Encode](encode).
###
Unicode Regular Expression Support Level
The following list of Unicode supported features for regular expressions describes all features currently directly supported by core Perl. The references to "Level *N*" and the section numbers refer to [UTS#18 "Unicode Regular Expressions"](https://www.unicode.org/reports/tr18), version 18, October 2016.
####
Level 1 - Basic Unicode Support
```
RL1.1 Hex Notation - Done [1]
RL1.2 Properties - Done [2]
RL1.2a Compatibility Properties - Done [3]
RL1.3 Subtraction and Intersection - Done [4]
RL1.4 Simple Word Boundaries - Done [5]
RL1.5 Simple Loose Matches - Done [6]
RL1.6 Line Boundaries - Partial [7]
RL1.7 Supplementary Code Points - Done [8]
```
[1] `\N{U+...}` and `\x{...}`
[2] `\p{...}` `\P{...}`. This requirement is for a minimal list of properties. Perl supports these. See R2.7 for other properties.
[3] Perl has `\d` `\D` `\s` `\S` `\w` `\W` `\X` `[:*prop*:]` `[:^*prop*:]`, plus all the properties specified by <https://www.unicode.org/reports/tr18/#Compatibility_Properties>. These are described above in ["Other Properties"](#Other-Properties)
[4] The regex sets feature `"(?[...])"` starting in v5.18 accomplishes this. See ["(?[ ])" in perlre](perlre#%28%3F%5B-%5D%29).
[5] `\b` `\B` meet most, but not all, the details of this requirement, but `\b{wb}` and `\B{wb}` do, as well as the stricter R2.3.
[6] Note that Perl does Full case-folding in matching, not Simple:
For example `U+1F88` is equivalent to `U+1F00 U+03B9`, instead of just `U+1F80`. This difference matters mainly for certain Greek capital letters with certain modifiers: the Full case-folding decomposes the letter, while the Simple case-folding would map it to a single character.
[7] The reason this is considered to be only partially implemented is that Perl has [`qr/\b{lb}/`](perlrebackslash#%5Cb%7Blb%7D) and `<Unicode::LineBreak>` that are conformant with [UAX#14 "Unicode Line Breaking Algorithm"](https://www.unicode.org/reports/tr14). The regular expression construct provides default behavior, while the heavier-weight module provides customizable line breaking.
But Perl treats `\n` as the start- and end-line delimiter, whereas Unicode specifies more characters that should be so-interpreted.
These are:
```
VT U+000B (\v in C)
FF U+000C (\f)
CR U+000D (\r)
NEL U+0085
LS U+2028
PS U+2029
```
`^` and `$` in regular expression patterns are supposed to match all these, but don't. These characters also don't, but should, affect `<>` `$.`, and script line numbers.
Also, lines should not be split within `CRLF` (i.e. there is no empty line between `\r` and `\n`). For `CRLF`, try the `:crlf` layer (see [PerlIO](perlio)).
[8] UTF-8/UTF-EBDDIC used in Perl allows not only `U+10000` to `U+10FFFF` but also beyond `U+10FFFF`
####
Level 2 - Extended Unicode Support
```
RL2.1 Canonical Equivalents - Retracted [9]
by Unicode
RL2.2 Extended Grapheme Clusters and - Partial [10]
Character Classes with Strings
RL2.3 Default Word Boundaries - Done [11]
RL2.4 Default Case Conversion - Done
RL2.5 Name Properties - Done
RL2.6 Wildcards in Property Values - Partial [12]
RL2.7 Full Properties - Partial [13]
RL2.8 Optional Properties - Partial [14]
```
[9] Unicode has rewritten this portion of UTS#18 to say that getting canonical equivalence (see UAX#15 ["Unicode Normalization Forms"](https://www.unicode.org/reports/tr15)) is basically to be done at the programmer level. Use NFD to write both your regular expressions and text to match them against (you can use <Unicode::Normalize>).
[10] Perl has `\X` and `\b{gcb}`. Unicode has retracted their "Grapheme Cluster Mode", and recently added string properties, which Perl does not yet support.
[11] see [UAX#29 "Unicode Text Segmentation"](https://www.unicode.org/reports/tr29),
[12] see ["Wildcards in Property Values"](#Wildcards-in-Property-Values) above.
[13] Perl supports all the properties in the Unicode Character Database (UCD). It does not yet support the listed properties that come from other Unicode sources.
[14] The only optional property that Perl supports is Named Sequence. None of these properties are in the UCD. ####
Level 3 - Tailored Support
This has been retracted by Unicode.
###
Unicode Encodings
Unicode characters are assigned to *code points*, which are abstract numbers. To use these numbers, various encodings are needed.
* UTF-8
UTF-8 is a variable-length (1 to 4 bytes), byte-order independent encoding. In most of Perl's documentation, including elsewhere in this document, the term "UTF-8" means also "UTF-EBCDIC". But in this section, "UTF-8" refers only to the encoding used on ASCII platforms. It is a superset of 7-bit US-ASCII, so anything encoded in ASCII has the identical representation when encoded in UTF-8.
The following table is from Unicode 3.2.
```
Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
U+0000..U+007F 00..7F
U+0080..U+07FF * C2..DF 80..BF
U+0800..U+0FFF E0 * A0..BF 80..BF
U+1000..U+CFFF E1..EC 80..BF 80..BF
U+D000..U+D7FF ED 80..9F 80..BF
U+D800..U+DFFF +++++ utf16 surrogates, not legal utf8 +++++
U+E000..U+FFFF EE..EF 80..BF 80..BF
U+10000..U+3FFFF F0 * 90..BF 80..BF 80..BF
U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
```
Note the gaps marked by "\*" before several of the byte entries above. These are caused by legal UTF-8 avoiding non-shortest encodings: it is technically possible to UTF-8-encode a single code point in different ways, but that is explicitly forbidden, and the shortest possible encoding should always be used (and that is what Perl does).
Another way to look at it is via bits:
```
Code Points 1st Byte 2nd Byte 3rd Byte 4th Byte
0aaaaaaa 0aaaaaaa
00000bbbbbaaaaaa 110bbbbb 10aaaaaa
ccccbbbbbbaaaaaa 1110cccc 10bbbbbb 10aaaaaa
00000dddccccccbbbbbbaaaaaa 11110ddd 10cccccc 10bbbbbb 10aaaaaa
```
As you can see, the continuation bytes all begin with `"10"`, and the leading bits of the start byte tell how many bytes there are in the encoded character.
The original UTF-8 specification allowed up to 6 bytes, to allow encoding of numbers up to `0x7FFF_FFFF`. Perl continues to allow those, and has extended that up to 13 bytes to encode code points up to what can fit in a 64-bit word. However, Perl will warn if you output any of these as being non-portable; and under strict UTF-8 input protocols, they are forbidden. In addition, it is now illegal to use a code point larger than what a signed integer variable on your system can hold. On 32-bit ASCII systems, this means `0x7FFF_FFFF` is the legal maximum (much higher on 64-bit systems).
* UTF-EBCDIC
Like UTF-8, but EBCDIC-safe, in the way that UTF-8 is ASCII-safe. This means that all the basic characters (which includes all those that have ASCII equivalents (like `"A"`, `"0"`, `"%"`, *etc.*) are the same in both EBCDIC and UTF-EBCDIC.)
UTF-EBCDIC is used on EBCDIC platforms. It generally requires more bytes to represent a given code point than UTF-8 does; the largest Unicode code points take 5 bytes to represent (instead of 4 in UTF-8), and, extended for 64-bit words, it uses 14 bytes instead of 13 bytes in UTF-8.
* UTF-16, UTF-16BE, UTF-16LE, Surrogates, and `BOM`'s (Byte Order Marks)
The followings items are mostly for reference and general Unicode knowledge, Perl doesn't use these constructs internally.
Like UTF-8, UTF-16 is a variable-width encoding, but where UTF-8 uses 8-bit code units, UTF-16 uses 16-bit code units. All code points occupy either 2 or 4 bytes in UTF-16: code points `U+0000..U+FFFF` are stored in a single 16-bit unit, and code points `U+10000..U+10FFFF` in two 16-bit units. The latter case is using *surrogates*, the first 16-bit unit being the *high surrogate*, and the second being the *low surrogate*.
Surrogates are code points set aside to encode the `U+10000..U+10FFFF` range of Unicode code points in pairs of 16-bit units. The *high surrogates* are the range `U+D800..U+DBFF` and the *low surrogates* are the range `U+DC00..U+DFFF`. The surrogate encoding is
```
$hi = ($uni - 0x10000) / 0x400 + 0xD800;
$lo = ($uni - 0x10000) % 0x400 + 0xDC00;
```
and the decoding is
```
$uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
```
Because of the 16-bitness, UTF-16 is byte-order dependent. UTF-16 itself can be used for in-memory computations, but if storage or transfer is required either UTF-16BE (big-endian) or UTF-16LE (little-endian) encodings must be chosen.
This introduces another problem: what if you just know that your data is UTF-16, but you don't know which endianness? Byte Order Marks, or `BOM`'s, are a solution to this. A special character has been reserved in Unicode to function as a byte order marker: the character with the code point `U+FEFF` is the `BOM`.
The trick is that if you read a `BOM`, you will know the byte order, since if it was written on a big-endian platform, you will read the bytes `0xFE 0xFF`, but if it was written on a little-endian platform, you will read the bytes `0xFF 0xFE`. (And if the originating platform was writing in ASCII platform UTF-8, you will read the bytes `0xEF 0xBB 0xBF`.)
The way this trick works is that the character with the code point `U+FFFE` is not supposed to be in input streams, so the sequence of bytes `0xFF 0xFE` is unambiguously "`BOM`, represented in little-endian format" and cannot be `U+FFFE`, represented in big-endian format".
Surrogates have no meaning in Unicode outside their use in pairs to represent other code points. However, Perl allows them to be represented individually internally, for example by saying `chr(0xD801)`, so that all code points, not just those valid for open interchange, are representable. Unicode does define semantics for them, such as their `["General\_Category"](#General_Category)` is `"Cs"`. But because their use is somewhat dangerous, Perl will warn (using the warning category `"surrogate"`, which is a sub-category of `"utf8"`) if an attempt is made to do things like take the lower case of one, or match case-insensitively, or to output them. (But don't try this on Perls before 5.14.)
* UTF-32, UTF-32BE, UTF-32LE
The UTF-32 family is pretty much like the UTF-16 family, except that the units are 32-bit, and therefore the surrogate scheme is not needed. UTF-32 is a fixed-width encoding. The `BOM` signatures are `0x00 0x00 0xFE 0xFF` for BE and `0xFF 0xFE 0x00 0x00` for LE.
* UCS-2, UCS-4
Legacy, fixed-width encodings defined by the ISO 10646 standard. UCS-2 is a 16-bit encoding. Unlike UTF-16, UCS-2 is not extensible beyond `U+FFFF`, because it does not use surrogates. UCS-4 is a 32-bit encoding, functionally identical to UTF-32 (the difference being that UCS-4 forbids neither surrogates nor code points larger than `0x10_FFFF`).
* UTF-7
A seven-bit safe (non-eight-bit) encoding, which is useful if the transport or storage is not eight-bit safe. Defined by RFC 2152.
###
Noncharacter code points
66 code points are set aside in Unicode as "noncharacter code points". These all have the `Unassigned` (`Cn`) `["General\_Category"](#General_Category)`, and no character will ever be assigned to any of them. They are the 32 code points between `U+FDD0` and `U+FDEF` inclusive, and the 34 code points:
```
U+FFFE U+FFFF
U+1FFFE U+1FFFF
U+2FFFE U+2FFFF
...
U+EFFFE U+EFFFF
U+FFFFE U+FFFFF
U+10FFFE U+10FFFF
```
Until Unicode 7.0, the noncharacters were "**forbidden** for use in open interchange of Unicode text data", so that code that processed those streams could use these code points as sentinels that could be mixed in with character data, and would always be distinguishable from that data. (Emphasis above and in the next paragraph are added in this document.)
Unicode 7.0 changed the wording so that they are "**not recommended** for use in open interchange of Unicode text data". The 7.0 Standard goes on to say:
"If a noncharacter is received in open interchange, an application is not required to interpret it in any way. It is good practice, however, to recognize it as a noncharacter and to take appropriate action, such as replacing it with `U+FFFD` replacement character, to indicate the problem in the text. It is not recommended to simply delete noncharacter code points from such text, because of the potential security issues caused by deleting uninterpreted characters. (See conformance clause C7 in Section 3.2, Conformance Requirements, and [Unicode Technical Report #36, "Unicode Security Considerations"](https://www.unicode.org/reports/tr36/#Substituting_for_Ill_Formed_Subsequences))."
This change was made because it was found that various commercial tools like editors, or for things like source code control, had been written so that they would not handle program files that used these code points, effectively precluding their use almost entirely! And that was never the intent. They've always been meant to be usable within an application, or cooperating set of applications, at will.
If you're writing code, such as an editor, that is supposed to be able to handle any Unicode text data, then you shouldn't be using these code points yourself, and instead allow them in the input. If you need sentinels, they should instead be something that isn't legal Unicode. For UTF-8 data, you can use the bytes 0xC1 and 0xC2 as sentinels, as they never appear in well-formed UTF-8. (There are equivalents for UTF-EBCDIC). You can also store your Unicode code points in integer variables and use negative values as sentinels.
If you're not writing such a tool, then whether you accept noncharacters as input is up to you (though the Standard recommends that you not). If you do strict input stream checking with Perl, these code points continue to be forbidden. This is to maintain backward compatibility (otherwise potential security holes could open up, as an unsuspecting application that was written assuming the noncharacters would be filtered out before getting to it, could now, without warning, start getting them). To do strict checking, you can use the layer `:encoding('UTF-8')`.
Perl continues to warn (using the warning category `"nonchar"`, which is a sub-category of `"utf8"`) if an attempt is made to output noncharacters.
###
Beyond Unicode code points
The maximum Unicode code point is `U+10FFFF`, and Unicode only defines operations on code points up through that. But Perl works on code points up to the maximum permissible signed number available on the platform. However, Perl will not accept these from input streams unless lax rules are being used, and will warn (using the warning category `"non_unicode"`, which is a sub-category of `"utf8"`) if any are output.
Since Unicode rules are not defined on these code points, if a Unicode-defined operation is done on them, Perl uses what we believe are sensible rules, while generally warning, using the `"non_unicode"` category. For example, `uc("\x{11_0000}")` will generate such a warning, returning the input parameter as its result, since Perl defines the uppercase of every non-Unicode code point to be the code point itself. (All the case changing operations, not just uppercasing, work this way.)
The situation with matching Unicode properties in regular expressions, the `\p{}` and `\P{}` constructs, against these code points is not as clear cut, and how these are handled has changed as we've gained experience.
One possibility is to treat any match against these code points as undefined. But since Perl doesn't have the concept of a match being undefined, it converts this to failing or `FALSE`. This is almost, but not quite, what Perl did from v5.14 (when use of these code points became generally reliable) through v5.18. The difference is that Perl treated all `\p{}` matches as failing, but all `\P{}` matches as succeeding.
One problem with this is that it leads to unexpected, and confusing results in some cases:
```
chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Failed on <= v5.18
chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Failed! on <= v5.18
```
That is, it treated both matches as undefined, and converted that to false (raising a warning on each). The first case is the expected result, but the second is likely counterintuitive: "How could both be false when they are complements?" Another problem was that the implementation optimized many Unicode property matches down to already existing simpler, faster operations, which don't raise the warning. We chose to not forgo those optimizations, which help the vast majority of matches, just to generate a warning for the unlikely event that an above-Unicode code point is being matched against.
As a result of these problems, starting in v5.20, what Perl does is to treat non-Unicode code points as just typical unassigned Unicode characters, and matches accordingly. (Note: Unicode has atypical unassigned code points. For example, it has noncharacter code points, and ones that, when they do get assigned, are destined to be written Right-to-left, as Arabic and Hebrew are. Perl assumes that no non-Unicode code point has any atypical properties.)
Perl, in most cases, will raise a warning when matching an above-Unicode code point against a Unicode property when the result is `TRUE` for `\p{}`, and `FALSE` for `\P{}`. For example:
```
chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails, no warning
chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Succeeds, with warning
```
In both these examples, the character being matched is non-Unicode, so Unicode doesn't define how it should match. It clearly isn't an ASCII hex digit, so the first example clearly should fail, and so it does, with no warning. But it is arguable that the second example should have an undefined, hence `FALSE`, result. So a warning is raised for it.
Thus the warning is raised for many fewer cases than in earlier Perls, and only when what the result is could be arguable. It turns out that none of the optimizations made by Perl (or are ever likely to be made) cause the warning to be skipped, so it solves both problems of Perl's earlier approach. The most commonly used property that is affected by this change is `\p{Unassigned}` which is a short form for `\p{General_Category=Unassigned}`. Starting in v5.20, all non-Unicode code points are considered `Unassigned`. In earlier releases the matches failed because the result was considered undefined.
The only place where the warning is not raised when it might ought to have been is if optimizations cause the whole pattern match to not even be attempted. For example, Perl may figure out that for a string to match a certain regular expression pattern, the string has to contain the substring `"foobar"`. Before attempting the match, Perl may look for that substring, and if not found, immediately fail the match without actually trying it; so no warning gets generated even if the string contains an above-Unicode code point.
This behavior is more "Do what I mean" than in earlier Perls for most applications. But it catches fewer issues for code that needs to be strictly Unicode compliant. Therefore there is an additional mode of operation available to accommodate such code. This mode is enabled if a regular expression pattern is compiled within the lexical scope where the `"non_unicode"` warning class has been made fatal, say by:
```
use warnings FATAL => "non_unicode"
```
(see <warnings>). In this mode of operation, Perl will raise the warning for all matches against a non-Unicode code point (not just the arguable ones), and it skips the optimizations that might cause the warning to not be output. (It currently still won't warn if the match isn't even attempted, like in the `"foobar"` example above.)
In summary, Perl now normally treats non-Unicode code points as typical Unicode unassigned code points for regular expression matches, raising a warning only when it is arguable what the result should be. However, if this warning has been made fatal, it isn't skipped.
There is one exception to all this. `\p{All}` looks like a Unicode property, but it is a Perl extension that is defined to be true for all possible code points, Unicode or not, so no warning is ever generated when matching this against a non-Unicode code point. (Prior to v5.20, it was an exact synonym for `\p{Any}`, matching code points `0` through `0x10FFFF`.)
###
Security Implications of Unicode
First, read [Unicode Security Considerations](https://www.unicode.org/reports/tr36).
Also, note the following:
* Malformed UTF-8
UTF-8 is very structured, so many combinations of bytes are invalid. In the past, Perl tried to soldier on and make some sense of invalid combinations, but this can lead to security holes, so now, if the Perl core needs to process an invalid combination, it will either raise a fatal error, or will replace those bytes by the sequence that forms the Unicode REPLACEMENT CHARACTER, for which purpose Unicode created it.
Every code point can be represented by more than one possible syntactically valid UTF-8 sequence. Early on, both Unicode and Perl considered any of these to be valid, but now, all sequences longer than the shortest possible one are considered to be malformed.
Unicode considers many code points to be illegal, or to be avoided. Perl generally accepts them, once they have passed through any input filters that may try to exclude them. These have been discussed above (see "Surrogates" under UTF-16 in ["Unicode Encodings"](#Unicode-Encodings), ["Noncharacter code points"](#Noncharacter-code-points), and ["Beyond Unicode code points"](#Beyond-Unicode-code-points)).
* Regular expression pattern matching may surprise you if you're not accustomed to Unicode. Starting in Perl 5.14, several pattern modifiers are available to control this, called the character set modifiers. Details are given in ["Character set modifiers" in perlre](perlre#Character-set-modifiers).
As discussed elsewhere, Perl has one foot (two hooves?) planted in each of two worlds: the old world of ASCII and single-byte locales, and the new world of Unicode, upgrading when necessary. If your legacy code does not explicitly use Unicode, no automatic switch-over to Unicode should happen.
###
Unicode in Perl on EBCDIC
Unicode is supported on EBCDIC platforms. See <perlebcdic>.
Unless ASCII vs. EBCDIC issues are specifically being discussed, references to UTF-8 encoding in this document and elsewhere should be read as meaning UTF-EBCDIC on EBCDIC platforms. See ["Unicode and UTF" in perlebcdic](perlebcdic#Unicode-and-UTF).
Because UTF-EBCDIC is so similar to UTF-8, the differences are mostly hidden from you; `use utf8` (and NOT something like `use utfebcdic`) declares the script is in the platform's "native" 8-bit encoding of Unicode. (Similarly for the `":utf8"` layer.)
### Locales
See ["Unicode and UTF-8" in perllocale](perllocale#Unicode-and-UTF-8)
###
When Unicode Does Not Happen
There are still many places where Unicode (in some encoding or another) could be given as arguments or received as results, or both in Perl, but it is not, in spite of Perl having extensive ways to input and output in Unicode, and a few other "entry points" like the `@ARGV` array (which can sometimes be interpreted as UTF-8).
The following are such interfaces. Also, see ["The "Unicode Bug""](#The-%22Unicode-Bug%22). For all of these interfaces Perl currently (as of v5.16.0) simply assumes byte strings both as arguments and results, or UTF-8 strings if the (deprecated) `encoding` pragma has been used.
One reason that Perl does not attempt to resolve the role of Unicode in these situations is that the answers are highly dependent on the operating system and the file system(s). For example, whether filenames can be in Unicode and in exactly what kind of encoding, is not exactly a portable concept. Similarly for `qx` and `system`: how well will the "command-line interface" (and which of them?) handle Unicode?
* `chdir`, `chmod`, `chown`, `chroot`, `exec`, `link`, `lstat`, `mkdir`, `rename`, `rmdir`, `stat`, `symlink`, `truncate`, `unlink`, `utime`, `-X`
* `%ENV`
* `glob` (aka the `<*>`)
* `open`, `opendir`, `sysopen`
* `qx` (aka the backtick operator), `system`
* `readdir`, `readlink`
###
The "Unicode Bug"
The term, "Unicode bug" has been applied to an inconsistency with the code points in the `Latin-1 Supplement` block, that is, between 128 and 255. Without a locale specified, unlike all other characters or code points, these characters can have very different semantics depending on the rules in effect. (Characters whose code points are above 255 force Unicode rules; whereas the rules for ASCII characters are the same under both ASCII and Unicode rules.)
Under Unicode rules, these upper-Latin1 characters are interpreted as Unicode code points, which means they have the same semantics as Latin-1 (ISO-8859-1) and C1 controls.
As explained in ["ASCII Rules versus Unicode Rules"](#ASCII-Rules-versus-Unicode-Rules), under ASCII rules, they are considered to be unassigned characters.
This can lead to unexpected results. For example, a string's semantics can suddenly change if a code point above 255 is appended to it, which changes the rules from ASCII to Unicode. As an example, consider the following program and its output:
```
$ perl -le'
no feature "unicode_strings";
$s1 = "\xC2";
$s2 = "\x{2660}";
for ($s1, $s2, $s1.$s2) {
print /\w/ || 0;
}
'
0
0
1
```
If there's no `\w` in `s1` nor in `s2`, why does their concatenation have one?
This anomaly stems from Perl's attempt to not disturb older programs that didn't use Unicode, along with Perl's desire to add Unicode support seamlessly. But the result turned out to not be seamless. (By the way, you can choose to be warned when things like this happen. See `<encoding::warnings>`.)
[`use feature 'unicode_strings'`](feature#The-%27unicode_strings%27-feature) was added, starting in Perl v5.12, to address this problem. It affects these things:
* Changing the case of a scalar, that is, using `uc()`, `ucfirst()`, `lc()`, and `lcfirst()`, or `\L`, `\U`, `\u` and `\l` in double-quotish contexts, such as regular expression substitutions.
Under `unicode_strings` starting in Perl 5.12.0, Unicode rules are generally used. See ["lc" in perlfunc](perlfunc#lc) for details on how this works in combination with various other pragmas.
* Using caseless (`/i`) regular expression matching.
Starting in Perl 5.14.0, regular expressions compiled within the scope of `unicode_strings` use Unicode rules even when executed or compiled into larger regular expressions outside the scope.
* Matching any of several properties in regular expressions.
These properties are `\b` (without braces), `\B` (without braces), `\s`, `\S`, `\w`, `\W`, and all the Posix character classes *except* `[[:ascii:]]`.
Starting in Perl 5.14.0, regular expressions compiled within the scope of `unicode_strings` use Unicode rules even when executed or compiled into larger regular expressions outside the scope.
* In `quotemeta` or its inline equivalent `\Q`.
Starting in Perl 5.16.0, consistent quoting rules are used within the scope of `unicode_strings`, as described in ["quotemeta" in perlfunc](perlfunc#quotemeta). Prior to that, or outside its scope, no code points above 127 are quoted in UTF-8 encoded strings, but in byte encoded strings, code points between 128-255 are always quoted.
* In the `..` or [range](perlop#Range-Operators) operator.
Starting in Perl 5.26.0, the range operator on strings treats their lengths consistently within the scope of `unicode_strings`. Prior to that, or outside its scope, it could produce strings whose length in characters exceeded that of the right-hand side, where the right-hand side took up more bytes than the correct range endpoint.
* In [`split`'s special-case whitespace splitting](perlfunc#split).
Starting in Perl 5.28.0, the `split` function with a pattern specified as a string containing a single space handles whitespace characters consistently within the scope of `unicode_strings`. Prior to that, or outside its scope, characters that are whitespace according to Unicode rules but not according to ASCII rules were treated as field contents rather than field separators when they appear in byte-encoded strings.
You can see from the above that the effect of `unicode_strings` increased over several Perl releases. (And Perl's support for Unicode continues to improve; it's best to use the latest available release in order to get the most complete and accurate results possible.) Note that `unicode_strings` is automatically chosen if you `use v5.12` or higher.
For Perls earlier than those described above, or when a string is passed to a function outside the scope of `unicode_strings`, see the next section.
###
Forcing Unicode in Perl (Or Unforcing Unicode in Perl)
Sometimes (see ["When Unicode Does Not Happen"](#When-Unicode-Does-Not-Happen) or ["The "Unicode Bug""](#The-%22Unicode-Bug%22)) there are situations where you simply need to force a byte string into UTF-8, or vice versa. The standard module [Encode](encode) can be used for this, or the low-level calls [`utf8::upgrade($bytestring)`](utf8#Utility-functions) and [`utf8::downgrade($utf8string[, FAIL_OK])`](utf8#Utility-functions).
Note that `utf8::downgrade()` can fail if the string contains characters that don't fit into a byte.
Calling either function on a string that already is in the desired state is a no-op.
["ASCII Rules versus Unicode Rules"](#ASCII-Rules-versus-Unicode-Rules) gives all the ways that a string is made to use Unicode rules.
###
Using Unicode in XS
See ["Unicode Support" in perlguts](perlguts#Unicode-Support) for an introduction to Unicode at the XS level, and ["Unicode Support" in perlapi](perlapi#Unicode-Support) for the API details.
###
Hacking Perl to work on earlier Unicode versions (for very serious hackers only)
Perl by default comes with the latest supported Unicode version built-in, but the goal is to allow you to change to use any earlier one. In Perls v5.20 and v5.22, however, the earliest usable version is Unicode 5.1. Perl v5.18 and v5.24 are able to handle all earlier versions.
Download the files in the desired version of Unicode from the Unicode web site <https://www.unicode.org>). These should replace the existing files in *lib/unicore* in the Perl source tree. Follow the instructions in *README.perl* in that directory to change some of their names, and then build perl (see [INSTALL](install)).
###
Porting code from perl-5.6.X
Perls starting in 5.8 have a different Unicode model from 5.6. In 5.6 the programmer was required to use the `utf8` pragma to declare that a given scope expected to deal with Unicode data and had to make sure that only Unicode data were reaching that scope. If you have code that is working with 5.6, you will need some of the following adjustments to your code. The examples are written such that the code will continue to work under 5.6, so you should be safe to try them out.
* A filehandle that should read or write UTF-8
```
if ($] > 5.008) {
binmode $fh, ":encoding(UTF-8)";
}
```
* A scalar that is going to be passed to some extension
Be it `Compress::Zlib`, `Apache::Request` or any extension that has no mention of Unicode in the manpage, you need to make sure that the UTF8 flag is stripped off. Note that at the time of this writing (January 2012) the mentioned modules are not UTF-8-aware. Please check the documentation to verify if this is still true.
```
if ($] > 5.008) {
require Encode;
$val = Encode::encode("UTF-8", $val); # make octets
}
```
* A scalar we got back from an extension
If you believe the scalar comes back as UTF-8, you will most likely want the UTF8 flag restored:
```
if ($] > 5.008) {
require Encode;
$val = Encode::decode("UTF-8", $val);
}
```
* Same thing, if you are really sure it is UTF-8
```
if ($] > 5.008) {
require Encode;
Encode::_utf8_on($val);
}
```
* A wrapper for [DBI](dbi) `fetchrow_array` and `fetchrow_hashref`
When the database contains only UTF-8, a wrapper function or method is a convenient way to replace all your `fetchrow_array` and `fetchrow_hashref` calls. A wrapper function will also make it easier to adapt to future enhancements in your database driver. Note that at the time of this writing (January 2012), the DBI has no standardized way to deal with UTF-8 data. Please check the [DBI documentation](dbi) to verify if that is still true.
```
sub fetchrow {
# $what is one of fetchrow_{array,hashref}
my($self, $sth, $what) = @_;
if ($] < 5.008) {
return $sth->$what;
} else {
require Encode;
if (wantarray) {
my @arr = $sth->$what;
for (@arr) {
defined && /[^\000-\177]/ && Encode::_utf8_on($_);
}
return @arr;
} else {
my $ret = $sth->$what;
if (ref $ret) {
for my $k (keys %$ret) {
defined
&& /[^\000-\177]/
&& Encode::_utf8_on($_) for $ret->{$k};
}
return $ret;
} else {
defined && /[^\000-\177]/ && Encode::_utf8_on($_) for $ret;
return $ret;
}
}
}
}
```
* A large scalar that you know can only contain ASCII
Scalars that contain only ASCII and are marked as UTF-8 are sometimes a drag to your program. If you recognize such a situation, just remove the UTF8 flag:
```
utf8::downgrade($val) if $] > 5.008;
```
BUGS
----
See also ["The "Unicode Bug""](#The-%22Unicode-Bug%22) above.
###
Interaction with Extensions
When Perl exchanges data with an extension, the extension should be able to understand the UTF8 flag and act accordingly. If the extension doesn't recognize that flag, it's likely that the extension will return incorrectly-flagged data.
So if you're working with Unicode data, consult the documentation of every module you're using if there are any issues with Unicode data exchange. If the documentation does not talk about Unicode at all, suspect the worst and probably look at the source to learn how the module is implemented. Modules written completely in Perl shouldn't cause problems. Modules that directly or indirectly access code written in other programming languages are at risk.
For affected functions, the simple strategy to avoid data corruption is to always make the encoding of the exchanged data explicit. Choose an encoding that you know the extension can handle. Convert arguments passed to the extensions to that encoding and convert results back from that encoding. Write wrapper functions that do the conversions for you, so you can later change the functions when the extension catches up.
To provide an example, let's say the popular `Foo::Bar::escape_html` function doesn't deal with Unicode data yet. The wrapper function would convert the argument to raw UTF-8 and convert the result back to Perl's internal representation like so:
```
sub my_escape_html ($) {
my($what) = shift;
return unless defined $what;
Encode::decode("UTF-8", Foo::Bar::escape_html(
Encode::encode("UTF-8", $what)));
}
```
Sometimes, when the extension does not convert data but just stores and retrieves it, you will be able to use the otherwise dangerous [`Encode::_utf8_on()`](encode#_utf8_on) function. Let's say the popular `Foo::Bar` extension, written in C, provides a `param` method that lets you store and retrieve data according to these prototypes:
```
$self->param($name, $value); # set a scalar
$value = $self->param($name); # retrieve a scalar
```
If it does not yet provide support for any encoding, one could write a derived class with such a `param` method:
```
sub param {
my($self,$name,$value) = @_;
utf8::upgrade($name); # make sure it is UTF-8 encoded
if (defined $value) {
utf8::upgrade($value); # make sure it is UTF-8 encoded
return $self->SUPER::param($name,$value);
} else {
my $ret = $self->SUPER::param($name);
Encode::_utf8_on($ret); # we know, it is UTF-8 encoded
return $ret;
}
}
```
Some extensions provide filters on data entry/exit points, such as `DB_File::filter_store_key` and family. Look out for such filters in the documentation of your extensions; they can make the transition to Unicode data much easier.
### Speed
Some functions are slower when working on UTF-8 encoded strings than on byte encoded strings. All functions that need to hop over characters such as `length()`, `substr()` or `index()`, or matching regular expressions can work **much** faster when the underlying data are byte-encoded.
In Perl 5.8.0 the slowness was often quite spectacular; in Perl 5.8.1 a caching scheme was introduced which improved the situation. In general, operations with UTF-8 encoded strings are still slower. As an example, the Unicode properties (character classes) like `\p{Nd}` are known to be quite a bit slower (5-20 times) than their simpler counterparts like `[0-9]` (then again, there are hundreds of Unicode characters matching `Nd` compared with the 10 ASCII characters matching `[0-9]`).
SEE ALSO
---------
<perlunitut>, <perluniintro>, <perluniprops>, [Encode](encode), <open>, <utf8>, <bytes>, <perlretut>, ["${^UNICODE}" in perlvar](perlvar#%24%7B%5EUNICODE%7D), <https://www.unicode.org/reports/tr44>).
| programming_docs |
Subsets and Splits